]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
/MAP and /LINKS added back (do not use - needs testing)
[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 "connection.h"
45 #include "users.h"
46 #include "servers.h"
47 #include "ctables.h"
48 #include "globals.h"
49 #include "modules.h"
50 #include "dynamic.h"
51 #include "wildcard.h"
52
53 #ifdef GCC3
54 #define nspace __gnu_cxx
55 #else
56 #define nspace std
57 #endif
58
59 int LogLevel = DEFAULT;
60 char ServerName[MAXBUF];
61 char Network[MAXBUF];
62 char ServerDesc[MAXBUF];
63 char AdminName[MAXBUF];
64 char AdminEmail[MAXBUF];
65 char AdminNick[MAXBUF];
66 char diepass[MAXBUF];
67 char restartpass[MAXBUF];
68 char motd[MAXBUF];
69 char rules[MAXBUF];
70 char list[MAXBUF];
71 char PrefixQuit[MAXBUF];
72 char DieValue[MAXBUF];
73 int debugging =  0;
74 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
75 int WHOWAS_MAX = 100;  // default 100 people maximum in the WHOWAS list
76 int DieDelay  =  5;
77 time_t startup_time = time(NULL);
78 int NetBufferSize = 10240; // NetBufferSize used as the buffer size for all read() ops
79 time_t nb_start = 0;
80
81 extern vector<Module*> modules;
82 std::vector<std::string> module_names;
83 extern vector<ircd_module*> factory;
84 std::vector<int> fd_reap;
85
86 extern int MODCOUNT;
87
88 bool nofork = false;
89
90 namespace nspace
91 {
92         template<> struct nspace::hash<in_addr>
93         {
94                 size_t operator()(const struct in_addr &a) const
95                 {
96                         size_t q;
97                         memcpy(&q,&a,sizeof(size_t));
98                         return q;
99                 }
100         };
101
102         template<> struct nspace::hash<string>
103         {
104                 size_t operator()(const string &s) const
105                 {
106                         char a[MAXBUF];
107                         static struct hash<const char *> strhash;
108                         strcpy(a,s.c_str());
109                         strlower(a);
110                         return strhash(a);
111                 }
112         };
113 }       
114
115
116 struct StrHashComp
117 {
118
119         bool operator()(const string& s1, const string& s2) const
120         {
121                 char a[MAXBUF],b[MAXBUF];
122                 strcpy(a,s1.c_str());
123                 strcpy(b,s2.c_str());
124                 return (strcasecmp(a,b) == 0);
125         }
126
127 };
128
129 struct InAddr_HashComp
130 {
131
132         bool operator()(const in_addr &s1, const in_addr &s2) const
133         {
134                 size_t q;
135                 size_t p;
136                 
137                 memcpy(&q,&s1,sizeof(size_t));
138                 memcpy(&p,&s2,sizeof(size_t));
139                 
140                 return (q == p);
141         }
142
143 };
144
145
146 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, StrHashComp> user_hash;
147 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, StrHashComp> chan_hash;
148 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, InAddr_HashComp> address_cache;
149 typedef std::deque<command_t> command_table;
150
151 serverrec* me[32];
152
153 FILE *log_file;
154
155 user_hash clientlist;
156 chan_hash chanlist;
157 user_hash whowas;
158 command_table cmdlist;
159 file_cache MOTD;
160 file_cache RULES;
161 address_cache IP;
162
163 ClassVector Classes;
164
165 struct linger linger = { 0 };
166 char bannerBuffer[MAXBUF];
167 int boundPortCount = 0;
168 int portCount = 0, UDPportCount = 0, ports[MAXSOCKS];
169 int defaultRoute = 0;
170
171 connection C;
172
173 long MyKey = C.GenKey();
174
175 /* prototypes */
176
177 int has_channel(userrec *u, chanrec *c);
178 int usercount(chanrec *c);
179 int usercount_i(chanrec *c);
180 void update_stats_l(int fd,int data_out);
181 char* Passwd(userrec *user);
182 bool IsDenied(userrec *user);
183 void AddWhoWas(userrec* u);
184
185 std::vector<long> auth_cookies;
186 std::stringstream config_f(stringstream::in | stringstream::out);
187
188 void safedelete(userrec *p)
189 {
190         if (p)
191         {
192                 log(DEBUG,"deleting %s %s %s %s",p->nick,p->ident,p->dhost,p->fullname);
193                 log(DEBUG,"safedelete(userrec*): pointer is safe to delete");
194                 delete p;
195                 p = NULL;
196         }
197         else
198         {
199                 log(DEBUG,"safedelete(userrec*): unsafe pointer operation squished");
200         }
201 }
202
203 void safedelete(chanrec *p)
204 {
205         if (p)
206         {
207                 delete p;
208                 p = NULL;
209                 log(DEBUG,"safedelete(chanrec*): pointer is safe to delete");
210         }
211         else
212         {
213                 log(DEBUG,"safedelete(chanrec*): unsafe pointer operation squished");
214         }
215 }
216
217
218 void tidystring(char* str)
219 {
220         // strips out double spaces before a : parameter
221         
222         char temp[MAXBUF];
223         bool go_again = true;
224         
225         if (!str)
226         {
227                 return;
228         }
229         
230         while ((str[0] == ' ') && (strlen(str)>0))
231         {
232                 str++;
233         }
234         
235         while (go_again)
236         {
237                 bool noparse = false;
238                 int t = 0, a = 0;
239                 go_again = false;
240                 while (a < strlen(str))
241                 {
242                         if ((a<strlen(str)-1) && (noparse==false))
243                         {
244                                 if ((str[a] == ' ') && (str[a+1] == ' '))
245                                 {
246                                         log(DEBUG,"Tidied extra space out of string: %s",str);
247                                         go_again = true;
248                                         a++;
249                                 }
250                         }
251                         
252                         if (a<strlen(str)-1)
253                         {
254                                 if ((str[a] == ' ') && (str[a+1] == ':'))
255                                 {
256                                         noparse = true;
257                                 }
258                         }
259                         
260                         temp[t++] = str[a++];
261                 }
262                 temp[t] = '\0';
263                 strncpy(str,temp,MAXBUF);
264         }
265 }
266
267 /* chop a string down to 512 characters and preserve linefeed (irc max
268  * line length) */
269
270 void chop(char* str)
271 {
272   if (!str)
273   {
274         log(DEBUG,"ERROR! Null string passed to chop()!");
275         return;
276   }
277   string temp = str;
278   FOREACH_MOD OnServerRaw(temp,false);
279   const char* str2 = temp.c_str();
280   sprintf(str,"%s",str2);
281   
282
283   if (strlen(str) >= 512)
284   {
285         str[509] = '\r';
286         str[510] = '\n';
287         str[511] = '\0';
288   }
289 }
290
291
292 std::string getservername()
293 {
294         return ServerName;
295 }
296
297 std::string getserverdesc()
298 {
299         return ServerDesc;
300 }
301
302 std::string getnetworkname()
303 {
304         return Network;
305 }
306
307 std::string getadminname()
308 {
309         return AdminName;
310 }
311
312 std::string getadminemail()
313 {
314         return AdminEmail;
315 }
316
317 std::string getadminnick()
318 {
319         return AdminNick;
320 }
321
322 void log(int level,char *text, ...)
323 {
324         char textbuffer[MAXBUF];
325         va_list argsPtr;
326         time_t rawtime;
327         struct tm * timeinfo;
328         if (level < LogLevel)
329                 return;
330
331         time(&rawtime);
332         timeinfo = localtime (&rawtime);
333
334         if (log_file)
335         {
336                 char b[MAXBUF];
337                 va_start (argsPtr, text);
338                 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
339                 va_end(argsPtr);
340                 strcpy(b,asctime(timeinfo));
341                 b[strlen(b)-1] = ':';
342                 fprintf(log_file,"%s %s\n",b,textbuffer);
343                 if (nofork)
344                 {
345                         // nofork enabled? display it on terminal too
346                         printf("%s %s\n",b,textbuffer);
347                 }
348         }
349 }
350
351 void readfile(file_cache &F, const char* fname)
352 {
353   FILE* file;
354   char linebuf[MAXBUF];
355
356   log(DEBUG,"readfile: loading %s",fname);
357   F.clear();
358   file =  fopen(fname,"r");
359   if (file)
360   {
361         while (!feof(file))
362         {
363                 fgets(linebuf,sizeof(linebuf),file);
364                 linebuf[strlen(linebuf)-1]='\0';
365                 if (!strcmp(linebuf,""))
366                 {
367                         strcpy(linebuf,"  ");
368                 }
369                 if (!feof(file))
370                 {
371                         F.push_back(linebuf);
372                 }
373         }
374         fclose(file);
375   }
376   else
377   {
378           log(DEBUG,"readfile: failed to load file: %s",fname);
379   }
380   log(DEBUG,"readfile: loaded %s, %d lines",fname,F.size());
381 }
382
383 void ReadConfig(void)
384 {
385   char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF];
386   ConnectClass c;
387
388   LoadConf(CONFIG_FILE,&config_f);
389   
390   ConfValue("server","name",0,ServerName,&config_f);
391   ConfValue("server","description",0,ServerDesc,&config_f);
392   ConfValue("server","network",0,Network,&config_f);
393   ConfValue("admin","name",0,AdminName,&config_f);
394   ConfValue("admin","email",0,AdminEmail,&config_f);
395   ConfValue("admin","nick",0,AdminNick,&config_f);
396   ConfValue("files","motd",0,motd,&config_f);
397   ConfValue("files","rules",0,rules,&config_f);
398   ConfValue("power","diepass",0,diepass,&config_f);
399   ConfValue("power","pause",0,pauseval,&config_f);
400   ConfValue("power","restartpass",0,restartpass,&config_f);
401   ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
402   ConfValue("die","value",0,DieValue,&config_f);
403   ConfValue("options","loglevel",0,dbg,&config_f);
404   ConfValue("options","netbuffersize",0,NB,&config_f);
405   NetBufferSize = atoi(NB);
406   if ((!NetBufferSize) || (NetBufferSize > 65535) || (NetBufferSize < 1024))
407   {
408         log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
409         NetBufferSize = 10240;
410   }
411   if (!strcmp(dbg,"debug"))
412         LogLevel = DEBUG;
413   if (!strcmp(dbg,"verbose"))
414         LogLevel = VERBOSE;
415   if (!strcmp(dbg,"default"))
416         LogLevel = DEFAULT;
417   if (!strcmp(dbg,"sparse"))
418         LogLevel = SPARSE;
419   if (!strcmp(dbg,"none"))
420         LogLevel = NONE;
421   readfile(MOTD,motd);
422   log(DEBUG,"Reading message of the day");
423   readfile(RULES,rules);
424   log(DEBUG,"Reading connect classes");
425   Classes.clear();
426   for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
427   {
428         strcpy(Value,"");
429         ConfValue("connect","allow",i,Value,&config_f);
430         ConfValue("connect","timeout",i,timeout,&config_f);
431         ConfValue("connect","flood",i,flood,&config_f);
432         if (strcmp(Value,""))
433         {
434                 strcpy(c.host,Value);
435                 c.type = CC_ALLOW;
436                 strcpy(Value,"");
437                 ConfValue("connect","password",i,Value,&config_f);
438                 strcpy(c.pass,Value);
439                 c.registration_timeout = 90; // default is 2 minutes
440                 c.flood = atoi(flood);
441                 if (atoi(timeout)>0)
442                 {
443                         c.registration_timeout = atoi(timeout);
444                 }
445                 Classes.push_back(c);
446                 log(DEBUG,"Read connect class type ALLOW, host=%s password=%s timeout=%d flood=%d",c.host,c.pass,c.registration_timeout,c.flood);
447         }
448         else
449         {
450                 ConfValue("connect","deny",i,Value,&config_f);
451                 strcpy(c.host,Value);
452                 c.type = CC_DENY;
453                 Classes.push_back(c);
454                 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
455         }
456         
457   }
458 }
459
460 void Blocking(int s)
461 {
462   int flags;
463   log(DEBUG,"Blocking: %d",s);
464   flags = fcntl(s, F_GETFL, 0);
465   fcntl(s, F_SETFL, flags ^ O_NONBLOCK);
466 }
467
468 void NonBlocking(int s)
469 {
470   int flags;
471   log(DEBUG,"NonBlocking: %d",s);
472   flags = fcntl(s, F_GETFL, 0);
473   //fcntl(s, F_SETFL, O_NONBLOCK);
474   fcntl(s, F_SETFL, flags | O_NONBLOCK);
475 }
476
477
478 int CleanAndResolve (char *resolvedHost, const char *unresolvedHost)
479 {
480   struct hostent *hostPtr = NULL;
481   struct in_addr addr;
482
483   memset (resolvedHost, '\0',MAXBUF);
484   if(unresolvedHost == NULL)
485         return(ERROR);
486   if ((inet_aton(unresolvedHost,&addr)) == 0)
487         return(ERROR);
488   hostPtr = gethostbyaddr ((char *)&addr.s_addr,sizeof(addr.s_addr),AF_INET);
489   if (hostPtr != NULL)
490         snprintf(resolvedHost,MAXBUF,"%s",hostPtr->h_name);
491   else
492         snprintf(resolvedHost,MAXBUF,"%s",unresolvedHost);
493   return (TRUE);
494 }
495
496 /* write formatted text to a socket, in same format as printf */
497
498 void Write(int sock,char *text, ...)
499 {
500   if (!text)
501   {
502         log(DEFAULT,"*** BUG *** Write was given an invalid parameter");
503         return;
504   }
505   char textbuffer[MAXBUF];
506   va_list argsPtr;
507   char tb[MAXBUF];
508
509   va_start (argsPtr, text);
510   vsnprintf(textbuffer, MAXBUF, text, argsPtr);
511   va_end(argsPtr);
512   sprintf(tb,"%s\r\n",textbuffer);
513   chop(tb);
514   if (sock != -1)
515   {
516         write(sock,tb,strlen(tb));
517         update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
518   }
519 }
520
521 /* write a server formatted numeric response to a single socket */
522
523 void WriteServ(int sock, char* text, ...)
524 {
525   if (!text)
526   {
527         log(DEFAULT,"*** BUG *** WriteServ was given an invalid parameter");
528         return;
529   }
530   char textbuffer[MAXBUF],tb[MAXBUF];
531   va_list argsPtr;
532   va_start (argsPtr, text);
533
534   vsnprintf(textbuffer, MAXBUF, text, argsPtr);
535   va_end(argsPtr);
536   sprintf(tb,":%s %s\r\n",ServerName,textbuffer);
537   chop(tb);
538   if (sock != -1)
539   {
540         write(sock,tb,strlen(tb));
541         update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
542   }
543 }
544
545 /* write text from an originating user to originating user */
546
547 void WriteFrom(int sock, userrec *user,char* text, ...)
548 {
549   if ((!text) || (!user))
550   {
551         log(DEFAULT,"*** BUG *** WriteFrom was given an invalid parameter");
552         return;
553   }
554   char textbuffer[MAXBUF],tb[MAXBUF];
555   va_list argsPtr;
556   va_start (argsPtr, text);
557
558   vsnprintf(textbuffer, MAXBUF, text, argsPtr);
559   va_end(argsPtr);
560   sprintf(tb,":%s!%s@%s %s\r\n",user->nick,user->ident,user->dhost,textbuffer);
561   chop(tb);
562   if (sock != -1)
563   {
564         write(sock,tb,strlen(tb));
565         update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
566   }
567 }
568
569 /* write text to an destination user from a source user (e.g. user privmsg) */
570
571 void WriteTo(userrec *source, userrec *dest,char *data, ...)
572 {
573         if ((!dest) || (!data))
574         {
575                 log(DEFAULT,"*** BUG *** WriteTo was given an invalid parameter");
576                 return;
577         }
578         char textbuffer[MAXBUF],tb[MAXBUF];
579         va_list argsPtr;
580         va_start (argsPtr, data);
581         vsnprintf(textbuffer, MAXBUF, data, argsPtr);
582         va_end(argsPtr);
583         chop(tb);
584
585         // if no source given send it from the server.
586         if (!source)
587         {
588                 WriteServ(dest->fd,":%s %s",ServerName,textbuffer);
589         }
590         else
591         {
592                 WriteFrom(dest->fd,source,"%s",textbuffer);
593         }
594 }
595
596 /* write formatted text from a source user to all users on a channel
597  * including the sender (NOT for privmsg, notice etc!) */
598
599 void WriteChannel(chanrec* Ptr, userrec* user, char* text, ...)
600 {
601         if ((!Ptr) || (!user) || (!text))
602         {
603                 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
604                 return;
605         }
606         char textbuffer[MAXBUF];
607         va_list argsPtr;
608         va_start (argsPtr, text);
609         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
610         va_end(argsPtr);
611         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
612         {
613                 if (has_channel(i->second,Ptr))
614                 {
615                         WriteTo(user,i->second,"%s",textbuffer);
616                 }
617         }
618 }
619
620 /* write formatted text from a source user to all users on a channel
621  * including the sender (NOT for privmsg, notice etc!) doesnt send to
622  * users on remote servers */
623
624 void WriteChannelLocal(chanrec* Ptr, userrec* user, char* text, ...)
625 {
626         if ((!Ptr) || (!text))
627         {
628                 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
629                 return;
630         }
631         char textbuffer[MAXBUF];
632         va_list argsPtr;
633         va_start (argsPtr, text);
634         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
635         va_end(argsPtr);
636         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
637         {
638                 if (has_channel(i->second,Ptr))
639                 {
640                         if (i->second->fd != -1)
641                         {
642                                 if (!user)
643                                 {
644                                         WriteServ(i->second->fd,"%s",textbuffer);
645                                 }
646                                 else
647                                 {
648                                         WriteTo(user,i->second,"%s",textbuffer);
649                                 }
650                         }       
651                 }
652         }
653 }
654
655
656 void WriteChannelWithServ(char* ServerName, chanrec* Ptr, userrec* user, char* text, ...)
657 {
658         if ((!Ptr) || (!user) || (!text))
659         {
660                 log(DEFAULT,"*** BUG *** WriteChannelWithServ was given an invalid parameter");
661                 return;
662         }
663         char textbuffer[MAXBUF];
664         va_list argsPtr;
665         va_start (argsPtr, text);
666         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
667         va_end(argsPtr);
668         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
669         {
670                 if (i->second)
671                 {
672                         if (has_channel(i->second,Ptr))
673                         {
674                                 WriteServ(i->second->fd,"%s",textbuffer);
675                         }
676                 }
677         }
678 }
679
680
681 /* write formatted text from a source user to all users on a channel except
682  * for the sender (for privmsg etc) */
683
684 void ChanExceptSender(chanrec* Ptr, userrec* user, char* text, ...)
685 {
686         if ((!Ptr) || (!user) || (!text))
687         {
688                 log(DEFAULT,"*** BUG *** ChanExceptSender was given an invalid parameter");
689                 return;
690         }
691         char textbuffer[MAXBUF];
692         va_list argsPtr;
693         va_start (argsPtr, text);
694         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
695         va_end(argsPtr);
696
697         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
698         {
699                 if (i->second)
700                 {
701                         if (has_channel(i->second,Ptr) && (user != i->second))
702                         {
703                                 WriteTo(user,i->second,"%s",textbuffer);
704                         }
705                 }
706         }
707 }
708
709 int c_count(userrec* u)
710 {
711         int z = 0;
712         for (int i =0; i != MAXCHANS; i++)
713                 if (u->chans[i].channel != NULL)
714                         z++;
715         return z;
716
717 }
718
719 /* return 0 or 1 depending if users u and u2 share one or more common channels
720  * (used by QUIT, NICK etc which arent channel specific notices) */
721
722 int common_channels(userrec *u, userrec *u2)
723 {
724         int i = 0;
725         int z = 0;
726
727         if ((!u) || (!u2))
728         {
729                 log(DEFAULT,"*** BUG *** common_channels was given an invalid parameter");
730                 return 0;
731         }
732         for (int i = 0; i != MAXCHANS; i++)
733         {
734                 for (z = 0; z != MAXCHANS; z++)
735                 {
736                         if ((u->chans[i].channel != NULL) && (u2->chans[z].channel != NULL))
737                         {
738                                 if ((u->chans[i].channel == u2->chans[z].channel) && (u->chans[i].channel) && (u2->chans[z].channel) && (u->registered == 7) && (u2->registered == 7))
739                                 {
740                                         if ((c_count(u)) && (c_count(u2)))
741                                         {
742                                                 return 1;
743                                         }
744                                 }
745                         }
746                 }
747         }
748         return 0;
749 }
750
751 /* write a formatted string to all users who share at least one common
752  * channel, including the source user e.g. for use in NICK */
753
754 void WriteCommon(userrec *u, char* text, ...)
755 {
756         if (!u)
757         {
758                 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
759                 return;
760         }
761
762         if (u->registered != 7) {
763                 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
764                 return;
765         }
766         
767         char textbuffer[MAXBUF];
768         va_list argsPtr;
769         va_start (argsPtr, text);
770         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
771         va_end(argsPtr);
772
773         WriteFrom(u->fd,u,"%s",textbuffer);
774
775         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
776         {
777                 if (i->second)
778                 {
779                         if (common_channels(u,i->second) && (i->second != u))
780                         {
781                                 WriteFrom(i->second->fd,u,"%s",textbuffer);
782                         }
783                 }
784         }
785 }
786
787 /* write a formatted string to all users who share at least one common
788  * channel, NOT including the source user e.g. for use in QUIT */
789
790 void WriteCommonExcept(userrec *u, char* text, ...)
791 {
792         if (!u)
793         {
794                 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
795                 return;
796         }
797
798         if (u->registered != 7) {
799                 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
800                 return;
801         }
802
803         char textbuffer[MAXBUF];
804         va_list argsPtr;
805         va_start (argsPtr, text);
806         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
807         va_end(argsPtr);
808
809         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
810         {
811                 if (i->second)
812                 {
813                         if ((common_channels(u,i->second)) && (u != i->second))
814                         {
815                                 WriteFrom(i->second->fd,u,"%s",textbuffer);
816                         }
817                 }
818         }
819 }
820
821 void WriteOpers(char* text, ...)
822 {
823         if (!text)
824         {
825                 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
826                 return;
827         }
828
829         char textbuffer[MAXBUF];
830         va_list argsPtr;
831         va_start (argsPtr, text);
832         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
833         va_end(argsPtr);
834
835         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
836         {
837                 if (i->second)
838                 {
839                         if (strchr(i->second->modes,'o'))
840                         {
841                                 if (strchr(i->second->modes,'s'))
842                                 {
843                                         // send server notices to all with +s
844                                         // (TODO: needs SNOMASKs)
845                                         WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
846                                 }
847                         }
848                 }
849         }
850 }
851
852 // returns TRUE of any users on channel C occupy server 'servername'.
853
854 bool ChanAnyOnThisServer(chanrec *c,char* servername)
855 {
856         log(DEBUG,"ChanAnyOnThisServer");
857         for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
858         {
859                 if (has_channel(i->second,c))
860                 {
861                         if (!strcasecmp(i->second->server,servername))
862                         {
863                                 return true;
864                         }
865                 }
866         }
867         return false;
868 }
869
870 // returns true if user 'u' shares any common channels with any users on server 'servername'
871
872 bool CommonOnThisServer(userrec* u,const char* servername)
873 {
874         log(DEBUG,"ChanAnyOnThisServer");
875         for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
876         {
877                 if ((common_channels(u,i->second)) && (u != i->second))
878                 {
879                         if (!strcasecmp(i->second->server,servername))
880                         {
881                                 log(DEBUG,"%s is common to %s sharing with %s",i->second->nick,servername,u->nick);
882                                 return true;
883                         }
884                 }
885         }
886         return false;
887 }
888
889
890 void NetSendToCommon(userrec* u, char* s)
891 {
892         char buffer[MAXBUF];
893         snprintf(buffer,MAXBUF,"%s",s);
894         
895         log(DEBUG,"NetSendToCommon: '%s' '%s'",u->nick,s);
896
897         for (int j = 0; j < 32; j++)
898         {
899                 if (me[j] != NULL)
900                 {
901                         for (int k = 0; k < me[j]->connectors.size(); k++)
902                         {
903                                 if (CommonOnThisServer(u,me[j]->connectors[k].GetServerName().c_str()))
904                                 {
905                                         me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
906                                 }
907                         }
908                 }
909         }
910 }
911
912
913 void NetSendToAll(char* s)
914 {
915         char buffer[MAXBUF];
916         snprintf(buffer,MAXBUF,"%s",s);
917         
918         log(DEBUG,"NetSendToAll: '%s'",s);
919
920         for (int j = 0; j < 32; j++)
921         {
922                 if (me[j] != NULL)
923                 {
924                         for (int k = 0; k < me[j]->connectors.size(); k++)
925                         {
926                                 me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
927                         }
928                 }
929         }
930 }
931
932
933 void NetSendToOne(char* target,char* s)
934 {
935         char buffer[MAXBUF];
936         snprintf(buffer,MAXBUF,"%s",s);
937         
938         log(DEBUG,"NetSendToOne: '%s' '%s'",target,s);
939
940         for (int j = 0; j < 32; j++)
941         {
942                 if (me[j] != NULL)
943                 {
944                         for (int k = 0; k < me[j]->connectors.size(); k++)
945                         {
946                                 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
947                                 {
948                                         me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
949                                 }
950                         }
951                 }
952         }
953 }
954
955 void NetSendToAllExcept(char* target,char* s)
956 {
957         char buffer[MAXBUF];
958         snprintf(buffer,MAXBUF,"%s",s);
959         
960         log(DEBUG,"NetSendToAllExcept: '%s' '%s'",target,s);
961         
962         for (int j = 0; j < 32; j++)
963         {
964                 if (me[j] != NULL)
965                 {
966                         for (int k = 0; k < me[j]->connectors.size(); k++)
967                         {
968                                 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),target))
969                                 {
970                                         me[j]->SendPacket(buffer,me[j]->connectors[k].GetServerName().c_str());
971                                 }
972                         }
973                 }
974         }
975 }
976
977
978 bool hasumode(userrec* user, char mode)
979 {
980         if (user)
981         {
982                 return (strchr(user->modes,mode)>0);
983         }
984         else return false;
985 }
986
987 void WriteMode(const char* modes, int flags, const char* text, ...)
988 {
989         if ((!text) || (!modes) || (!flags))
990         {
991                 log(DEFAULT,"*** BUG *** WriteMode was given an invalid parameter");
992                 return;
993         }
994
995         char textbuffer[MAXBUF];
996         va_list argsPtr;
997         va_start (argsPtr, text);
998         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
999         va_end(argsPtr);
1000
1001         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1002         {
1003                 if (i->second)
1004                 {
1005                         bool send_to_user = false;
1006                         
1007                         if (flags == WM_AND)
1008                         {
1009                                 send_to_user = true;
1010                                 for (int n = 0; n < strlen(modes); n++)
1011                                 {
1012                                         if (!hasumode(i->second,modes[n]))
1013                                         {
1014                                                 send_to_user = false;
1015                                                 break;
1016                                         }
1017                                 }
1018                         }
1019                         else if (flags == WM_OR)
1020                         {
1021                                 send_to_user = false;
1022                                 for (int n = 0; n < strlen(modes); n++)
1023                                 {
1024                                         if (hasumode(i->second,modes[n]))
1025                                         {
1026                                                 send_to_user = true;
1027                                                 break;
1028                                         }
1029                                 }
1030                         }
1031
1032                         if (send_to_user)
1033                         {
1034                                 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
1035                         }
1036                 }
1037         }
1038 }
1039
1040 void ChangeName(userrec* user, const char* gecos)
1041 {
1042         strncpy(user->fullname,gecos,MAXBUF);
1043
1044         // TODO: replace these with functions:
1045         // NetSendToAll - to all
1046         // NetSendToCommon - to all that hold users sharing a common channel with another user
1047         // NetSendToOne - to one server
1048         // NetSendToAllExcept - send to all but one
1049         // all by servername
1050
1051         char buffer[MAXBUF];
1052         snprintf(buffer,MAXBUF,"a %s :%s",user->nick,gecos);
1053         NetSendToAll(buffer);
1054 }
1055
1056 void ChangeDisplayedHost(userrec* user, const char* host)
1057 {
1058         strncpy(user->dhost,host,160);
1059         char buffer[MAXBUF];
1060         snprintf(buffer,MAXBUF,"b %s :%s",user->nick,host);
1061         NetSendToAll(buffer);
1062 }
1063
1064 void WriteWallOps(userrec *source, bool local_only, char* text, ...)  
1065 {  
1066         if ((!text) || (!source))
1067         {
1068                 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
1069                 return;
1070         }
1071
1072         int i = 0;  
1073         char textbuffer[MAXBUF];  
1074         va_list argsPtr;  
1075         va_start (argsPtr, text);  
1076         vsnprintf(textbuffer, MAXBUF, text, argsPtr);  
1077         va_end(argsPtr);  
1078   
1079         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1080         {
1081                 if (i->second)
1082                 {
1083                         if (strchr(i->second->modes,'w'))
1084                         {
1085                                 WriteTo(source,i->second,"WALLOPS %s",textbuffer);
1086                         }
1087                 }
1088         }
1089
1090         if (!local_only)
1091         {
1092                 char buffer[MAXBUF];
1093                 snprintf(buffer,MAXBUF,"@ %s :%s",source->nick,textbuffer);
1094                 NetSendToAll(buffer);
1095         }
1096 }  
1097
1098 /* convert a string to lowercase. Note following special circumstances
1099  * taken from RFC 1459. Many "official" server branches still hold to this
1100  * rule so i will too;
1101  *
1102  *  Because of IRC's scandanavian origin, the characters {}| are
1103  *  considered to be the lower case equivalents of the characters []\,
1104  *  respectively. This is a critical issue when determining the
1105  *  equivalence of two nicknames.
1106  */
1107
1108 void strlower(char *n)
1109 {
1110         if (!n)
1111         {
1112                 return;
1113         }
1114         for (int i = 0; i != strlen(n); i++)
1115         {
1116                 n[i] = tolower(n[i]);
1117                 if (n[i] == '[')
1118                         n[i] = '{';
1119                 if (n[i] == ']')
1120                         n[i] = '}';
1121                 if (n[i] == '\\')
1122                         n[i] = '|';
1123         }
1124 }
1125
1126 /* verify that a user's ident and nickname is valid */
1127
1128 int isident(const char* n)
1129 {
1130         char v[MAXBUF];
1131         if (!n)
1132
1133         {
1134                 return 0;
1135         }
1136         if (!strcmp(n,""))
1137         {
1138                 return 0;
1139         }
1140         for (int i = 0; i != strlen(n); i++)
1141         {
1142                 if ((n[i] < 33) || (n[i] > 125))
1143                 {
1144                         return 0;
1145                 }
1146                 /* can't occur ANYWHERE in an Ident! */
1147                 if (strchr("<>,./?:;@'~#=+()*&%$£ \"!",n[i]))
1148                 {
1149                         return 0;
1150                 }
1151         }
1152         return 1;
1153 }
1154
1155
1156 int isnick(const char* n)
1157 {
1158         int i = 0;
1159         char v[MAXBUF];
1160         if (!n)
1161         {
1162                 return 0;
1163         }
1164         if (!strcmp(n,""))
1165         {
1166                 return 0;
1167         }
1168         if (strlen(n) > NICKMAX-1)
1169         {
1170                 return 0;
1171         }
1172         for (int i = 0; i != strlen(n); i++)
1173         {
1174                 if ((n[i] < 33) || (n[i] > 125))
1175                 {
1176                         return 0;
1177                 }
1178                 /* can't occur ANYWHERE in a nickname! */
1179                 if (strchr("<>,./?:;@'~#=+()*&%$£ \"!",n[i]))
1180                 {
1181                         return 0;
1182                 }
1183                 /* can't occur as the first char of a nickname... */
1184                 if ((strchr("0123456789",n[i])) && (!i))
1185                 {
1186                         return 0;
1187                 }
1188         }
1189         return 1;
1190 }
1191
1192 /* Find a user record by nickname and return a pointer to it */
1193
1194 userrec* Find(string nick)
1195 {
1196         user_hash::iterator iter = clientlist.find(nick);
1197
1198         if (iter == clientlist.end())
1199                 /* Couldn't find it */
1200                 return NULL;
1201
1202         return iter->second;
1203 }
1204
1205 void update_stats_l(int fd,int data_out) /* add one line-out to stats L for this fd */
1206 {
1207         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1208         {
1209                 if (i->second)
1210                 {
1211                         if (i->second->fd == fd)
1212                         {
1213                                 i->second->bytes_out+=data_out;
1214                                 i->second->cmds_out++;
1215                         }
1216                 }
1217         }
1218 }
1219
1220
1221 /* find a channel record by channel name and return a pointer to it */
1222
1223 chanrec* FindChan(const char* chan)
1224 {
1225         if (!chan)
1226         {
1227                 log(DEFAULT,"*** BUG *** Findchan was given an invalid parameter");
1228                 return NULL;
1229         }
1230
1231         chan_hash::iterator iter = chanlist.find(chan);
1232
1233         if (iter == chanlist.end())
1234                 /* Couldn't find it */
1235                 return NULL;
1236
1237         return iter->second;
1238 }
1239
1240
1241 void purge_empty_chans(void)
1242 {
1243         int go_again = 1, purge = 0;
1244         
1245         while (go_again)
1246         {
1247                 go_again = 0;
1248                 for (chan_hash::iterator i = chanlist.begin(); i != chanlist.end(); i++)
1249                 {
1250                         if (i->second) {
1251                                 if (!usercount(i->second))
1252                                 {
1253                                         /* kill the record */
1254                                         if (i != chanlist.end())
1255                                         {
1256                                                 log(DEBUG,"del_channel: destroyed: %s",i->second->name);
1257                                                 delete i->second;
1258                                                 chanlist.erase(i);
1259                                                 go_again = 1;
1260                                                 purge++;
1261                                                 break;
1262                                         }
1263                                 }
1264                                 else
1265                                 {
1266                                         log(DEBUG,"skipped purge for %s",i->second->name);
1267                                 }
1268                         }
1269                 }
1270         }
1271         log(DEBUG,"completed channel purge, killed %d",purge);
1272 }
1273
1274 /* returns the status character for a given user on a channel, e.g. @ for op,
1275  * % for halfop etc. If the user has several modes set, the highest mode
1276  * the user has must be returned. */
1277
1278 char* cmode(userrec *user, chanrec *chan)
1279 {
1280         if ((!user) || (!chan))
1281         {
1282                 log(DEFAULT,"*** BUG *** cmode was given an invalid parameter");
1283                 return "";
1284         }
1285
1286         int i;
1287         for (int i = 0; i != MAXCHANS; i++)
1288         {
1289                 if ((user->chans[i].channel == chan) && (chan != NULL))
1290                 {
1291                         if ((user->chans[i].uc_modes & UCMODE_OP) > 0)
1292                         {
1293                                 return "@";
1294                         }
1295                         if ((user->chans[i].uc_modes & UCMODE_HOP) > 0)
1296                         {
1297                                 return "%";
1298                         }
1299                         if ((user->chans[i].uc_modes & UCMODE_VOICE) > 0)
1300                         {
1301                                 return "+";
1302                         }
1303                         return "";
1304                 }
1305         }
1306 }
1307
1308 char scratch[MAXBUF];
1309 char sparam[MAXBUF];
1310
1311 char* chanmodes(chanrec *chan)
1312 {
1313         if (!chan)
1314         {
1315                 log(DEFAULT,"*** BUG *** chanmodes was given an invalid parameter");
1316                 strcpy(scratch,"");
1317                 return scratch;
1318         }
1319
1320         strcpy(scratch,"");
1321         strcpy(sparam,"");
1322         if (chan->noexternal)
1323         {
1324                 strncat(scratch,"n",MAXMODES);
1325         }
1326         if (chan->topiclock)
1327         {
1328                 strncat(scratch,"t",MAXMODES);
1329         }
1330         if (strcmp(chan->key,""))
1331         {
1332                 strncat(scratch,"k",MAXMODES);
1333         }
1334         if (chan->limit)
1335         {
1336                 strncat(scratch,"l",MAXMODES);
1337         }
1338         if (chan->inviteonly)
1339         {
1340                 strncat(scratch,"i",MAXMODES);
1341         }
1342         if (chan->moderated)
1343         {
1344                 strncat(scratch,"m",MAXMODES);
1345         }
1346         if (chan->secret)
1347         {
1348                 strncat(scratch,"s",MAXMODES);
1349         }
1350         if (chan->c_private)
1351         {
1352                 strncat(scratch,"p",MAXMODES);
1353         }
1354         if (strcmp(chan->key,""))
1355         {
1356                 strncat(sparam,chan->key,MAXBUF);
1357         }
1358         if (chan->limit)
1359         {
1360                 char foo[24];
1361                 sprintf(foo," %d",chan->limit);
1362                 strncat(sparam,foo,MAXBUF);
1363         }
1364         if (strlen(chan->custom_modes))
1365         {
1366                 strncat(scratch,chan->custom_modes,MAXMODES);
1367                 for (int z = 0; z < strlen(chan->custom_modes); z++)
1368                 {
1369                         std::string extparam = chan->GetModeParameter(chan->custom_modes[z]);
1370                         if (extparam != "")
1371                         {
1372                                 strncat(sparam," ",MAXBUF);
1373                                 strncat(sparam,extparam.c_str(),MAXBUF);
1374                         }
1375                 }
1376         }
1377         log(DEBUG,"chanmodes: %s %s%s",chan->name,scratch,sparam);
1378         strncat(scratch,sparam,MAXMODES);
1379         return scratch;
1380 }
1381
1382 /* returns the status value for a given user on a channel, e.g. STATUS_OP for
1383  * op, STATUS_VOICE for voice etc. If the user has several modes set, the
1384  * highest mode the user has must be returned. */
1385
1386 int cstatus(userrec *user, chanrec *chan)
1387 {
1388         if ((!chan) || (!user))
1389         {
1390                 log(DEFAULT,"*** BUG *** cstatus was given an invalid parameter");
1391                 return 0;
1392         }
1393
1394         for (int i = 0; i != MAXCHANS; i++)
1395         {
1396                 if ((user->chans[i].channel == chan) && (chan != NULL))
1397                 {
1398                         if ((user->chans[i].uc_modes & UCMODE_OP) > 0)
1399                         {
1400                                 return STATUS_OP;
1401                         }
1402                         if ((user->chans[i].uc_modes & UCMODE_HOP) > 0)
1403                         {
1404                                 return STATUS_HOP;
1405                         }
1406                         if ((user->chans[i].uc_modes & UCMODE_VOICE) > 0)
1407                         {
1408                                 return STATUS_VOICE;
1409                         }
1410                         return STATUS_NORMAL;
1411                 }
1412         }
1413 }
1414
1415
1416 /* compile a userlist of a channel into a string, each nick seperated by
1417  * spaces and op, voice etc status shown as @ and + */
1418
1419 void userlist(userrec *user,chanrec *c)
1420 {
1421         if ((!c) || (!user))
1422         {
1423                 log(DEFAULT,"*** BUG *** userlist was given an invalid parameter");
1424                 return;
1425         }
1426
1427         sprintf(list,"353 %s = %s :", user->nick, c->name);
1428         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1429         {
1430                 if (has_channel(i->second,c))
1431                 {
1432                         if (isnick(i->second->nick))
1433                         {
1434                                 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1435                                 {
1436                                         /* user is +i, and source not on the channel, does not show
1437                                          * nick in NAMES list */
1438                                         continue;
1439                                 }
1440                                 strcat(list,cmode(i->second,c));
1441                                 strcat(list,i->second->nick);
1442                                 strcat(list," ");
1443                                 if (strlen(list)>(480-NICKMAX))
1444                                 {
1445                                         /* list overflowed into
1446                                          * multiple numerics */
1447                                         WriteServ(user->fd,list);
1448                                         sprintf(list,"353 %s = %s :", user->nick, c->name);
1449                                 }
1450                         }
1451                 }
1452         }
1453         /* if whats left in the list isnt empty, send it */
1454         if (list[strlen(list)-1] != ':')
1455         {
1456                 WriteServ(user->fd,list);
1457         }
1458 }
1459
1460 /* return a count of the users on a specific channel accounting for
1461  * invisible users who won't increase the count. e.g. for /LIST */
1462
1463 int usercount_i(chanrec *c)
1464 {
1465         int i = 0;
1466         int count = 0;
1467         
1468         if (!c)
1469         {
1470                 log(DEFAULT,"*** BUG *** usercount_i was given an invalid parameter");
1471                 return 0;
1472         }
1473
1474         strcpy(list,"");
1475         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1476         {
1477                 if (i->second)
1478                 {
1479                         if (has_channel(i->second,c))
1480                         {
1481                                 if (isnick(i->second->nick))
1482                                 {
1483                                         if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1484                                         {
1485                                                 /* user is +i, and source not on the channel, does not show
1486                                                  * nick in NAMES list */
1487                                                 continue;
1488                                         }
1489                                         count++;
1490                                 }
1491                         }
1492                 }
1493         }
1494         log(DEBUG,"usercount_i: %s %d",c->name,count);
1495         return count;
1496 }
1497
1498
1499 int usercount(chanrec *c)
1500 {
1501         int i = 0;
1502         int count = 0;
1503         
1504         if (!c)
1505         {
1506                 log(DEFAULT,"*** BUG *** usercount was given an invalid parameter");
1507                 return 0;
1508         }
1509
1510         strcpy(list,"");
1511         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1512         {
1513                 if (i->second)
1514                 {
1515                         if (has_channel(i->second,c))
1516                         {
1517                                 if ((isnick(i->second->nick)) && (i->second->registered == 7))
1518                                 {
1519                                         count++;
1520                                 }
1521                         }
1522                 }
1523         }
1524         log(DEBUG,"usercount: %s %d",c->name,count);
1525         return count;
1526 }
1527
1528
1529 /* add a channel to a user, creating the record for it if needed and linking
1530  * it to the user record */
1531
1532 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
1533 {
1534         if ((!user) || (!cn))
1535         {
1536                 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
1537                 return 0;
1538         }
1539
1540         int i = 0;
1541         chanrec* Ptr;
1542         int created = 0;
1543         char cname[MAXBUF];
1544
1545         strncpy(cname,cn,MAXBUF);
1546         
1547         // we MUST declare this wherever we use FOREACH_RESULT
1548         int MOD_RESULT = 0;
1549
1550         if (strlen(cname) > CHANMAX-1)
1551         {
1552                 cname[CHANMAX-1] = '\0';
1553         }
1554
1555         log(DEBUG,"add_channel: %s %s",user->nick,cname);
1556         
1557         if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
1558         {
1559                 return NULL; // already on the channel!
1560         }
1561
1562
1563         if (!FindChan(cname))
1564         {
1565                 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
1566                 if (MOD_RESULT) {
1567                         return NULL;
1568                 }
1569
1570                 /* create a new one */
1571                 log(DEBUG,"add_channel: creating: %s",cname);
1572                 {
1573                         chanlist[cname] = new chanrec();
1574
1575                         strcpy(chanlist[cname]->name, cname);
1576                         chanlist[cname]->topiclock = 1;
1577                         chanlist[cname]->noexternal = 1;
1578                         chanlist[cname]->created = time(NULL);
1579                         strcpy(chanlist[cname]->topic, "");
1580                         strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
1581                         chanlist[cname]->topicset = 0;
1582                         Ptr = chanlist[cname];
1583                         log(DEBUG,"add_channel: created: %s",cname);
1584                         /* set created to 2 to indicate user
1585                          * is the first in the channel
1586                          * and should be given ops */
1587                         created = 2;
1588                 }
1589         }
1590         else
1591         {
1592                 /* channel exists, just fish out a pointer to its struct */
1593                 Ptr = FindChan(cname);
1594                 if (Ptr)
1595                 {
1596                         log(DEBUG,"add_channel: joining to: %s",Ptr->name);
1597                         
1598                         // the override flag allows us to bypass channel modes
1599                         // and bans (used by servers)
1600                         if (!override)
1601                         {
1602                                 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
1603                                 if (MOD_RESULT) {
1604                                         return NULL;
1605                                 }
1606                                 
1607                                 if (strcmp(Ptr->key,""))
1608                                 {
1609                                         log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
1610                                         if (!key)
1611                                         {
1612                                                 log(DEBUG,"add_channel: no key given in JOIN");
1613                                                 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
1614                                                 return NULL;
1615                                         }
1616                                         else
1617                                         {
1618                                                 log(DEBUG,"key at %p is %s",key,key);
1619                                                 if (strcasecmp(key,Ptr->key))
1620                                                 {
1621                                                         log(DEBUG,"add_channel: bad key given in JOIN");
1622                                                         WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
1623                                                         return NULL;
1624                                                 }
1625                                         }
1626                                 }
1627                                 log(DEBUG,"add_channel: no key");
1628         
1629                                 if (Ptr->inviteonly)
1630                                 {
1631                                         log(DEBUG,"add_channel: channel is +i");
1632                                         if (user->IsInvited(Ptr->name))
1633                                         {
1634                                                 /* user was invited to channel */
1635                                                 /* there may be an optional channel NOTICE here */
1636                                         }
1637                                         else
1638                                         {
1639                                                 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
1640                                                 return NULL;
1641                                         }
1642                                 }
1643                                 log(DEBUG,"add_channel: channel is not +i");
1644         
1645                                 if (Ptr->limit)
1646                                 {
1647                                         if (usercount(Ptr) == Ptr->limit)
1648                                         {
1649                                                 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
1650                                                 return NULL;
1651                                         }
1652                                 }
1653                                 
1654                                 log(DEBUG,"add_channel: about to walk banlist");
1655         
1656                                 /* check user against the channel banlist */
1657                                 if (Ptr)
1658                                 {
1659                                         if (Ptr->bans.size())
1660                                         {
1661                                                 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
1662                                                 {
1663                                                         if (match(user->GetFullHost(),i->data))
1664                                                         {
1665                                                                 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
1666                                                                 return NULL;
1667                                                         }
1668                                                 }
1669                                         }
1670                                 }
1671                                 
1672                                 log(DEBUG,"add_channel: bans checked");
1673                                 
1674
1675                                 if ((Ptr) && (user))
1676                                 {
1677                                         user->RemoveInvite(Ptr->name);
1678                                 }
1679         
1680                                 log(DEBUG,"add_channel: invites removed");
1681
1682                         }
1683                         else
1684                         {
1685                                 log(DEBUG,"Overridden checks");
1686                         }
1687
1688                         
1689                 }
1690                 created = 1;
1691         }
1692
1693         log(DEBUG,"Passed channel checks");
1694         
1695         for (int i =0; i != MAXCHANS; i++)
1696         {
1697                 log(DEBUG,"Check location %d",i);
1698                 if (user->chans[i].channel == NULL)
1699                 {
1700                         log(DEBUG,"Adding into their channel list at location %d",i);
1701
1702                         if (created == 2) 
1703                         {
1704                                 /* first user in is given ops */
1705                                 user->chans[i].uc_modes = UCMODE_OP;
1706                         }
1707                         else
1708                         {
1709                                 user->chans[i].uc_modes = 0;
1710                         }
1711                         user->chans[i].channel = Ptr;
1712                         WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
1713                         
1714                         if (!override) // we're not overriding... so this isnt part of a netburst, broadcast it.
1715                         {
1716                                 // use the stamdard J token with no privilages.
1717                                 char buffer[MAXBUF];
1718                                 snprintf(buffer,MAXBUF,"J %s :%s",user->nick,Ptr->name);
1719                                 NetSendToAll(buffer);
1720                         }
1721
1722                         log(DEBUG,"Sent JOIN to client");
1723
1724                         if (Ptr->topicset)
1725                         {
1726                                 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
1727                                 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
1728                         }
1729                         userlist(user,Ptr);
1730                         WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
1731                         WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
1732                         WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
1733                         FOREACH_MOD OnUserJoin(user,Ptr);
1734                         return Ptr;
1735                 }
1736         }
1737         log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
1738         WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
1739         return NULL;
1740 }
1741
1742 /* remove a channel from a users record, and remove the record from memory
1743  * if the channel has become empty */
1744
1745 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
1746 {
1747         if ((!user) || (!cname))
1748         {
1749                 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
1750                 return NULL;
1751         }
1752
1753         chanrec* Ptr;
1754         int created = 0;
1755
1756         if ((!cname) || (!user))
1757         {
1758                 return NULL;
1759         }
1760
1761         Ptr = FindChan(cname);
1762         
1763         if (!Ptr)
1764         {
1765                 return NULL;
1766         }
1767
1768         FOREACH_MOD OnUserPart(user,Ptr);
1769         log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
1770         
1771         for (int i =0; i != MAXCHANS; i++)
1772         {
1773                 /* zap it from the channel list of the user */
1774                 if (user->chans[i].channel == Ptr)
1775                 {
1776                         if (reason)
1777                         {
1778                                 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
1779
1780                                 if (!local)
1781                                 {
1782                                         char buffer[MAXBUF];
1783                                         snprintf(buffer,MAXBUF,"L %s %s :%s",user->nick,Ptr->name,reason);
1784                                         NetSendToAll(buffer);
1785                                 }
1786
1787                                 
1788                         }
1789                         else
1790                         {
1791                                 if (!local)
1792                                 {
1793                                         char buffer[MAXBUF];
1794                                         snprintf(buffer,MAXBUF,"L %s %s :",user->nick,Ptr->name);
1795                                         NetSendToAll(buffer);
1796                                 }
1797                         
1798                                 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
1799                         }
1800                         user->chans[i].uc_modes = 0;
1801                         user->chans[i].channel = NULL;
1802                         log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1803                         break;
1804                 }
1805         }
1806         
1807         /* if there are no users left on the channel */
1808         if (!usercount(Ptr))
1809         {
1810                 chan_hash::iterator iter = chanlist.find(Ptr->name);
1811
1812                 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1813
1814                 /* kill the record */
1815                 if (iter != chanlist.end())
1816                 {
1817                         log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1818                         delete iter->second;
1819                         chanlist.erase(iter);
1820                 }
1821         }
1822 }
1823
1824
1825 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
1826 {
1827         if ((!src) || (!user) || (!Ptr) || (!reason))
1828         {
1829                 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
1830                 return;
1831         }
1832
1833         int i = 0;
1834         int created = 0;
1835
1836         if ((!Ptr) || (!user) || (!src))
1837         {
1838                 return;
1839         }
1840
1841         log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
1842
1843         if (!has_channel(user,Ptr))
1844         {
1845                 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
1846                 return;
1847         }
1848         if ((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr)))
1849         {
1850                 if (cstatus(src,Ptr) == STATUS_HOP)
1851                 {
1852                         WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
1853                 }
1854                 else
1855                 {
1856                         WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
1857                 }
1858                 
1859                 return;
1860         }
1861         
1862         for (int i =0; i != MAXCHANS; i++)
1863         {
1864                 /* zap it from the channel list of the user */
1865                 if (user->chans[i].channel)
1866                 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
1867                 {
1868                         WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
1869                         user->chans[i].uc_modes = 0;
1870                         user->chans[i].channel = NULL;
1871                         log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1872                         break;
1873                 }
1874         }
1875         
1876         /* if there are no users left on the channel */
1877         if (!usercount(Ptr))
1878         {
1879                 chan_hash::iterator iter = chanlist.find(Ptr->name);
1880
1881                 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1882
1883                 /* kill the record */
1884                 if (iter != chanlist.end())
1885                 {
1886                         log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1887                         delete iter->second;
1888                         chanlist.erase(iter);
1889                 }
1890         }
1891 }
1892
1893
1894 /* returns 1 if user u has channel c in their record, 0 if not */
1895
1896 int has_channel(userrec *u, chanrec *c)
1897 {
1898         if ((!u) || (!c))
1899         {
1900                 log(DEFAULT,"*** BUG *** has_channel was given an invalid parameter");
1901                 return 0;
1902         }
1903         for (int i =0; i != MAXCHANS; i++)
1904         {
1905                 if (u->chans[i].channel == c)
1906                 {
1907                         return 1;
1908                 }
1909         }
1910         return 0;
1911 }
1912
1913 int give_ops(userrec *user,char *dest,chanrec *chan,int status)
1914 {
1915         userrec *d;
1916         int i;
1917         
1918         if ((!user) || (!dest) || (!chan))
1919         {
1920                 log(DEFAULT,"*** BUG *** give_ops was given an invalid parameter");
1921                 return 0;
1922         }
1923         if (status < STATUS_OP)
1924         {
1925                 log(DEBUG,"%s cant give ops to %s because they nave status %d and needs %d",user->nick,dest,status,STATUS_OP);
1926                 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1927                 return 0;
1928         }
1929         else
1930         {
1931                 if (!isnick(dest))
1932                 {
1933                         log(DEFAULT,"the target nickname given to give_ops was invalid");
1934                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1935                         return 0;
1936                 }
1937                 d = Find(dest);
1938                 if (!d)
1939                 {
1940                         log(DEFAULT,"the target nickname given to give_ops couldnt be found");
1941                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1942                         return 0;
1943                 }
1944                 else
1945                 {
1946                         for (int i = 0; i != MAXCHANS; i++)
1947                         {
1948                                 if ((d->chans[i].channel != NULL) && (chan != NULL))
1949                                 if (!strcasecmp(d->chans[i].channel->name,chan->name))
1950                                 {
1951                                         if (d->chans[i].uc_modes & UCMODE_OP)
1952                                         {
1953                                                 /* mode already set on user, dont allow multiple */
1954                                                 log(DEFAULT,"The target user given to give_ops was already opped on the channel");
1955                                                 return 0;
1956                                         }
1957                                         d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_OP;
1958                                         log(DEBUG,"gave ops: %s %s",d->chans[i].channel->name,d->nick);
1959                                         return 1;
1960                                 }
1961                         }
1962                         log(DEFAULT,"The target channel given to give_ops was not in the users mode list");
1963                 }
1964         }
1965         return 1;
1966 }
1967
1968 int give_hops(userrec *user,char *dest,chanrec *chan,int status)
1969 {
1970         userrec *d;
1971         int i;
1972         
1973         if ((!user) || (!dest) || (!chan))
1974         {
1975                 log(DEFAULT,"*** BUG *** give_hops was given an invalid parameter");
1976                 return 0;
1977         }
1978         if (status != STATUS_OP)
1979         {
1980                 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1981                 return 0;
1982         }
1983         else
1984         {
1985                 d = Find(dest);
1986                 if (!isnick(dest))
1987                 {
1988                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1989                         return 0;
1990                 }
1991                 if (!d)
1992                 {
1993                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1994                         return 0;
1995                 }
1996                 else
1997                 {
1998                         for (int i = 0; i != MAXCHANS; i++)
1999                         {
2000                                 if ((d->chans[i].channel != NULL) && (chan != NULL))
2001                                 if (!strcasecmp(d->chans[i].channel->name,chan->name))
2002                                 {
2003                                         if (d->chans[i].uc_modes & UCMODE_HOP)
2004                                         {
2005                                                 /* mode already set on user, dont allow multiple */
2006                                                 return 0;
2007                                         }
2008                                         d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_HOP;
2009                                         log(DEBUG,"gave h-ops: %s %s",d->chans[i].channel->name,d->nick);
2010                                         return 1;
2011                                 }
2012                         }
2013                 }
2014         }
2015         return 1;
2016 }
2017
2018 int give_voice(userrec *user,char *dest,chanrec *chan,int status)
2019 {
2020         userrec *d;
2021         int i;
2022         
2023         if ((!user) || (!dest) || (!chan))
2024         {
2025                 log(DEFAULT,"*** BUG *** give_voice was given an invalid parameter");
2026                 return 0;
2027         }
2028         if (status < STATUS_HOP)
2029         {
2030                 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, chan->name);
2031                 return 0;
2032         }
2033         else
2034         {
2035                 d = Find(dest);
2036                 if (!isnick(dest))
2037                 {
2038                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
2039                         return 0;
2040                 }
2041                 if (!d)
2042                 {
2043                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
2044                         return 0;
2045                 }
2046                 else
2047                 {
2048                         for (int i = 0; i != MAXCHANS; i++)
2049                         {
2050                                 if ((d->chans[i].channel != NULL) && (chan != NULL))
2051                                 if (!strcasecmp(d->chans[i].channel->name,chan->name))
2052                                 {
2053                                         if (d->chans[i].uc_modes & UCMODE_VOICE)
2054                                         {
2055                                                 /* mode already set on user, dont allow multiple */
2056                                                 return 0;
2057                                         }
2058                                         d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_VOICE;
2059                                         log(DEBUG,"gave voice: %s %s",d->chans[i].channel->name,d->nick);
2060                                         return 1;
2061                                 }
2062                         }
2063                 }
2064         }
2065         return 1;
2066 }
2067
2068 int take_ops(userrec *user,char *dest,chanrec *chan,int status)
2069 {
2070         userrec *d;
2071         int i;
2072         
2073         if ((!user) || (!dest) || (!chan))
2074         {
2075                 log(DEFAULT,"*** BUG *** take_ops was given an invalid parameter");
2076                 return 0;
2077         }
2078         if (status < STATUS_OP)
2079         {
2080                 log(DEBUG,"%s cant give ops to %s because they have status %d and needs %d",user->nick,dest,status,STATUS_OP);
2081                 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
2082                 return 0;
2083         }
2084         else
2085         {
2086                 d = Find(dest);
2087                 if (!isnick(dest))
2088                 {
2089                         log(DEBUG,"take_ops was given an invalid target nickname of %s",dest);
2090                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
2091                         return 0;
2092                 }
2093                 if (!d)
2094                 {
2095                         log(DEBUG,"take_ops couldnt resolve the target nickname: %s",dest);
2096                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
2097                         return 0;
2098                 }
2099                 else
2100                 {
2101                         for (int i = 0; i != MAXCHANS; i++)
2102                         {
2103                                 if ((d->chans[i].channel != NULL) && (chan != NULL))
2104                                 if (!strcasecmp(d->chans[i].channel->name,chan->name))
2105                                 {
2106                                         if ((d->chans[i].uc_modes & UCMODE_OP) == 0)
2107                                         {
2108                                                 /* mode already set on user, dont allow multiple */
2109                                                 return 0;
2110                                         }
2111                                         d->chans[i].uc_modes ^= UCMODE_OP;
2112                                         log(DEBUG,"took ops: %s %s",d->chans[i].channel->name,d->nick);
2113                                         return 1;
2114                                 }
2115                         }
2116                         log(DEBUG,"take_ops couldnt locate the target channel in the target users list");
2117                 }
2118         }
2119         return 1;
2120 }
2121
2122 int take_hops(userrec *user,char *dest,chanrec *chan,int status)
2123 {
2124         userrec *d;
2125         int i;
2126         
2127         if ((!user) || (!dest) || (!chan))
2128         {
2129                 log(DEFAULT,"*** BUG *** take_hops was given an invalid parameter");
2130                 return 0;
2131         }
2132         if (status != STATUS_OP)
2133         {
2134                 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
2135                 return 0;
2136         }
2137         else
2138         {
2139                 d = Find(dest);
2140                 if (!isnick(dest))
2141                 {
2142                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
2143                         return 0;
2144                 }
2145                 if (!d)
2146                 {
2147                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
2148                         return 0;
2149                 }
2150                 else
2151                 {
2152                         for (int i = 0; i != MAXCHANS; i++)
2153                         {
2154                                 if ((d->chans[i].channel != NULL) && (chan != NULL))
2155                                 if (!strcasecmp(d->chans[i].channel->name,chan->name))
2156                                 {
2157                                         if ((d->chans[i].uc_modes & UCMODE_HOP) == 0)
2158                                         {
2159                                                 /* mode already set on user, dont allow multiple */
2160                                                 return 0;
2161                                         }
2162                                         d->chans[i].uc_modes ^= UCMODE_HOP;
2163                                         log(DEBUG,"took h-ops: %s %s",d->chans[i].channel->name,d->nick);
2164                                         return 1;
2165                                 }
2166                         }
2167                 }
2168         }
2169         return 1;
2170 }
2171
2172 int take_voice(userrec *user,char *dest,chanrec *chan,int status)
2173 {
2174         userrec *d;
2175         int i;
2176         
2177         if ((!user) || (!dest) || (!chan))
2178         {
2179                 log(DEFAULT,"*** BUG *** take_voice was given an invalid parameter");
2180                 return 0;
2181         }
2182         if (status < STATUS_HOP)
2183         {
2184                 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, chan->name);
2185                 return 0;
2186         }
2187         else
2188         {
2189                 d = Find(dest);
2190                 if (!isnick(dest))
2191                 {
2192                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
2193                         return 0;
2194                 }
2195                 if (!d)
2196                 {
2197                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
2198                         return 0;
2199                 }
2200                 else
2201                 {
2202                         for (int i = 0; i != MAXCHANS; i++)
2203                         {
2204                                 if ((d->chans[i].channel != NULL) && (chan != NULL))
2205                                 if (!strcasecmp(d->chans[i].channel->name,chan->name))
2206                                 {
2207                                         if ((d->chans[i].uc_modes & UCMODE_VOICE) == 0)
2208                                         {
2209                                                 /* mode already set on user, dont allow multiple */
2210                                                 return 0;
2211                                         }
2212                                         d->chans[i].uc_modes ^= UCMODE_VOICE;
2213                                         log(DEBUG,"took voice: %s %s",d->chans[i].channel->name,d->nick);
2214                                         return 1;
2215                                 }
2216                         }
2217                 }
2218         }
2219         return 1;
2220 }
2221
2222 void TidyBan(char *ban)
2223 {
2224         if (!ban) {
2225                 log(DEFAULT,"*** BUG *** TidyBan was given an invalid parameter");
2226                 return;
2227         }
2228         
2229         char temp[MAXBUF],NICK[MAXBUF],IDENT[MAXBUF],HOST[MAXBUF];
2230
2231         strcpy(temp,ban);
2232
2233         char* pos_of_pling = strchr(temp,'!');
2234         char* pos_of_at = strchr(temp,'@');
2235
2236         pos_of_pling[0] = '\0';
2237         pos_of_at[0] = '\0';
2238         pos_of_pling++;
2239         pos_of_at++;
2240
2241         strncpy(NICK,temp,NICKMAX);
2242         strncpy(IDENT,pos_of_pling,IDENTMAX+1);
2243         strncpy(HOST,pos_of_at,160);
2244
2245         sprintf(ban,"%s!%s@%s",NICK,IDENT,HOST);
2246 }
2247
2248 int add_ban(userrec *user,char *dest,chanrec *chan,int status)
2249 {
2250         if ((!user) || (!dest) || (!chan)) {
2251                 log(DEFAULT,"*** BUG *** add_ban was given an invalid parameter");
2252                 return 0;
2253         }
2254
2255         BanItem b;
2256         if ((!user) || (!dest) || (!chan))
2257                 return 0;
2258         if (strchr(dest,'!')==0)
2259                 return 0;
2260         if (strchr(dest,'@')==0)
2261                 return 0;
2262         for (int i = 0; i < strlen(dest); i++)
2263                 if (dest[i] < 32)
2264                         return 0;
2265         for (int i = 0; i < strlen(dest); i++)
2266                 if (dest[i] > 126)
2267                         return 0;
2268         int c = 0;
2269         for (int i = 0; i < strlen(dest); i++)
2270                 if (dest[i] == '!')
2271                         c++;
2272         if (c>1)
2273                 return 0;
2274         c = 0;
2275         for (int i = 0; i < strlen(dest); i++)
2276                 if (dest[i] == '@')
2277                         c++;
2278         if (c>1)
2279                 return 0;
2280         log(DEBUG,"add_ban: %s %s",chan->name,user->nick);
2281
2282         TidyBan(dest);
2283         for (BanList::iterator i = chan->bans.begin(); i != chan->bans.end(); i++)
2284         {
2285                 if (!strcasecmp(i->data,dest))
2286                 {
2287                         // dont allow a user to set the same ban twice
2288                         return 0;
2289                 }
2290         }
2291
2292         b.set_time = time(NULL);
2293         strncpy(b.data,dest,MAXBUF);
2294         strncpy(b.set_by,user->nick,NICKMAX);
2295         chan->bans.push_back(b);
2296         return 1;
2297 }
2298
2299 int take_ban(userrec *user,char *dest,chanrec *chan,int status)
2300 {
2301         if ((!user) || (!dest) || (!chan)) {
2302                 log(DEFAULT,"*** BUG *** take_ban was given an invalid parameter");
2303                 return 0;
2304         }
2305
2306         log(DEBUG,"del_ban: %s %s",chan->name,user->nick);
2307         for (BanList::iterator i = chan->bans.begin(); i != chan->bans.end(); i++)
2308         {
2309                 if (!strcasecmp(i->data,dest))
2310                 {
2311                         chan->bans.erase(i);
2312                         return 1;
2313                 }
2314         }
2315         return 0;
2316 }
2317
2318 void process_modes(char **parameters,userrec* user,chanrec *chan,int status, int pcnt, bool servermode, bool silent, bool local)
2319 {
2320         if (!parameters) {
2321                 log(DEFAULT,"*** BUG *** process_modes was given an invalid parameter");
2322                 return;
2323         }
2324
2325         char modelist[MAXBUF];
2326         char outlist[MAXBUF];
2327         char outstr[MAXBUF];
2328         char outpars[32][MAXBUF];
2329         int param = 2;
2330         int pc = 0;
2331         int ptr = 0;
2332         int mdir = 1;
2333         int r = 0;
2334         bool k_set = false, l_set = false;
2335
2336         if (pcnt < 2)
2337         {
2338                 return;
2339         }
2340
2341         log(DEBUG,"process_modes: start: parameters=%d",pcnt);
2342
2343         strcpy(modelist,parameters[1]); /* mode list, e.g. +oo-o */
2344                                         /* parameters[2] onwards are parameters for
2345                                          * modes that require them :) */
2346         strcpy(outlist,"+");
2347         mdir = 1;
2348
2349         log(DEBUG,"process_modes: modelist: %s",modelist);
2350
2351         for (ptr = 0; ptr < strlen(modelist); ptr++)
2352         {
2353                 r = 0;
2354
2355                 {
2356                         log(DEBUG,"process_modes: modechar: %c",modelist[ptr]);
2357                         char modechar = modelist[ptr];
2358                         switch (modelist[ptr])
2359                         {
2360                                 case '-':
2361                                         if (mdir != 0)
2362                                         {
2363                                                 if ((outlist[strlen(outlist)-1] == '+') || (outlist[strlen(outlist)-1] == '-'))
2364                                                 {
2365                                                         outlist[strlen(outlist)-1] = '-';
2366                                                 }
2367                                                 else
2368                                                 {
2369                                                         strcat(outlist,"-");
2370                                                 }
2371                                         }
2372                                         mdir = 0;
2373                                         
2374                                 break;                  
2375
2376                                 case '+':
2377                                         if (mdir != 1)
2378                                         {
2379                                                 if ((outlist[strlen(outlist)-1] == '+') || (outlist[strlen(outlist)-1] == '-'))
2380                                                 {
2381                                                         outlist[strlen(outlist)-1] = '+';
2382                                                 }
2383                                                 else
2384                                                 {
2385                                                         strcat(outlist,"+");
2386                                                 }
2387                                         }
2388                                         mdir = 1;
2389                                 break;
2390
2391                                 case 'o':
2392                                         log(DEBUG,"Ops");
2393                                         if ((param >= pcnt)) break;
2394                                         log(DEBUG,"Enough parameters left");
2395                                         if (mdir == 1)
2396                                         {
2397                                                 log(DEBUG,"calling give_ops");
2398                                                 r = give_ops(user,parameters[param++],chan,status);
2399                                         }
2400                                         else
2401                                         {
2402                                                 log(DEBUG,"calling take_ops");
2403                                                 r = take_ops(user,parameters[param++],chan,status);
2404                                         }
2405                                         if (r)
2406                                         {
2407                                                 strcat(outlist,"o");
2408                                                 strcpy(outpars[pc++],parameters[param-1]);
2409                                         }
2410                                 break;
2411                         
2412                                 case 'h':
2413                                         if ((param >= pcnt)) break;
2414                                         if (mdir == 1)
2415                                         {
2416                                                 r = give_hops(user,parameters[param++],chan,status);
2417                                         }
2418                                         else
2419                                         {
2420                                                 r = take_hops(user,parameters[param++],chan,status);
2421                                         }
2422                                         if (r)
2423                                         {
2424                                                 strcat(outlist,"h");
2425                                                 strcpy(outpars[pc++],parameters[param-1]);
2426                                         }
2427                                 break;
2428                         
2429                                 
2430                                 case 'v':
2431                                         if ((param >= pcnt)) break;
2432                                         if (mdir == 1)
2433                                         {
2434                                                 r = give_voice(user,parameters[param++],chan,status);
2435                                         }
2436                                         else
2437                                         {
2438                                                 r = take_voice(user,parameters[param++],chan,status);
2439                                         }
2440                                         if (r)
2441                                         {
2442                                                 strcat(outlist,"v");
2443                                                 strcpy(outpars[pc++],parameters[param-1]);
2444                                         }
2445                                 break;
2446                                 
2447                                 case 'b':
2448                                         if ((param >= pcnt)) break;
2449                                         if (mdir == 1)
2450                                         {
2451                                                 r = add_ban(user,parameters[param++],chan,status);
2452                                         }
2453                                         else
2454                                         {
2455                                                 r = take_ban(user,parameters[param++],chan,status);
2456                                         }
2457                                         if (r)
2458                                         {
2459                                                 strcat(outlist,"b");
2460                                                 strcpy(outpars[pc++],parameters[param-1]);
2461                                         }
2462                                 break;
2463
2464
2465                                 case 'k':
2466                                         if ((param >= pcnt))
2467                                                 break;
2468
2469                                         if (mdir == 1)
2470                                         {
2471                                                 if (k_set)
2472                                                         break;
2473                                                 
2474                                                 if (!strcmp(chan->key,""))
2475                                                 {
2476                                                         strcat(outlist,"k");
2477                                                         char key[MAXBUF];
2478                                                         strcpy(key,parameters[param++]);
2479                                                         if (strlen(key)>32) {
2480                                                                 key[31] = '\0';
2481                                                         }
2482                                                         strcpy(outpars[pc++],key);
2483                                                         strcpy(chan->key,key);
2484                                                         k_set = true;
2485                                                 }
2486                                         }
2487                                         else
2488                                         {
2489                                                 /* checks on -k are case sensitive and only accurate to the
2490                                                    first 32 characters */
2491                                                 char key[MAXBUF];
2492                                                 strcpy(key,parameters[param++]);
2493                                                 if (strlen(key)>32) {
2494                                                         key[31] = '\0';
2495                                                 }
2496                                                 /* only allow -k if correct key given */
2497                                                 if (!strcmp(chan->key,key))
2498                                                 {
2499                                                         strcat(outlist,"k");
2500                                                         strcpy(chan->key,"");
2501                                                         strcpy(outpars[pc++],key);
2502                                                 }
2503                                         }
2504                                 break;
2505                                 
2506                                 case 'l':
2507                                         if (mdir == 0)
2508                                         {
2509                                                 if (chan->limit)
2510                                                 {
2511                                                         strcat(outlist,"l");
2512                                                         chan->limit = 0;
2513                                                 }
2514                                         }
2515                                         
2516                                         if ((param >= pcnt)) break;
2517                                         if (mdir == 1)
2518                                         {
2519                                                 if (l_set)
2520                                                         break;
2521                                                 
2522                                                 bool invalid = false;
2523                                                 for (int i = 0; i < strlen(parameters[param]); i++)
2524                                                 {
2525                                                         if ((parameters[param][i] < '0') || (parameters[param][i] > '9'))
2526                                                         {
2527                                                                 invalid = true;
2528                                                         }
2529                                                 }
2530                                                 if (atoi(parameters[param]) < 1)
2531                                                 {
2532                                                         invalid = true;
2533                                                 }
2534
2535                                                 if (invalid)
2536                                                         break;
2537                                                 
2538                                                 chan->limit = atoi(parameters[param]);
2539                                                 if (chan->limit)
2540                                                 {
2541                                                         strcat(outlist,"l");
2542                                                         strcpy(outpars[pc++],parameters[param++]);
2543                                                         l_set = true;
2544                                                 }
2545                                         }
2546                                 break;
2547                                 
2548                                 case 'i':
2549                                         if (chan->inviteonly != mdir)
2550                                         {
2551                                                 strcat(outlist,"i");
2552                                         }
2553                                         chan->inviteonly = mdir;
2554                                 break;
2555                                 
2556                                 case 't':
2557                                         if (chan->topiclock != mdir)
2558                                         {
2559                                                 strcat(outlist,"t");
2560                                         }
2561                                         chan->topiclock = mdir;
2562                                 break;
2563                                 
2564                                 case 'n':
2565                                         if (chan->noexternal != mdir)
2566                                         {
2567                                                 strcat(outlist,"n");
2568                                         }
2569                                         chan->noexternal = mdir;
2570                                 break;
2571                                 
2572                                 case 'm':
2573                                         if (chan->moderated != mdir)
2574                                         {
2575                                                 strcat(outlist,"m");
2576                                         }
2577                                         chan->moderated = mdir;
2578                                 break;
2579                                 
2580                                 case 's':
2581                                         if (chan->secret != mdir)
2582                                         {
2583                                                 strcat(outlist,"s");
2584                                                 if (chan->c_private)
2585                                                 {
2586                                                         chan->c_private = 0;
2587                                                         if (mdir)
2588                                                         {
2589                                                                 strcat(outlist,"-p+");
2590                                                         }
2591                                                         else
2592                                                         {
2593                                                                 strcat(outlist,"+p-");
2594                                                         }
2595                                                 }
2596                                         }
2597                                         chan->secret = mdir;
2598                                 break;
2599                                 
2600                                 case 'p':
2601                                         if (chan->c_private != mdir)
2602                                         {
2603                                                 strcat(outlist,"p");
2604                                                 if (chan->secret)
2605                                                 {
2606                                                         chan->secret = 0;
2607                                                         if (mdir)
2608                                                         {
2609                                                                 strcat(outlist,"-s+");
2610                                                         }
2611                                                         else
2612                                                         {
2613                                                                 strcat(outlist,"+s-");
2614                                                         }
2615                                                 }
2616                                         }
2617                                         chan->c_private = mdir;
2618                                 break;
2619                                 
2620                                 default:
2621                                         log(DEBUG,"Preprocessing custom mode %c",modechar);
2622                                         string_list p;
2623                                         p.clear();
2624                                         if (((!strchr(chan->custom_modes,modechar)) && (!mdir)) || ((strchr(chan->custom_modes,modechar)) && (mdir)))
2625                                         {
2626                                                 log(DEBUG,"Mode %c isnt set on %s but trying to remove!",modechar,chan->name);
2627                                                 break;
2628                                         }
2629                                         if (ModeDefined(modechar,MT_CHANNEL))
2630                                         {
2631                                                 log(DEBUG,"A module has claimed this mode");
2632                                                 if (param<pcnt)
2633                                                 {
2634                                                         if ((ModeDefinedOn(modechar,MT_CHANNEL)>0) && (mdir))
2635                                                         {
2636                                                                 p.push_back(parameters[param]);
2637                                                         }
2638                                                         if ((ModeDefinedOff(modechar,MT_CHANNEL)>0) && (!mdir))
2639                                                         {
2640                                                                 p.push_back(parameters[param]);
2641                                                         }
2642                                                 }
2643                                                 bool handled = false;
2644                                                 if (param>=pcnt)
2645                                                 {
2646                                                         log(DEBUG,"Not enough parameters for module-mode %c",modechar);
2647                                                         // we're supposed to have a parameter, but none was given... so dont handle the mode.
2648                                                         if (((ModeDefinedOn(modechar,MT_CHANNEL)>0) && (mdir)) || ((ModeDefinedOff(modechar,MT_CHANNEL)>0) && (!mdir))) 
2649                                                         {
2650                                                                 handled = true;
2651                                                                 param++;
2652                                                         }
2653                                                 }
2654                                                 for (int i = 0; i <= MODCOUNT; i++)
2655                                                 {
2656                                                         if (!handled)
2657                                                         {
2658                                                                 if (modules[i]->OnExtendedMode(user,chan,modechar,MT_CHANNEL,mdir,p))
2659                                                                 {
2660                                                                         log(DEBUG,"OnExtendedMode returned nonzero for a module");
2661                                                                         char app[] = {modechar, 0};
2662                                                                         if (ptr>0)
2663                                                                         {
2664                                                                                 if ((modelist[ptr-1] == '+') || (modelist[ptr-1] == '-'))
2665                                                                                 {
2666                                                                                         strcat(outlist, app);
2667                                                                                 }
2668                                                                                 else if (!strchr(outlist,modechar))
2669                                                                                 {
2670                                                                                         strcat(outlist, app);
2671                                                                                 }
2672                                                                         }
2673                                                                         chan->SetCustomMode(modechar,mdir);
2674                                                                         // include parameters in output if mode has them
2675                                                                         if ((ModeDefinedOn(modechar,MT_CHANNEL)>0) && (mdir))
2676                                                                         {
2677                                                                                 chan->SetCustomModeParam(modelist[ptr],parameters[param],mdir);
2678                                                                                 strcpy(outpars[pc++],parameters[param++]);
2679                                                                         }
2680                                                                         // break, because only one module can handle the mode.
2681                                                                         handled = true;
2682                                                                 }
2683                                                         }
2684                                                 }
2685                                         }
2686                                 break;
2687                                 
2688                         }
2689                 }
2690         }
2691
2692         /* this ensures only the *valid* modes are sent out onto the network */
2693         while ((outlist[strlen(outlist)-1] == '-') || (outlist[strlen(outlist)-1] == '+'))
2694         {
2695                 outlist[strlen(outlist)-1] = '\0';
2696         }
2697         if (strcmp(outlist,""))
2698         {
2699                 strcpy(outstr,outlist);
2700                 for (ptr = 0; ptr < pc; ptr++)
2701                 {
2702                         strcat(outstr," ");
2703                         strcat(outstr,outpars[ptr]);
2704                 }
2705                 if (local)
2706                 {
2707                         log(DEBUG,"Local mode change");
2708                         WriteChannelLocal(chan, user, "MODE %s %s",chan->name,outstr);
2709                 }
2710                 else
2711                 {
2712                         if (servermode)
2713                         {
2714                                 if (!silent)
2715                                 {
2716                                         WriteChannelWithServ(ServerName,chan,user,"MODE %s %s",chan->name,outstr);
2717                                         // M token for a usermode must go to all servers
2718                                         char buffer[MAXBUF];
2719                                         snprintf(buffer,MAXBUF,"M %s %s",chan->name, outstr);
2720                                         NetSendToAll(buffer);
2721                                 }
2722                                         
2723                         }
2724                         else
2725                         {
2726                                 if (!silent)
2727                                 {
2728                                         WriteChannel(chan,user,"MODE %s %s",chan->name,outstr);
2729                                         // M token for a usermode must go to all servers
2730                                         char buffer[MAXBUF];
2731                                         snprintf(buffer,MAXBUF,"m %s %s %s",user->nick,chan->name, outstr);
2732                                         NetSendToAll(buffer);
2733                                 }
2734                         }
2735                 }
2736         }
2737 }
2738
2739 // based on sourcemodes, return true or false to determine if umode is a valid mode a user may set on themselves or others.
2740
2741 bool allowed_umode(char umode, char* sourcemodes,bool adding)
2742 {
2743         log(DEBUG,"Allowed_umode: %c %s",umode,sourcemodes);
2744         // RFC1459 specified modes
2745         if ((umode == 'w') || (umode == 's') || (umode == 'i'))
2746         {
2747                 log(DEBUG,"umode %c allowed by RFC1459 scemantics",umode);
2748                 return true;
2749         }
2750         
2751         // user may not +o themselves or others, but an oper may de-oper other opers or themselves
2752         if ((strchr(sourcemodes,'o')) && (!adding))
2753         {
2754                 log(DEBUG,"umode %c allowed by RFC1459 scemantics",umode);
2755                 return true;
2756         }
2757         else if (umode == 'o')
2758         {
2759                 log(DEBUG,"umode %c allowed by RFC1459 scemantics",umode);
2760                 return false;
2761         }
2762         
2763         // process any module-defined modes that need oper
2764         if ((ModeDefinedOper(umode,MT_CLIENT)) && (strchr(sourcemodes,'o')))
2765         {
2766                 log(DEBUG,"umode %c allowed by module handler (oper only mode)",umode);
2767                 return true;
2768         }
2769         else
2770         if (ModeDefined(umode,MT_CLIENT))
2771         {
2772                 // process any module-defined modes that don't need oper
2773                 log(DEBUG,"umode %c allowed by module handler (non-oper mode)",umode);
2774                 if ((ModeDefinedOper(umode,MT_CLIENT)) && (!strchr(sourcemodes,'o')))
2775                 {
2776                         // no, this mode needs oper, and this user 'aint got what it takes!
2777                         return false;
2778                 }
2779                 return true;
2780         }
2781
2782         // anything else - return false.
2783         log(DEBUG,"umode %c not known by any ruleset",umode);
2784         return false;
2785 }
2786
2787 bool process_module_umode(char umode, userrec* source, void* dest, bool adding)
2788 {
2789         userrec* s2;
2790         bool faked = false;
2791         if (!source)
2792         {
2793                 s2 = new userrec;
2794                 strncpy(s2->nick,ServerName,NICKMAX);
2795                 strcpy(s2->modes,"o");
2796                 s2->fd = -1;
2797                 source = s2;
2798                 faked = true;
2799         }
2800         string_list p;
2801         p.clear();
2802         if (ModeDefined(umode,MT_CLIENT))
2803         {
2804                 for (int i = 0; i <= MODCOUNT; i++)
2805                 {
2806                         if (modules[i]->OnExtendedMode(source,(void*)dest,umode,MT_CLIENT,adding,p))
2807                         {
2808                                 log(DEBUG,"Module claims umode %c",umode);
2809                                 return true;
2810                         }
2811                 }
2812                 log(DEBUG,"No module claims umode %c",umode);
2813                 if (faked)
2814                 {
2815                         delete s2;
2816                         source = NULL;
2817                 }
2818                 return false;
2819         }
2820         else
2821         {
2822                 log(DEBUG,"*** BUG *** Non-module umode passed to process_module_umode!");
2823                 if (faked)
2824                 {
2825                         delete s2;
2826                         source = NULL;
2827                 }
2828                 return false;
2829         }
2830 }
2831
2832 void handle_mode(char **parameters, int pcnt, userrec *user)
2833 {
2834         chanrec* Ptr;
2835         userrec* dest;
2836         int can_change,i;
2837         int direction = 1;
2838         char outpars[MAXBUF];
2839
2840         dest = Find(parameters[0]);
2841
2842         if (!user)
2843         {
2844                 return;
2845         }
2846
2847         if ((dest) && (pcnt == 1))
2848         {
2849                 WriteServ(user->fd,"221 %s :+%s",user->nick,user->modes);
2850                 return;
2851         }
2852
2853         if ((dest) && (pcnt > 1))
2854         {
2855                 char dmodes[MAXBUF];
2856                 strncpy(dmodes,dest->modes,MAXBUF);
2857                 log(DEBUG,"pulled up dest user modes: %s",dmodes);
2858         
2859                 can_change = 0;
2860                 if (user != dest)
2861                 {
2862                         if (strchr(user->modes,'o'))
2863                         {
2864                                 can_change = 1;
2865                         }
2866                 }
2867                 else
2868                 {
2869                         can_change = 1;
2870                 }
2871                 if (!can_change)
2872                 {
2873                         WriteServ(user->fd,"482 %s :Can't change mode for other users",user->nick);
2874                         return;
2875                 }
2876                 
2877                 strcpy(outpars,"+");
2878                 direction = 1;
2879
2880                 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
2881                         return;
2882
2883                 for (int i = 0; i < strlen(parameters[1]); i++)
2884                 {
2885                         if (parameters[1][i] == '+')
2886                         {
2887                                 if (direction != 1)
2888                                 {
2889                                         if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2890                                         {
2891                                                 outpars[strlen(outpars)-1] = '+';
2892                                         }
2893                                         else
2894                                         {
2895                                                 strcat(outpars,"+");
2896                                         }
2897                                 }
2898                                 direction = 1;
2899                         }
2900                         else
2901                         if (parameters[1][i] == '-')
2902                         {
2903                                 if (direction != 0)
2904                                 {
2905                                         if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2906                                         {
2907                                                 outpars[strlen(outpars)-1] = '-';
2908                                         }
2909                                         else
2910                                         {
2911                                                 strcat(outpars,"-");
2912                                         }
2913                                 }
2914                                 direction = 0;
2915                         }
2916                         else
2917                         {
2918                                 can_change = 0;
2919                                 if (strchr(user->modes,'o'))
2920                                 {
2921                                         can_change = 1;
2922                                 }
2923                                 else
2924                                 {
2925                                         if ((parameters[1][i] == 'i') || (parameters[1][i] == 'w') || (parameters[1][i] == 's') || (allowed_umode(parameters[1][i],user->modes,direction)))
2926                                         {
2927                                                 can_change = 1;
2928                                         }
2929                                 }
2930                                 if (can_change)
2931                                 {
2932                                         if (direction == 1)
2933                                         {
2934                                                 if ((!strchr(dmodes,parameters[1][i])) && (allowed_umode(parameters[1][i],user->modes,true)))
2935                                                 {
2936                                                         char umode = parameters[1][i];
2937                                                         if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
2938                                                         {
2939                                                                 dmodes[strlen(dmodes)+1]='\0';
2940                                                                 dmodes[strlen(dmodes)] = parameters[1][i];
2941                                                                 outpars[strlen(outpars)+1]='\0';
2942                                                                 outpars[strlen(outpars)] = parameters[1][i];
2943                                                         }
2944                                                 }
2945                                         }
2946                                         else
2947                                         {
2948                                                 if ((allowed_umode(parameters[1][i],user->modes,false)) && (strchr(dmodes,parameters[1][i])))
2949                                                 {
2950                                                         char umode = parameters[1][i];
2951                                                         if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
2952                                                         {
2953                                                                 int q = 0;
2954                                                                 char temp[MAXBUF];      
2955                                                                 char moo[MAXBUF];       
2956
2957                                                                 outpars[strlen(outpars)+1]='\0';
2958                                                                 outpars[strlen(outpars)] = parameters[1][i];
2959                                                         
2960                                                                 strcpy(temp,"");
2961                                                                 for (q = 0; q < strlen(dmodes); q++)
2962                                                                 {
2963                                                                         if (dmodes[q] != parameters[1][i])
2964                                                                         {
2965                                                                                 moo[0] = dmodes[q];
2966                                                                                 moo[1] = '\0';
2967                                                                                 strcat(temp,moo);
2968                                                                         }
2969                                                                 }
2970                                                                 strcpy(dmodes,temp);
2971                                                         }
2972                                                 }
2973                                         }
2974                                 }
2975                         }
2976                 }
2977                 if (strlen(outpars))
2978                 {
2979                         char b[MAXBUF];
2980                         strcpy(b,"");
2981                         int z = 0;
2982                         int i = 0;
2983                         while (i < strlen (outpars))
2984                         {
2985                                 b[z++] = outpars[i++];
2986                                 b[z] = '\0';
2987                                 if (i<strlen(outpars)-1)
2988                                 {
2989                                         if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
2990                                         {
2991                                                 // someones playing silly buggers and trying
2992                                                 // to put a +- or -+ into the line...
2993                                                 i++;
2994                                         }
2995                                 }
2996                                 if (i == strlen(outpars)-1)
2997                                 {
2998                                         if ((outpars[i] == '-') || (outpars[i] == '+'))
2999                                         {
3000                                                 i++;
3001                                         }
3002                                 }
3003                         }
3004
3005                         z = strlen(b)-1;
3006                         if ((b[z] == '-') || (b[z] == '+'))
3007                                 b[z] == '\0';
3008
3009                         if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
3010                                 return;
3011
3012                         WriteTo(user, dest, "MODE %s :%s", dest->nick, b);
3013
3014                         // M token for a usermode must go to all servers
3015                         char buffer[MAXBUF];
3016                         snprintf(buffer,MAXBUF,"m %s %s %s",user->nick, dest->nick, b);
3017                         NetSendToAll(buffer);
3018
3019                         if (strlen(dmodes)>MAXMODES)
3020                         {
3021                                 dmodes[MAXMODES-1] = '\0';
3022                         }
3023                         log(DEBUG,"Stripped mode line");
3024                         log(DEBUG,"Line dest is now %s",dmodes);
3025                         strncpy(dest->modes,dmodes,MAXMODES);
3026
3027                 }
3028
3029                 return;
3030         }
3031         
3032         Ptr = FindChan(parameters[0]);
3033         if (Ptr)
3034         {
3035                 if (pcnt == 1)
3036                 {
3037                         /* just /modes #channel */
3038                         WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name, chanmodes(Ptr));
3039                         WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
3040                         return;
3041                 }
3042                 else
3043                 if (pcnt == 2)
3044                 {
3045                         if ((!strcmp(parameters[1],"+b")) || (!strcmp(parameters[1],"b")))
3046                         {
3047
3048                                 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
3049                                 {
3050                                         WriteServ(user->fd,"367 %s %s %s %s %d",user->nick, Ptr->name, i->data, i->set_by, i->set_time);
3051                                 }
3052                                 WriteServ(user->fd,"368 %s %s :End of channel ban list",user->nick, Ptr->name);
3053                                 return;
3054                         }
3055                 }
3056
3057                 if ((cstatus(user,Ptr) < STATUS_HOP) && (Ptr))
3058                 {
3059                         WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, Ptr->name);
3060                         return;
3061                 }
3062
3063                 process_modes(parameters,user,Ptr,cstatus(user,Ptr),pcnt,false,false,false);
3064         }
3065         else
3066         {
3067                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3068         }
3069 }
3070
3071
3072
3073
3074 void server_mode(char **parameters, int pcnt, userrec *user)
3075 {
3076         chanrec* Ptr;
3077         userrec* dest;
3078         int can_change,i;
3079         int direction = 1;
3080         char outpars[MAXBUF];
3081
3082         dest = Find(parameters[0]);
3083         
3084         // fix: ChroNiCk found this - we cant use this as debug if its null!
3085         if (dest)
3086         {
3087                 log(DEBUG,"server_mode on %s",dest->nick);
3088         }
3089
3090         if ((dest) && (pcnt > 1))
3091         {
3092                 log(DEBUG,"params > 1");
3093
3094                 char dmodes[MAXBUF];
3095                 strncpy(dmodes,dest->modes,MAXBUF);
3096
3097                 strcpy(outpars,"+");
3098                 direction = 1;
3099
3100                 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
3101                         return;
3102
3103                 for (int i = 0; i < strlen(parameters[1]); i++)
3104                 {
3105                         if (parameters[1][i] == '+')
3106                         {
3107                                 if (direction != 1)
3108                                 {
3109                                         if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
3110                                         {
3111                                                 outpars[strlen(outpars)-1] = '+';
3112                                         }
3113                                         else
3114                                         {
3115                                                 strcat(outpars,"+");
3116                                         }
3117                                 }
3118                                 direction = 1;
3119                         }
3120                         else
3121                         if (parameters[1][i] == '-')
3122                         {
3123                                 if (direction != 0)
3124                                 {
3125                                         if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
3126                                         {
3127                                                 outpars[strlen(outpars)-1] = '-';
3128                                         }
3129                                         else
3130                                         {
3131                                                 strcat(outpars,"-");
3132                                         }
3133                                 }
3134                                 direction = 0;
3135                         }
3136                         else
3137                         {
3138                                 log(DEBUG,"begin mode processing entry");
3139                                 can_change = 1;
3140                                 if (can_change)
3141                                 {
3142                                         if (direction == 1)
3143                                         {
3144                                                 log(DEBUG,"umode %c being added",parameters[1][i]);
3145                                                 if ((!strchr(dmodes,parameters[1][i])) && (allowed_umode(parameters[1][i],user->modes,true)))
3146                                                 {
3147                                                         char umode = parameters[1][i];
3148                                                         log(DEBUG,"umode %c is an allowed umode",umode);
3149                                                         if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
3150                                                         {
3151                                                                 dmodes[strlen(dmodes)+1]='\0';
3152                                                                 dmodes[strlen(dmodes)] = parameters[1][i];
3153                                                                 outpars[strlen(outpars)+1]='\0';
3154                                                                 outpars[strlen(outpars)] = parameters[1][i];
3155                                                         }
3156                                                 }
3157                                         }
3158                                         else
3159                                         {
3160                                                 // can only remove a mode they already have
3161                                                 log(DEBUG,"umode %c being removed",parameters[1][i]);
3162                                                 if ((allowed_umode(parameters[1][i],user->modes,false)) && (strchr(dmodes,parameters[1][i])))
3163                                                 {
3164                                                         char umode = parameters[1][i];
3165                                                         log(DEBUG,"umode %c is an allowed umode",umode);
3166                                                         if ((process_module_umode(umode, user, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
3167                                                         {
3168                                                                 int q = 0;
3169                                                                 char temp[MAXBUF];
3170                                                                 char moo[MAXBUF];       
3171
3172                                                                 outpars[strlen(outpars)+1]='\0';
3173                                                                 outpars[strlen(outpars)] = parameters[1][i];
3174                                                         
3175                                                                 strcpy(temp,"");
3176                                                                 for (q = 0; q < strlen(dmodes); q++)
3177                                                                 {
3178                                                                         if (dmodes[q] != parameters[1][i])
3179                                                                         {
3180                                                                                 moo[0] = dmodes[q];
3181                                                                                 moo[1] = '\0';
3182                                                                                 strcat(temp,moo);
3183                                                                         }
3184                                                                 }
3185                                                                 strcpy(dmodes,temp);
3186                                                         }
3187                                                 }
3188                                         }
3189                                 }
3190                         }
3191                 }
3192                 if (strlen(outpars))
3193                 {
3194                         char b[MAXBUF];
3195                         strcpy(b,"");
3196                         int z = 0;
3197                         int i = 0;
3198                         while (i < strlen (outpars))
3199                         {
3200                                 b[z++] = outpars[i++];
3201                                 b[z] = '\0';
3202                                 if (i<strlen(outpars)-1)
3203                                 {
3204                                         if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
3205                                         {
3206                                                 // someones playing silly buggers and trying
3207                                                 // to put a +- or -+ into the line...
3208                                                 i++;
3209                                         }
3210                                 }
3211                                 if (i == strlen(outpars)-1)
3212                                 {
3213                                         if ((outpars[i] == '-') || (outpars[i] == '+'))
3214                                         {
3215                                                 i++;
3216                                         }
3217                                 }
3218                         }
3219
3220                         z = strlen(b)-1;
3221                         if ((b[z] == '-') || (b[z] == '+'))
3222                                 b[z] == '\0';
3223
3224                         if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
3225                                 return;
3226
3227                         WriteTo(user, dest, "MODE %s :%s", dest->nick, b);
3228
3229                         // M token for a usermode must go to all servers
3230                         char buffer[MAXBUF];
3231                         snprintf(buffer,MAXBUF,"m %s %s %s",user->nick, dest->nick, b);
3232                         NetSendToAll(buffer);
3233                         
3234                         if (strlen(dmodes)>MAXMODES)
3235                         {
3236                                 dmodes[MAXMODES-1] = '\0';
3237                         }
3238                         log(DEBUG,"Stripped mode line");
3239                         log(DEBUG,"Line dest is now %s",dmodes);
3240                         strncpy(dest->modes,dmodes,MAXMODES);
3241
3242                 }
3243
3244                 return;
3245         }
3246         
3247         Ptr = FindChan(parameters[0]);
3248         if (Ptr)
3249         {
3250                 process_modes(parameters,user,Ptr,STATUS_OP,pcnt,true,false,false);
3251         }
3252         else
3253         {
3254                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3255         }
3256 }
3257
3258
3259
3260 void merge_mode(char **parameters, int pcnt)
3261 {
3262         chanrec* Ptr;
3263         userrec* dest;
3264         int can_change,i;
3265         int direction = 1;
3266         char outpars[MAXBUF];
3267
3268         dest = Find(parameters[0]);
3269         
3270         // fix: ChroNiCk found this - we cant use this as debug if its null!
3271         if (dest)
3272         {
3273                 log(DEBUG,"merge_mode on %s",dest->nick);
3274         }
3275
3276         if ((dest) && (pcnt > 1))
3277         {
3278                 log(DEBUG,"params > 1");
3279
3280                 char dmodes[MAXBUF];
3281                 strncpy(dmodes,dest->modes,MAXBUF);
3282
3283                 strcpy(outpars,"+");
3284                 direction = 1;
3285
3286                 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
3287                         return;
3288
3289                 for (int i = 0; i < strlen(parameters[1]); i++)
3290                 {
3291                         if (parameters[1][i] == '+')
3292                         {
3293                                 if (direction != 1)
3294                                 {
3295                                         if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
3296                                         {
3297                                                 outpars[strlen(outpars)-1] = '+';
3298                                         }
3299                                         else
3300                                         {
3301                                                 strcat(outpars,"+");
3302                                         }
3303                                 }
3304                                 direction = 1;
3305                         }
3306                         else
3307                         if (parameters[1][i] == '-')
3308                         {
3309                                 if (direction != 0)
3310                                 {
3311                                         if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
3312                                         {
3313                                                 outpars[strlen(outpars)-1] = '-';
3314                                         }
3315                                         else
3316                                         {
3317                                                 strcat(outpars,"-");
3318                                         }
3319                                 }
3320                                 direction = 0;
3321                         }
3322                         else
3323                         {
3324                                 log(DEBUG,"begin mode processing entry");
3325                                 can_change = 1;
3326                                 if (can_change)
3327                                 {
3328                                         if (direction == 1)
3329                                         {
3330                                                 log(DEBUG,"umode %c being added",parameters[1][i]);
3331                                                 if ((!strchr(dmodes,parameters[1][i])) && (allowed_umode(parameters[1][i],"o",true)))
3332                                                 {
3333                                                         char umode = parameters[1][i];
3334                                                         log(DEBUG,"umode %c is an allowed umode",umode);
3335                                                         if ((process_module_umode(umode, NULL, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
3336                                                         {
3337                                                                 dmodes[strlen(dmodes)+1]='\0';
3338                                                                 dmodes[strlen(dmodes)] = parameters[1][i];
3339                                                                 outpars[strlen(outpars)+1]='\0';
3340                                                                 outpars[strlen(outpars)] = parameters[1][i];
3341                                                         }
3342                                                 }
3343                                         }
3344                                         else
3345                                         {
3346                                                 // can only remove a mode they already have
3347                                                 log(DEBUG,"umode %c being removed",parameters[1][i]);
3348                                                 if ((allowed_umode(parameters[1][i],"o",false)) && (strchr(dmodes,parameters[1][i])))
3349                                                 {
3350                                                         char umode = parameters[1][i];
3351                                                         log(DEBUG,"umode %c is an allowed umode",umode);
3352                                                         if ((process_module_umode(umode, NULL, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
3353                                                         {
3354                                                                 int q = 0;
3355                                                                 char temp[MAXBUF];
3356                                                                 char moo[MAXBUF];       
3357
3358                                                                 outpars[strlen(outpars)+1]='\0';
3359                                                                 outpars[strlen(outpars)] = parameters[1][i];
3360                                                         
3361                                                                 strcpy(temp,"");
3362                                                                 for (q = 0; q < strlen(dmodes); q++)
3363                                                                 {
3364                                                                         if (dmodes[q] != parameters[1][i])
3365                                                                         {
3366                                                                                 moo[0] = dmodes[q];
3367                                                                                 moo[1] = '\0';
3368                                                                                 strcat(temp,moo);
3369                                                                         }
3370                                                                 }
3371                                                                 strcpy(dmodes,temp);
3372                                                         }
3373                                                 }
3374                                         }
3375                                 }
3376                         }
3377                 }
3378                 if (strlen(outpars))
3379                 {
3380                         char b[MAXBUF];
3381                         strcpy(b,"");
3382                         int z = 0;
3383                         int i = 0;
3384                         while (i < strlen (outpars))
3385                         {
3386                                 b[z++] = outpars[i++];
3387                                 b[z] = '\0';
3388                                 if (i<strlen(outpars)-1)
3389                                 {
3390                                         if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
3391                                         {
3392                                                 // someones playing silly buggers and trying
3393                                                 // to put a +- or -+ into the line...
3394                                                 i++;
3395                                         }
3396                                 }
3397                                 if (i == strlen(outpars)-1)
3398                                 {
3399                                         if ((outpars[i] == '-') || (outpars[i] == '+'))
3400                                         {
3401                                                 i++;
3402                                         }
3403                                 }
3404                         }
3405
3406                         z = strlen(b)-1;
3407                         if ((b[z] == '-') || (b[z] == '+'))
3408                                 b[z] == '\0';
3409
3410                         if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
3411                                 return;
3412
3413                         if (strlen(dmodes)>MAXMODES)
3414                         {
3415                                 dmodes[MAXMODES-1] = '\0';
3416                         }
3417                         log(DEBUG,"Stripped mode line");
3418                         log(DEBUG,"Line dest is now %s",dmodes);
3419                         strncpy(dest->modes,dmodes,MAXMODES);
3420
3421                 }
3422
3423                 return;
3424         }
3425         
3426         Ptr = FindChan(parameters[0]);
3427         if (Ptr)
3428         {
3429                 userrec s2;
3430                 strncpy(s2.nick,ServerName,NICKMAX);
3431                 strcpy(s2.modes,"o");
3432                 s2.fd = -1;
3433                 process_modes(parameters,&s2,Ptr,STATUS_OP,pcnt,true,true,false);
3434         }
3435 }
3436
3437
3438 void merge_mode2(char **parameters, int pcnt, userrec* user)
3439 {
3440         chanrec* Ptr;
3441         userrec* dest;
3442         int can_change,i;
3443         int direction = 1;
3444         char outpars[MAXBUF];
3445
3446         dest = Find(parameters[0]);
3447         
3448         // fix: ChroNiCk found this - we cant use this as debug if its null!
3449         if (dest)
3450         {
3451                 log(DEBUG,"merge_mode on %s",dest->nick);
3452         }
3453
3454         if ((dest) && (pcnt > 1))
3455         {
3456                 log(DEBUG,"params > 1");
3457
3458                 char dmodes[MAXBUF];
3459                 strncpy(dmodes,dest->modes,MAXBUF);
3460
3461                 strcpy(outpars,"+");
3462                 direction = 1;
3463
3464                 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
3465                         return;
3466
3467                 for (int i = 0; i < strlen(parameters[1]); i++)
3468                 {
3469                         if (parameters[1][i] == '+')
3470                         {
3471                                 if (direction != 1)
3472                                 {
3473                                         if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
3474                                         {
3475                                                 outpars[strlen(outpars)-1] = '+';
3476                                         }
3477                                         else
3478                                         {
3479                                                 strcat(outpars,"+");
3480                                         }
3481                                 }
3482                                 direction = 1;
3483                         }
3484                         else
3485                         if (parameters[1][i] == '-')
3486                         {
3487                                 if (direction != 0)
3488                                 {
3489                                         if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
3490                                         {
3491                                                 outpars[strlen(outpars)-1] = '-';
3492                                         }
3493                                         else
3494                                         {
3495                                                 strcat(outpars,"-");
3496                                         }
3497                                 }
3498                                 direction = 0;
3499                         }
3500                         else
3501                         {
3502                                 log(DEBUG,"begin mode processing entry");
3503                                 can_change = 1;
3504                                 if (can_change)
3505                                 {
3506                                         if (direction == 1)
3507                                         {
3508                                                 log(DEBUG,"umode %c being added",parameters[1][i]);
3509                                                 if ((!strchr(dmodes,parameters[1][i])) && (allowed_umode(parameters[1][i],user->modes,true)))
3510                                                 {
3511                                                         char umode = parameters[1][i];
3512                                                         log(DEBUG,"umode %c is an allowed umode",umode);
3513                                                         if ((process_module_umode(umode, NULL, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
3514                                                         {
3515                                                                 dmodes[strlen(dmodes)+1]='\0';
3516                                                                 dmodes[strlen(dmodes)] = parameters[1][i];
3517                                                                 outpars[strlen(outpars)+1]='\0';
3518                                                                 outpars[strlen(outpars)] = parameters[1][i];
3519                                                         }
3520                                                 }
3521                                         }
3522                                         else
3523                                         {
3524                                                 // can only remove a mode they already have
3525                                                 log(DEBUG,"umode %c being removed",parameters[1][i]);
3526                                                 if ((allowed_umode(parameters[1][i],user->modes,false)) && (strchr(dmodes,parameters[1][i])))
3527                                                 {
3528                                                         char umode = parameters[1][i];
3529                                                         log(DEBUG,"umode %c is an allowed umode",umode);
3530                                                         if ((process_module_umode(umode, NULL, dest, direction)) || (umode == 'i') || (umode == 's') || (umode == 'w') || (umode == 'o'))
3531                                                         {
3532                                                                 int q = 0;
3533                                                                 char temp[MAXBUF];
3534                                                                 char moo[MAXBUF];       
3535
3536                                                                 outpars[strlen(outpars)+1]='\0';
3537                                                                 outpars[strlen(outpars)] = parameters[1][i];
3538                                                         
3539                                                                 strcpy(temp,"");
3540                                                                 for (q = 0; q < strlen(dmodes); q++)
3541                                                                 {
3542                                                                         if (dmodes[q] != parameters[1][i])
3543                                                                         {
3544                                                                                 moo[0] = dmodes[q];
3545                                                                                 moo[1] = '\0';
3546                                                                                 strcat(temp,moo);
3547                                                                         }
3548                                                                 }
3549                                                                 strcpy(dmodes,temp);
3550                                                         }
3551                                                 }
3552                                         }
3553                                 }
3554                         }
3555                 }
3556                 if (strlen(outpars))
3557                 {
3558                         char b[MAXBUF];
3559                         strcpy(b,"");
3560                         int z = 0;
3561                         int i = 0;
3562                         while (i < strlen (outpars))
3563                         {
3564                                 b[z++] = outpars[i++];
3565                                 b[z] = '\0';
3566                                 if (i<strlen(outpars)-1)
3567                                 {
3568                                         if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
3569                                         {
3570                                                 // someones playing silly buggers and trying
3571                                                 // to put a +- or -+ into the line...
3572                                                 i++;
3573                                         }
3574                                 }
3575                                 if (i == strlen(outpars)-1)
3576                                 {
3577                                         if ((outpars[i] == '-') || (outpars[i] == '+'))
3578                                         {
3579                                                 i++;
3580                                         }
3581                                 }
3582                         }
3583
3584                         z = strlen(b)-1;
3585                         if ((b[z] == '-') || (b[z] == '+'))
3586                                 b[z] == '\0';
3587
3588                         if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
3589                                 return;
3590
3591                         WriteTo(user,dest,"MODE :%s",b);
3592
3593                         if (strlen(dmodes)>MAXMODES)
3594                         {
3595                                 dmodes[MAXMODES-1] = '\0';
3596                         }
3597                         log(DEBUG,"Stripped mode line");
3598                         log(DEBUG,"Line dest is now %s",dmodes);
3599                         strncpy(dest->modes,dmodes,MAXMODES);
3600
3601                 }
3602
3603                 return;
3604         }
3605         
3606         Ptr = FindChan(parameters[0]);
3607         if (Ptr)
3608         {
3609                 if ((cstatus(user,Ptr) < STATUS_HOP) && (Ptr))
3610                 {
3611                         return;
3612                 }
3613
3614                 process_modes(parameters,user,Ptr,cstatus(user,Ptr),pcnt,false,false,true);
3615         }
3616 }
3617
3618
3619
3620 /* This function pokes and hacks at a parameter list like the following:
3621  *
3622  * PART #winbot, #darkgalaxy :m00!
3623  *
3624  * to turn it into a series of individual calls like this:
3625  *
3626  * PART #winbot :m00!
3627  * PART #darkgalaxy :m00!
3628  *
3629  * The seperate calls are sent to a callback function provided by the caller
3630  * (the caller will usually call itself recursively). The callback function
3631  * must be a command handler. Calling this function on a line with no list causes
3632  * no action to be taken. You must provide a starting and ending parameter number
3633  * where the range of the list can be found, useful if you have a terminating
3634  * parameter as above which is actually not part of the list, or parameters
3635  * before the actual list as well. This code is used by many functions which
3636  * can function as "one to list" (see the RFC) */
3637
3638 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
3639 {
3640         char plist[MAXBUF];
3641         char *param;
3642         char *pars[32];
3643         char blog[32][MAXBUF];
3644         char blog2[32][MAXBUF];
3645         int i = 0, j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
3646         char keystr[MAXBUF];
3647         char moo[MAXBUF];
3648
3649         for (int i = 0; i <32; i++)
3650                 strcpy(blog[i],"");
3651
3652         for (int i = 0; i <32; i++)
3653                 strcpy(blog2[i],"");
3654
3655         strcpy(moo,"");
3656         for (int i = 0; i <10; i++)
3657         {
3658                 if (!parameters[i])
3659                 {
3660                         parameters[i] = moo;
3661                 }
3662         }
3663         if (joins)
3664         {
3665                 if (pcnt > 1) /* we have a key to copy */
3666                 {
3667                         strcpy(keystr,parameters[1]);
3668                 }
3669         }
3670
3671         if (!parameters[start])
3672         {
3673                 return 0;
3674         }
3675         if (!strchr(parameters[start],','))
3676         {
3677                 return 0;
3678         }
3679         strcpy(plist,"");
3680         for (int i = start; i <= end; i++)
3681         {
3682                 if (parameters[i])
3683                 {
3684                         strcat(plist,parameters[i]);
3685                 }
3686         }
3687         
3688         j = 0;
3689         param = plist;
3690
3691         t = strlen(plist);
3692         for (int i = 0; i < t; i++)
3693         {
3694                 if (plist[i] == ',')
3695                 {
3696                         plist[i] = '\0';
3697                         strcpy(blog[j++],param);
3698                         param = plist+i+1;
3699                         if (j>20)
3700                         {
3701                                 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
3702                                 return 1;
3703                         }
3704                 }
3705         }
3706         strcpy(blog[j++],param);
3707         total = j;
3708
3709         if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
3710         {
3711                 strcat(keystr,",");
3712         }
3713         
3714         if ((joins) && (keystr))
3715         {
3716                 if (strchr(keystr,','))
3717                 {
3718                         j = 0;
3719                         param = keystr;
3720                         t2 = strlen(keystr);
3721                         for (int i = 0; i < t2; i++)
3722                         {
3723                                 if (keystr[i] == ',')
3724                                 {
3725                                         keystr[i] = '\0';
3726                                         strcpy(blog2[j++],param);
3727                                         param = keystr+i+1;
3728                                 }
3729                         }
3730                         strcpy(blog2[j++],param);
3731                         total2 = j;
3732                 }
3733         }
3734
3735         for (j = 0; j < total; j++)
3736         {
3737                 if (blog[j])
3738                 {
3739                         pars[0] = blog[j];
3740                 }
3741                 for (q = end; q < pcnt-1; q++)
3742                 {
3743                         if (parameters[q+1])
3744                         {
3745                                 pars[q-end+1] = parameters[q+1];
3746                         }
3747                 }
3748                 if ((joins) && (parameters[1]))
3749                 {
3750                         if (pcnt > 1)
3751                         {
3752                                 pars[1] = blog2[j];
3753                         }
3754                         else
3755                         {
3756                                 pars[1] = NULL;
3757                         }
3758                 }
3759                 /* repeatedly call the function with the hacked parameter list */
3760                 if ((joins) && (pcnt > 1))
3761                 {
3762                         if (pars[1])
3763                         {
3764                                 // pars[1] already set up and containing key from blog2[j]
3765                                 fn(pars,2,u);
3766                         }
3767                         else
3768                         {
3769                                 pars[1] = parameters[1];
3770                                 fn(pars,2,u);
3771                         }
3772                 }
3773                 else
3774                 {
3775                         fn(pars,pcnt-(end-start),u);
3776                 }
3777         }
3778
3779         return 1;
3780 }
3781
3782
3783 void handle_join(char **parameters, int pcnt, userrec *user)
3784 {
3785         chanrec* Ptr;
3786         int i = 0;
3787         
3788         if (loop_call(handle_join,parameters,pcnt,user,0,0,1))
3789                 return;
3790         if (parameters[0][0] == '#')
3791         {
3792                 Ptr = add_channel(user,parameters[0],parameters[1],false);
3793         }
3794 }
3795
3796
3797 void handle_part(char **parameters, int pcnt, userrec *user)
3798 {
3799         chanrec* Ptr;
3800
3801         if (pcnt > 1)
3802         {
3803                 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-2,0))
3804                         return;
3805                 del_channel(user,parameters[0],parameters[1],false);
3806         }
3807         else
3808         {
3809                 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-1,0))
3810                         return;
3811                 del_channel(user,parameters[0],NULL,false);
3812         }
3813 }
3814
3815 void handle_kick(char **parameters, int pcnt, userrec *user)
3816 {
3817         chanrec* Ptr = FindChan(parameters[0]);
3818         userrec* u   = Find(parameters[1]);
3819
3820         if ((!u) || (!Ptr))
3821         {
3822                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3823                 return;
3824         }
3825         
3826         if (!has_channel(u,Ptr))
3827         {
3828                 WriteServ(user->fd,"442 %s %s :You're not on that channel!",user->nick, parameters[0]);
3829                 return;
3830         }
3831
3832         char reason[MAXBUF];
3833         
3834         if (pcnt > 2)
3835         {
3836                 strncpy(reason,parameters[2],MAXBUF);
3837                 if (strlen(reason)>MAXKICK)
3838                 {
3839                         reason[MAXKICK-1] = '\0';
3840                 }
3841
3842                 kick_channel(user,u,Ptr,reason);
3843         }
3844         else
3845         {
3846                 strcpy(reason,user->nick);
3847                 kick_channel(user,u,Ptr,reason);
3848         }
3849         
3850         // this must be propogated so that channel membership is kept in step network-wide
3851         
3852         char buffer[MAXBUF];
3853         snprintf(buffer,MAXBUF,"k %s %s %s :%s",user->nick,u->nick,Ptr->name,reason);
3854         NetSendToAll(buffer);
3855 }
3856
3857
3858 void handle_die(char **parameters, int pcnt, userrec *user)
3859 {
3860         log(DEBUG,"die: %s",user->nick);
3861         if (!strcmp(parameters[0],diepass))
3862         {
3863                 WriteOpers("*** DIE command from %s!%s@%s, terminating...",user->nick,user->ident,user->host);
3864                 sleep(DieDelay);
3865                 Exit(ERROR);
3866         }
3867         else
3868         {
3869                 WriteOpers("*** Failed DIE Command from %s!%s@%s.",user->nick,user->ident,user->host);
3870         }
3871 }
3872
3873 void handle_restart(char **parameters, int pcnt, userrec *user)
3874 {
3875         log(DEBUG,"restart: %s",user->nick);
3876         if (!strcmp(parameters[0],restartpass))
3877         {
3878                 WriteOpers("*** RESTART command from %s!%s@%s, Pretending to restart till this is finished :D",user->nick,user->ident,user->host);
3879                 sleep(DieDelay);
3880                 Exit(ERROR);
3881                 /* Will finish this later when i can be arsed :) */
3882         }
3883         else
3884         {
3885                 WriteOpers("*** Failed RESTART Command from %s!%s@%s.",user->nick,user->ident,user->host);
3886         }
3887 }
3888
3889
3890 void kill_link(userrec *user,const char* r)
3891 {
3892         user_hash::iterator iter = clientlist.find(user->nick);
3893         
3894         char reason[MAXBUF];
3895         
3896         strncpy(reason,r,MAXBUF);
3897
3898         if (strlen(reason)>MAXQUIT)
3899         {
3900                 reason[MAXQUIT-1] = '\0';
3901         }
3902
3903         log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
3904         Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
3905         log(DEBUG,"closing fd %d",user->fd);
3906
3907         /* bugfix, cant close() a nonblocking socket (sux!) */
3908         if (user->registered == 7) {
3909                 FOREACH_MOD OnUserQuit(user);
3910                 WriteCommonExcept(user,"QUIT :%s",reason);
3911
3912                 // Q token must go to ALL servers!!!
3913                 char buffer[MAXBUF];
3914                 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
3915                 NetSendToAll(buffer);
3916         }
3917
3918         /* push the socket on a stack of sockets due to be closed at the next opportunity
3919          * 'Client exited' is an exception to this as it means the client side has already
3920          * closed the socket, we don't need to do it.
3921          */
3922         fd_reap.push_back(user->fd);
3923         
3924         bool do_purge = false;
3925         
3926         if (user->registered == 7) {
3927                 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
3928                 AddWhoWas(user);
3929         }
3930
3931         if (iter != clientlist.end())
3932         {
3933                 log(DEBUG,"deleting user hash value %d",iter->second);
3934                 if ((iter->second) && (user->registered == 7)) {
3935                         delete iter->second;
3936                 }
3937                 clientlist.erase(iter);
3938         }
3939
3940         if (user->registered == 7) {
3941                 purge_empty_chans();
3942         }
3943 }
3944
3945
3946 void handle_kill(char **parameters, int pcnt, userrec *user)
3947 {
3948         userrec *u = Find(parameters[0]);
3949         char killreason[MAXBUF];
3950         
3951         log(DEBUG,"kill: %s %s",parameters[0],parameters[1]);
3952         if (u)
3953         {
3954                 if (strcmp(ServerName,u->server))
3955                 {
3956                         // remote kill
3957                         WriteOpers("*** Remote kill by %s: %s!%s@%s (%s)",user->nick,u->nick,u->ident,u->host,parameters[1]);
3958                         sprintf(killreason,"[%s] Killed (%s (%s))",ServerName,user->nick,parameters[1]);
3959                         WriteCommonExcept(u,"QUIT :%s",killreason);
3960                         // K token must go to ALL servers!!!
3961                         char buffer[MAXBUF];
3962                         snprintf(buffer,MAXBUF,"K %s %s :%s",user->nick,u->nick,killreason);
3963                         NetSendToAll(buffer);
3964                         
3965                         user_hash::iterator iter = clientlist.find(u->nick);
3966                         if (iter != clientlist.end())
3967                         {
3968                                 log(DEBUG,"deleting user hash value %d",iter->second);
3969                                 if ((iter->second) && (user->registered == 7)) {
3970                                         delete iter->second;
3971                                         }
3972                         clientlist.erase(iter);
3973                         }
3974                         purge_empty_chans();
3975                 }
3976                 else
3977                 {
3978                         // local kill
3979                         WriteTo(user, u, "KILL %s :%s!%s!%s (%s)", u->nick, ServerName,user->dhost,user->nick,parameters[1]);
3980                         WriteOpers("*** Local Kill by %s: %s!%s@%s (%s)",user->nick,u->nick,u->ident,u->host,parameters[1]);
3981                         sprintf(killreason,"Killed (%s (%s))",user->nick,parameters[1]);
3982                         kill_link(u,killreason);
3983                 }
3984         }
3985         else
3986         {
3987                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3988         }
3989 }
3990
3991 void handle_summon(char **parameters, int pcnt, userrec *user)
3992 {
3993         WriteServ(user->fd,"445 %s :SUMMON has been disabled (depreciated command)",user->nick);
3994 }
3995
3996 void handle_users(char **parameters, int pcnt, userrec *user)
3997 {
3998         WriteServ(user->fd,"445 %s :USERS has been disabled (depreciated command)",user->nick);
3999 }
4000
4001
4002 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
4003
4004 char* Passwd(userrec *user)
4005 {
4006         for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
4007         {
4008                 if (match(user->host,i->host) && (i->type == CC_ALLOW))
4009                 {
4010                         return i->pass;
4011                 }
4012         }
4013         return "";
4014 }
4015
4016 bool IsDenied(userrec *user)
4017 {
4018         for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
4019         {
4020                 if (match(user->host,i->host) && (i->type == CC_DENY))
4021                 {
4022                         return true;
4023                 }
4024         }
4025         return false;
4026 }
4027
4028
4029
4030 void handle_pass(char **parameters, int pcnt, userrec *user)
4031 {
4032         // Check to make sure they havnt registered -- Fix by FCS
4033         if (user->registered == 7)
4034         {
4035                 WriteServ(user->fd,"462 %s :You may not reregister",user->nick);
4036                 return;
4037         }
4038         if (!strcasecmp(parameters[0],Passwd(user)))
4039         {
4040                 user->haspassed = true;
4041         }
4042 }
4043
4044 void handle_invite(char **parameters, int pcnt, userrec *user)
4045 {
4046         userrec* u = Find(parameters[0]);
4047         chanrec* c = FindChan(parameters[1]);
4048
4049         if ((!c) || (!u))
4050         {
4051                 if (!c)
4052                 {
4053                         WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[1]);
4054                 }
4055                 else
4056                 {
4057                         if (c->inviteonly)
4058                         {
4059                                 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[0]);
4060                         }
4061                 }
4062
4063                 return;
4064         }
4065
4066         if (c->inviteonly)
4067         {
4068                 if (cstatus(user,c) < STATUS_HOP)
4069                 {
4070                         WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, c->name);
4071                         return;
4072                 }
4073         }
4074         if (has_channel(u,c))
4075         {
4076                 WriteServ(user->fd,"443 %s %s %s :Is already on channel %s",user->nick,u->nick,c->name,c->name);
4077                 return;
4078         }
4079         if (!has_channel(user,c))
4080         {
4081                 WriteServ(user->fd,"442 %s %s :You're not on that channel!",user->nick, c->name);
4082                 return;
4083         }
4084         u->InviteTo(c->name);
4085         WriteFrom(u->fd,user,"INVITE %s :%s",u->nick,c->name);
4086         WriteServ(user->fd,"341 %s %s %s",user->nick,u->nick,c->name);
4087         
4088         // i token must go to ALL servers!!!
4089         char buffer[MAXBUF];
4090         snprintf(buffer,MAXBUF,"i %s %s %s",u->nick,user->nick,c->name);
4091         NetSendToAll(buffer);
4092 }
4093
4094 void handle_topic(char **parameters, int pcnt, userrec *user)
4095 {
4096         chanrec* Ptr;
4097
4098         if (pcnt == 1)
4099         {
4100                 if (strlen(parameters[0]) <= CHANMAX)
4101                 {
4102                         Ptr = FindChan(parameters[0]);
4103                         if (Ptr)
4104                         {
4105                                 if (Ptr->topicset)
4106                                 {
4107                                         WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
4108                                         WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
4109                                 }
4110                                 else
4111                                 {
4112                                         WriteServ(user->fd,"331 %s %s :No topic is set.", user->nick, Ptr->name);
4113                                 }
4114                         }
4115                         else
4116                         {
4117                                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4118                         }
4119                 }
4120                 return;
4121         }
4122         else if (pcnt>1)
4123         {
4124                 if (strlen(parameters[0]) <= CHANMAX)
4125                 {
4126                         Ptr = FindChan(parameters[0]);
4127                         if (Ptr)
4128                         {
4129                                 if ((Ptr->topiclock) && (cstatus(user,Ptr)<STATUS_HOP))
4130                                 {
4131                                         WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel", user->nick, Ptr->name);
4132                                         return;
4133                                 }
4134                                 
4135                                 char topic[MAXBUF];
4136                                 strncpy(topic,parameters[1],MAXBUF);
4137                                 if (strlen(topic)>MAXTOPIC)
4138                                 {
4139                                         topic[MAXTOPIC-1] = '\0';
4140                                 }
4141                                         
4142                                 strcpy(Ptr->topic,topic);
4143                                 strcpy(Ptr->setby,user->nick);
4144                                 Ptr->topicset = time(NULL);
4145                                 WriteChannel(Ptr,user,"TOPIC %s :%s",Ptr->name, Ptr->topic);
4146
4147                                 // t token must go to ALL servers!!!
4148                                 char buffer[MAXBUF];
4149                                 snprintf(buffer,MAXBUF,"t %s %s :%s",user->nick,Ptr->name,topic);
4150                                 NetSendToAll(buffer);
4151                         }
4152                         else
4153                         {
4154                                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4155                         }
4156                 }
4157         }
4158 }
4159
4160 /* sends out an error notice to all connected clients (not to be used
4161  * lightly!) */
4162
4163 void send_error(char *s)
4164 {
4165         log(DEBUG,"send_error: %s",s);
4166         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4167         {
4168                 if (isnick(i->second->nick))
4169                 {
4170                         WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
4171                 }
4172                 else
4173                 {
4174                         // fix - unregistered connections receive ERROR, not NOTICE
4175                         Write(i->second->fd,"ERROR :%s",s);
4176                 }
4177         }
4178 }
4179
4180 void Error(int status)
4181 {
4182         signal (SIGALRM, SIG_IGN);
4183         signal (SIGPIPE, SIG_IGN);
4184         signal (SIGTERM, SIG_IGN);
4185         signal (SIGABRT, SIG_IGN);
4186         signal (SIGSEGV, SIG_IGN);
4187         signal (SIGURG, SIG_IGN);
4188         signal (SIGKILL, SIG_IGN);
4189         log(DEBUG,"*** fell down a pothole in the road to perfection ***");
4190         send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
4191         exit(status);
4192 }
4193
4194
4195 int main(int argc, char *argv[])
4196 {
4197         Start();
4198         srand(time(NULL));
4199         log(DEBUG,"*** InspIRCd starting up!");
4200         if (!FileExists(CONFIG_FILE))
4201         {
4202                 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
4203                 log(DEBUG,"main: no config");
4204                 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
4205                 Exit(ERROR);
4206         }
4207         if (argc > 1) {
4208                 if (!strcmp(argv[1],"-nofork")) {
4209                         nofork = true;
4210                 }
4211         }
4212         if (InspIRCd() == ERROR)
4213         {
4214                 log(DEBUG,"main: daemon function bailed");
4215                 printf("ERROR: could not initialise. Shutting down.\n");
4216                 Exit(ERROR);
4217         }
4218         Exit(TRUE);
4219         return 0;
4220 }
4221
4222 template<typename T> inline string ConvToStr(const T &in)
4223 {
4224         stringstream tmp;
4225         if (!(tmp << in)) return string();
4226         return tmp.str();
4227 }
4228
4229 /* re-allocates a nick in the user_hash after they change nicknames,
4230  * returns a pointer to the new user as it may have moved */
4231
4232 userrec* ReHashNick(char* Old, char* New)
4233 {
4234         user_hash::iterator newnick;
4235         user_hash::iterator oldnick = clientlist.find(Old);
4236
4237         log(DEBUG,"ReHashNick: %s %s",Old,New);
4238         
4239         if (!strcasecmp(Old,New))
4240         {
4241                 log(DEBUG,"old nick is new nick, skipping");
4242                 return oldnick->second;
4243         }
4244         
4245         if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
4246
4247         log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
4248
4249         clientlist[New] = new userrec();
4250         clientlist[New] = oldnick->second;
4251         /*delete oldnick->second; */
4252         clientlist.erase(oldnick);
4253
4254         log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
4255         
4256         return clientlist[New];
4257 }
4258
4259 /* adds or updates an entry in the whowas list */
4260 void AddWhoWas(userrec* u)
4261 {
4262         user_hash::iterator iter = whowas.find(u->nick);
4263         userrec *a = new userrec();
4264         strcpy(a->nick,u->nick);
4265         strcpy(a->ident,u->ident);
4266         strcpy(a->dhost,u->dhost);
4267         strcpy(a->host,u->host);
4268         strcpy(a->fullname,u->fullname);
4269         strcpy(a->server,u->server);
4270         a->signon = u->signon;
4271
4272         /* MAX_WHOWAS:   max number of /WHOWAS items
4273          * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
4274          *               can be replaced by a newer one
4275          */
4276         
4277         if (iter == whowas.end())
4278         {
4279                 if (whowas.size() == WHOWAS_MAX)
4280                 {
4281                         for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
4282                         {
4283                                 // 3600 seconds in an hour ;)
4284                                 if ((i->second->signon)<(time(NULL)-(WHOWAS_STALE*3600)))
4285                                 {
4286                                         delete i->second;
4287                                         i->second = a;
4288                                         log(DEBUG,"added WHOWAS entry, purged an old record");
4289                                         return;
4290                                 }
4291                         }
4292                 }
4293                 else
4294                 {
4295                         log(DEBUG,"added fresh WHOWAS entry");
4296                         whowas[a->nick] = a;
4297                 }
4298         }
4299         else
4300         {
4301                 log(DEBUG,"updated WHOWAS entry");
4302                 delete iter->second;
4303                 iter->second = a;
4304         }
4305 }
4306
4307
4308 /* add a client connection to the sockets list */
4309 void AddClient(int socket, char* host, int port, bool iscached)
4310 {
4311         int i;
4312         int blocking = 1;
4313         char resolved[MAXBUF];
4314         string tempnick;
4315         char tn2[MAXBUF];
4316         user_hash::iterator iter;
4317
4318         tempnick = ConvToStr(socket) + "-unknown";
4319         sprintf(tn2,"%d-unknown",socket);
4320
4321         iter = clientlist.find(tempnick);
4322
4323         if (iter != clientlist.end()) return;
4324
4325         /*
4326          * It is OK to access the value here this way since we know
4327          * it exists, we just created it above.
4328          *
4329          * At NO other time should you access a value in a map or a
4330          * hash_map this way.
4331          */
4332         clientlist[tempnick] = new userrec();
4333
4334         NonBlocking(socket);
4335         log(DEBUG,"AddClient: %d %s %d",socket,host,port);
4336
4337         clientlist[tempnick]->fd = socket;
4338         strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
4339         strncpy(clientlist[tempnick]->host, host,160);
4340         strncpy(clientlist[tempnick]->dhost, host,160);
4341         strncpy(clientlist[tempnick]->server, ServerName,256);
4342         strncpy(clientlist[tempnick]->ident, "unknown",9);
4343         clientlist[tempnick]->registered = 0;
4344         clientlist[tempnick]->signon = time(NULL);
4345         clientlist[tempnick]->nping = time(NULL)+240;
4346         clientlist[tempnick]->lastping = 1;
4347         clientlist[tempnick]->port = port;
4348
4349         if (iscached)
4350         {
4351                 WriteServ(socket,"NOTICE Auth :Found your hostname (cached)...");
4352         }
4353         else
4354         {
4355                 WriteServ(socket,"NOTICE Auth :Looking up your hostname...");
4356         }
4357
4358         // set the registration timeout for this user
4359         unsigned long class_regtimeout = 90;
4360         for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
4361         {
4362                 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
4363                 {
4364                         class_regtimeout = (unsigned long)i->registration_timeout;
4365                         break;
4366                 }
4367         }
4368
4369         int class_flood = 0;
4370         for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
4371         {
4372                 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
4373                 {
4374                         class_flood = i->flood;
4375                         break;
4376                 }
4377         }
4378
4379         clientlist[tempnick]->timeout = time(NULL)+class_regtimeout;
4380         clientlist[tempnick]->flood = class_flood;
4381
4382         for (int i = 0; i < MAXCHANS; i++)
4383         {
4384                 clientlist[tempnick]->chans[i].channel = NULL;
4385                 clientlist[tempnick]->chans[i].uc_modes = 0;
4386         }
4387
4388         if (clientlist.size() == MAXCLIENTS)
4389                 kill_link(clientlist[tempnick],"No more connections allowed in this class");
4390 }
4391
4392 void handle_names(char **parameters, int pcnt, userrec *user)
4393 {
4394         chanrec* c;
4395
4396         if (loop_call(handle_names,parameters,pcnt,user,0,pcnt-1,0))
4397                 return;
4398         c = FindChan(parameters[0]);
4399         if (c)
4400         {
4401                 /*WriteServ(user->fd,"353 %s = %s :%s", user->nick, c->name,*/
4402                 userlist(user,c);
4403                 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, c->name);
4404         }
4405         else
4406         {
4407                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4408         }
4409 }
4410
4411 void handle_privmsg(char **parameters, int pcnt, userrec *user)
4412 {
4413         userrec *dest;
4414         chanrec *chan;
4415
4416         user->idle_lastmsg = time(NULL);
4417         
4418         if (loop_call(handle_privmsg,parameters,pcnt,user,0,pcnt-2,0))
4419                 return;
4420         if (parameters[0][0] == '#')
4421         {
4422                 chan = FindChan(parameters[0]);
4423                 if (chan)
4424                 {
4425                         if ((chan->noexternal) && (!has_channel(user,chan)))
4426                         {
4427                                 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
4428                                 return;
4429                         }
4430                         if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
4431                         {
4432                                 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
4433                                 return;
4434                         }
4435                         
4436                         int MOD_RESULT = 0;
4437
4438                         FOREACH_RESULT(OnUserPreMessage(user,chan,TYPE_CHANNEL,std::string(parameters[1])));
4439                         if (MOD_RESULT) {
4440                                 return;
4441                         }
4442                         
4443                         ChanExceptSender(chan, user, "PRIVMSG %s :%s", chan->name, parameters[1]);
4444                         
4445                         // if any users of this channel are on remote servers, broadcast the packet
4446                         char buffer[MAXBUF];
4447                         snprintf(buffer,MAXBUF,"P %s %s :%s",user->nick,chan->name,parameters[1]);
4448                         NetSendToCommon(user,buffer);
4449                 }
4450                 else
4451                 {
4452                         /* no such nick/channel */
4453                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4454                 }
4455                 return;
4456         }
4457         
4458         dest = Find(parameters[0]);
4459         if (dest)
4460         {
4461                 if (strcmp(dest->awaymsg,""))
4462                 {
4463                         /* auto respond with aweh msg */
4464                         WriteServ(user->fd,"301 %s %s :%s",user->nick,dest->nick,dest->awaymsg);
4465                 }
4466
4467                 int MOD_RESULT = 0;
4468                 
4469                 FOREACH_RESULT(OnUserPreMessage(user,dest,TYPE_USER,std::string(parameters[1])));
4470                 if (MOD_RESULT) {
4471                         return;
4472                 }
4473
4474
4475
4476                 if (!strcmp(dest->server,user->server))
4477                 {
4478                         // direct write, same server
4479                         WriteTo(user, dest, "PRIVMSG %s :%s", dest->nick, parameters[1]);
4480                 }
4481                 else
4482                 {
4483                         char buffer[MAXBUF];
4484                         snprintf(buffer,MAXBUF,"P %s %s :%s",user->nick,dest->nick,parameters[1]);
4485                         NetSendToOne(dest->server,buffer);
4486                 }
4487         }
4488         else
4489         {
4490                 /* no such nick/channel */
4491                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4492         }
4493 }
4494
4495 void handle_notice(char **parameters, int pcnt, userrec *user)
4496 {
4497         userrec *dest;
4498         chanrec *chan;
4499
4500         user->idle_lastmsg = time(NULL);
4501         
4502         if (loop_call(handle_notice,parameters,pcnt,user,0,pcnt-2,0))
4503                 return;
4504         if (parameters[0][0] == '#')
4505         {
4506                 chan = FindChan(parameters[0]);
4507                 if (chan)
4508                 {
4509                         if ((chan->noexternal) && (!has_channel(user,chan)))
4510                         {
4511                                 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
4512                                 return;
4513                         }
4514                         if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
4515                         {
4516                                 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
4517                                 return;
4518                         }
4519
4520                         int MOD_RESULT = 0;
4521                 
4522                         FOREACH_RESULT(OnUserPreNotice(user,chan,TYPE_CHANNEL,std::string(parameters[1])));
4523                         if (MOD_RESULT) {
4524                                 return;
4525                         }
4526
4527                         ChanExceptSender(chan, user, "NOTICE %s :%s", chan->name, parameters[1]);
4528
4529                         // if any users of this channel are on remote servers, broadcast the packet
4530                         char buffer[MAXBUF];
4531                         snprintf(buffer,MAXBUF,"V %s %s :%s",user->nick,chan->name,parameters[1]);
4532                         NetSendToCommon(user,buffer);
4533                 }
4534                 else
4535                 {
4536                         /* no such nick/channel */
4537                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4538                 }
4539                 return;
4540         }
4541         
4542         dest = Find(parameters[0]);
4543         if (dest)
4544         {
4545                 int MOD_RESULT = 0;
4546                 
4547                 FOREACH_RESULT(OnUserPreNotice(user,dest,TYPE_USER,std::string(parameters[1])));
4548                 if (MOD_RESULT) {
4549                         return;
4550                 }
4551
4552                 if (!strcmp(dest->server,user->server))
4553                 {
4554                         // direct write, same server
4555                         WriteTo(user, dest, "NOTICE %s :%s", dest->nick, parameters[1]);
4556                 }
4557                 else
4558                 {
4559                         char buffer[MAXBUF];
4560                         snprintf(buffer,MAXBUF,"V %s %s :%s",user->nick,dest->nick,parameters[1]);
4561                         NetSendToOne(dest->server,buffer);
4562                 }
4563         }
4564         else
4565         {
4566                 /* no such nick/channel */
4567                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4568         }
4569 }
4570
4571 char lst[MAXBUF];
4572
4573 char* chlist(userrec *user)
4574 {
4575         int i = 0;
4576         char cmp[MAXBUF];
4577
4578         log(DEBUG,"chlist: %s",user->nick);
4579         strcpy(lst,"");
4580         if (!user)
4581         {
4582                 return lst;
4583         }
4584         for (int i = 0; i != MAXCHANS; i++)
4585         {
4586                 if (user->chans[i].channel != NULL)
4587                 {
4588                         if (user->chans[i].channel->name)
4589                         {
4590                                 strcpy(cmp,user->chans[i].channel->name);
4591                                 strcat(cmp," ");
4592                                 if (!strstr(lst,cmp))
4593                                 {
4594                                         if ((!user->chans[i].channel->c_private) && (!user->chans[i].channel->secret))
4595                                         {
4596                                                 strcat(lst,cmode(user,user->chans[i].channel));
4597                                                 strcat(lst,user->chans[i].channel->name);
4598                                                 strcat(lst," ");
4599                                         }
4600                                 }
4601                         }
4602                 }
4603         }
4604         if (strlen(lst))
4605         {
4606                 lst[strlen(lst)-1] = '\0'; // chop trailing space
4607         }
4608         return lst;
4609 }
4610
4611 void handle_info(char **parameters, int pcnt, userrec *user)
4612 {
4613         WriteServ(user->fd,"371 %s :The Inspire IRCd Project Has been brought to you by the following people..",user->nick);
4614         WriteServ(user->fd,"371 %s :Craig Edwards, Craig McLure, and Others..",user->nick);
4615         WriteServ(user->fd,"371 %s :Will finish this later when i can be arsed :p",user->nick);
4616         FOREACH_MOD OnInfo(user);
4617         WriteServ(user->fd,"374 %s :End of /INFO list",user->nick);
4618 }
4619
4620 void handle_time(char **parameters, int pcnt, userrec *user)
4621 {
4622         time_t rawtime;
4623         struct tm * timeinfo;
4624
4625         time ( &rawtime );
4626         timeinfo = localtime ( &rawtime );
4627         WriteServ(user->fd,"391 %s %s :%s",user->nick,ServerName, asctime (timeinfo) );
4628   
4629 }
4630
4631 void handle_whois(char **parameters, int pcnt, userrec *user)
4632 {
4633         userrec *dest;
4634         char *t;
4635
4636         if (loop_call(handle_whois,parameters,pcnt,user,0,pcnt-1,0))
4637                 return;
4638         dest = Find(parameters[0]);
4639         if (dest)
4640         {
4641                 // bug found by phidjit - were able to whois an incomplete connection if it had sent a NICK or USER
4642                 if (dest->registered == 7)
4643                 {
4644                         WriteServ(user->fd,"311 %s %s %s %s * :%s",user->nick, dest->nick, dest->ident, dest->dhost, dest->fullname);
4645                         if ((user == dest) || (strchr(user->modes,'o')))
4646                         {
4647                                 WriteServ(user->fd,"378 %s %s :is connecting from *@%s",user->nick, dest->nick, dest->host);
4648                         }
4649                         if (strcmp(chlist(dest),""))
4650                         {
4651                                 WriteServ(user->fd,"319 %s %s :%s",user->nick, dest->nick, chlist(dest));
4652                         }
4653                         WriteServ(user->fd,"312 %s %s %s :%s",user->nick, dest->nick, dest->server, ServerDesc);
4654                         if (strcmp(dest->awaymsg,""))
4655                         {
4656                                 WriteServ(user->fd,"301 %s %s :%s",user->nick, dest->nick, dest->awaymsg);
4657                         }
4658                         if (strchr(dest->modes,'o'))
4659                         {
4660                                 WriteServ(user->fd,"313 %s %s :is an IRC operator",user->nick, dest->nick);
4661                         }
4662                         FOREACH_MOD OnWhois(user,dest);
4663                         //WriteServ(user->fd,"310 %s %s :is available for help.",user->nick, dest->nick);
4664                         WriteServ(user->fd,"317 %s %s %d %d :seconds idle, signon time",user->nick, dest->nick, abs((dest->idle_lastmsg)-time(NULL)), dest->signon);
4665                         
4666                         WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, dest->nick);
4667                 }
4668                 else
4669                 {
4670                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4671                 }
4672         }
4673         else
4674         {
4675                 /* no such nick/channel */
4676                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4677         }
4678 }
4679
4680 void send_network_quit(const char* nick, const char* reason)
4681 {
4682         char buffer[MAXBUF];
4683         snprintf(buffer,MAXBUF,"Q %s :%s",nick,reason);
4684         NetSendToAll(buffer);
4685 }
4686
4687 void handle_quit(char **parameters, int pcnt, userrec *user)
4688 {
4689         user_hash::iterator iter = clientlist.find(user->nick);
4690         char* reason;
4691
4692         if (user->registered == 7)
4693         {
4694                 /* theres more to do here, but for now just close the socket */
4695                 if (pcnt == 1)
4696                 {
4697                         if (parameters[0][0] == ':')
4698                         {
4699                                 *parameters[0]++;
4700                         }
4701                         reason = parameters[0];
4702
4703                         if (strlen(reason)>MAXQUIT)
4704                         {
4705                                 reason[MAXQUIT-1] = '\0';
4706                         }
4707
4708                         Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,parameters[0]);
4709                         WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,parameters[0]);
4710                         WriteCommonExcept(user,"QUIT :%s%s",PrefixQuit,parameters[0]);
4711
4712                         char buffer[MAXBUF];
4713                         snprintf(buffer,MAXBUF,"Q %s :%s%s",user->nick,PrefixQuit,parameters[0]);
4714                         NetSendToAll(buffer);
4715                 }
4716                 else
4717                 {
4718                         Write(user->fd,"ERROR :Closing link (%s@%s) [QUIT]",user->ident,user->host);
4719                         WriteOpers("*** Client exiting: %s!%s@%s [Client exited]",user->nick,user->ident,user->host);
4720                         WriteCommonExcept(user,"QUIT :Client exited");
4721
4722                         char buffer[MAXBUF];
4723                         snprintf(buffer,MAXBUF,"Q %s :Client exited",user->nick);
4724                         NetSendToAll(buffer);
4725                 }
4726                 FOREACH_MOD OnUserQuit(user);
4727                 AddWhoWas(user);
4728         }
4729
4730         /* push the socket on a stack of sockets due to be closed at the next opportunity */
4731         fd_reap.push_back(user->fd);
4732         
4733         if (iter != clientlist.end())
4734         {
4735                 clientlist.erase(iter);
4736                 log(DEBUG,"deleting user hash value %d",iter->second);
4737                 //if ((user) && (user->registered == 7)) {
4738                         //delete user;
4739                 //}
4740         }
4741
4742         if (user->registered == 7) {
4743                 purge_empty_chans();
4744         }
4745 }
4746
4747 void handle_who(char **parameters, int pcnt, userrec *user)
4748 {
4749         chanrec* Ptr = NULL;
4750         
4751         /* theres more to do here, but for now just close the socket */
4752         if (pcnt == 1)
4753         {
4754                 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")))
4755                 {
4756                         if (user->chans[0].channel)
4757                         {
4758                                 Ptr = user->chans[0].channel;
4759                                 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4760                                 {
4761                                         if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
4762                                         {
4763                                                 WriteServ(user->fd,"352 %s %s %s %s %s %s Hr@ :0 %s",user->nick, Ptr->name, i->second->ident, i->second->dhost, i->second->server, i->second->nick, i->second->fullname);
4764                                         }
4765                                 }
4766                         }
4767                         if (Ptr)
4768                         {
4769                                 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
4770                         }
4771                         else
4772                         {
4773                                 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, user->nick);
4774                         }
4775                         return;
4776                 }
4777                 if (parameters[0][0] == '#')
4778                 {
4779                         Ptr = FindChan(parameters[0]);
4780                         if (Ptr)
4781                         {
4782                                 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4783                                 {
4784                                         if ((has_channel(i->second,Ptr)) && (isnick(i->second->nick)))
4785                                         {
4786                                                 WriteServ(user->fd,"352 %s %s %s %s %s %s Hr@ :0 %s",user->nick, Ptr->name, i->second->ident, i->second->dhost, i->second->server, i->second->nick, i->second->fullname);
4787                                         }
4788                                 }
4789                                 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
4790                         }
4791                         else
4792                         {
4793                                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
4794                         }
4795                 }
4796                 else
4797                 {
4798                         userrec* u = Find(parameters[0]);
4799                         WriteServ(user->fd,"352 %s %s %s %s %s %s Hr@ :0 %s",user->nick, u->nick, u->ident, u->dhost, u->server, u->nick, u->fullname);
4800                 }
4801         }
4802         if (pcnt == 2)
4803         {
4804                 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")) && (!strcmp(parameters[1],"o")))
4805                 {
4806                         Ptr = user->chans[0].channel;
4807                         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4808                         {
4809                                 if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
4810                                 {
4811                                         if (strchr(i->second->modes,'o'))
4812                                         {
4813                                                 WriteServ(user->fd,"352 %s %s %s %s %s %s Hr@ :0 %s",user->nick, Ptr->name, i->second->ident, i->second->dhost, i->second->server, i->second->nick, i->second->fullname);
4814                                         }
4815                                 }
4816                         }
4817                         WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
4818                         return;
4819                 }
4820         }
4821 }
4822
4823 void handle_wallops(char **parameters, int pcnt, userrec *user)
4824 {
4825         WriteWallOps(user,false,"%s",parameters[0]);
4826 }
4827
4828 void handle_list(char **parameters, int pcnt, userrec *user)
4829 {
4830         chanrec* Ptr;
4831         
4832         WriteServ(user->fd,"321 %s Channel :Users Name",user->nick);
4833         for (chan_hash::const_iterator i = chanlist.begin(); i != chanlist.end(); i++)
4834         {
4835                 if ((!i->second->c_private) && (!i->second->secret))
4836                 {
4837                         WriteServ(user->fd,"322 %s %s %d :[+%s] %s",user->nick,i->second->name,usercount_i(i->second),chanmodes(i->second),i->second->topic);
4838                 }
4839         }
4840         WriteServ(user->fd,"323 %s :End of channel list.",user->nick);
4841 }
4842
4843
4844 void handle_rehash(char **parameters, int pcnt, userrec *user)
4845 {
4846         WriteServ(user->fd,"382 %s %s :Rehashing",user->nick,CleanFilename(CONFIG_FILE));
4847         ReadConfig();
4848         FOREACH_MOD OnRehash();
4849         WriteOpers("%s is rehashing config file %s",user->nick,CleanFilename(CONFIG_FILE));
4850 }
4851
4852
4853 int usercnt(void)
4854 {
4855         return clientlist.size();
4856 }
4857
4858
4859 int usercount_invisible(void)
4860 {
4861         int c = 0;
4862
4863         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4864         {
4865                 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
4866         }
4867         return c;
4868 }
4869
4870 int usercount_opers(void)
4871 {
4872         int c = 0;
4873
4874         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4875         {
4876                 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
4877         }
4878         return c;
4879 }
4880
4881 int usercount_unknown(void)
4882 {
4883         int c = 0;
4884
4885         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4886         {
4887                 if ((i->second->fd) && (i->second->registered != 7))
4888                         c++;
4889         }
4890         return c;
4891 }
4892
4893 long chancount(void)
4894 {
4895         return chanlist.size();
4896 }
4897
4898 long count_servs(void)
4899 {
4900         int c = 0;
4901         //for (int j = 0; j < 255; j++)
4902         //{
4903         //      if (servers[j] != NULL)
4904         //              c++;
4905         //}
4906         return c;
4907 }
4908
4909 long servercount(void)
4910 {
4911         return count_servs()+1;
4912 }
4913
4914 long local_count()
4915 {
4916         int c = 0;
4917         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
4918         {
4919                 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,ServerName))) c++;
4920         }
4921         return c;
4922 }
4923
4924
4925 void handle_lusers(char **parameters, int pcnt, userrec *user)
4926 {
4927         WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),servercount());
4928         WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
4929         WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
4930         WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
4931         WriteServ(user->fd,"254 %s :I have %d clients and %d servers",user->nick,local_count(),count_servs());
4932 }
4933
4934 void handle_admin(char **parameters, int pcnt, userrec *user)
4935 {
4936         WriteServ(user->fd,"256 %s :Administrative info for %s",user->nick,ServerName);
4937         WriteServ(user->fd,"257 %s :Name     - %s",user->nick,AdminName);
4938         WriteServ(user->fd,"258 %s :Nickname - %s",user->nick,AdminNick);
4939         WriteServ(user->fd,"258 %s :E-Mail   - %s",user->nick,AdminEmail);
4940 }
4941
4942 void ShowMOTD(userrec *user)
4943 {
4944         if (!MOTD.size())
4945         {
4946                 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
4947                 return;
4948         }
4949         WriteServ(user->fd,"375 %s :- %s message of the day",user->nick,ServerName);
4950         for (int i = 0; i != MOTD.size(); i++)
4951         {
4952                                 WriteServ(user->fd,"372 %s :- %s",user->nick,MOTD[i].c_str());
4953         }
4954         WriteServ(user->fd,"376 %s :End of %s message of the day.",user->nick,ServerName);
4955 }
4956
4957 void ShowRULES(userrec *user)
4958 {
4959         if (!RULES.size())
4960         {
4961                 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
4962                 return;
4963         }
4964         WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
4965         for (int i = 0; i != RULES.size(); i++)
4966         {
4967                                 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
4968         }
4969         WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
4970 }
4971
4972 /* shows the message of the day, and any other on-logon stuff */
4973 void ConnectUser(userrec *user)
4974 {
4975         user->registered = 7;
4976         user->idle_lastmsg = time(NULL);
4977         log(DEBUG,"ConnectUser: %s",user->nick);
4978
4979         if (strcmp(Passwd(user),"") && (!user->haspassed))
4980         {
4981                 kill_link(user,"Invalid password");
4982                 return;
4983         }
4984         if (IsDenied(user))
4985         {
4986                 kill_link(user,"Unauthorised connection");
4987                 return;
4988         }
4989
4990         WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
4991         WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
4992         WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
4993         WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
4994         WriteServ(user->fd,"004 %s :%s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
4995         WriteServ(user->fd,"005 %s :MAP KNOCK SAFELIST HCN MAXCHANNELS=20 MAXBANS=60 NICKLEN=30 TOPICLEN=307 KICKLEN=307 MAXTARGETS=20 AWAYLEN=307 :are supported by this server",user->nick);
4996         WriteServ(user->fd,"005 %s :WALLCHOPS WATCH=128 SILENCE=5 MODES=13 CHANTYPES=# PREFIX=(ohv)@%c+ CHANMODES=ohvbeqa,kfL,l,psmntirRcOAQKVHGCuzN NETWORK=%s :are supported by this server",user->nick,'%',Network);
4997         ShowMOTD(user);
4998         FOREACH_MOD OnUserConnect(user);
4999         WriteOpers("*** Client connecting on port %d: %s!%s@%s",user->port,user->nick,user->ident,user->host);
5000         
5001         char buffer[MAXBUF];
5002         snprintf(buffer,MAXBUF,"N %d %s %s %s %s +%s %s :%s",user->age,user->nick,user->host,user->dhost,user->ident,user->modes,ServerName,user->fullname);
5003         NetSendToAll(buffer);
5004 }
5005
5006 void handle_version(char **parameters, int pcnt, userrec *user)
5007 {
5008         WriteServ(user->fd,"351 %s :%s %s %s :%s",user->nick,VERSION,"$Revision$ $Date$",ServerName,SYSTEM);
5009 }
5010
5011 void handle_ping(char **parameters, int pcnt, userrec *user)
5012 {
5013         WriteServ(user->fd,"PONG %s :%s",ServerName,parameters[0]);
5014 }
5015
5016 void handle_pong(char **parameters, int pcnt, userrec *user)
5017 {
5018         // set the user as alive so they survive to next ping
5019         user->lastping = 1;
5020 }
5021
5022 void handle_motd(char **parameters, int pcnt, userrec *user)
5023 {
5024         ShowMOTD(user);
5025 }
5026
5027 void handle_rules(char **parameters, int pcnt, userrec *user)
5028 {
5029         ShowRULES(user);
5030 }
5031
5032 void handle_user(char **parameters, int pcnt, userrec *user)
5033 {
5034         if (user->registered < 3)
5035         {
5036                 if (isident(parameters[0]) == 0) {
5037                         // This kinda Sucks, According to the RFC thou, its either this,
5038                         // or "You have already registered" :p -- Craig
5039                         WriteServ(user->fd,"461 %s USER :Not enough parameters",user->nick);
5040                 }
5041                 else {
5042                         WriteServ(user->fd,"NOTICE Auth :No ident response, ident prefixed with ~");
5043                         strcpy(user->ident,"~"); /* we arent checking ident... but these days why bother anyway? */
5044                         strncat(user->ident,parameters[0],IDENTMAX);
5045                         strncpy(user->fullname,parameters[3],128);
5046                         user->registered = (user->registered | 1);
5047                 }
5048         }
5049         else
5050         {
5051                 WriteServ(user->fd,"462 %s :You may not reregister",user->nick);
5052                 return;
5053         }
5054         /* parameters 2 and 3 are local and remote hosts, ignored when sent by client connection */
5055         if (user->registered == 3)
5056         {
5057                 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
5058                 ConnectUser(user);
5059         }
5060 }
5061
5062 void handle_userhost(char **parameters, int pcnt, userrec *user)
5063 {
5064         char Return[MAXBUF],junk[MAXBUF];
5065         sprintf(Return,"302 %s :",user->nick);
5066         for (int i = 0; i < pcnt; i++)
5067         {
5068                 userrec *u = Find(parameters[i]);
5069                 if (u)
5070                 {
5071                         if (strchr(u->modes,'o'))
5072                         {
5073                                 sprintf(junk,"%s*=+%s@%s ",u->nick,u->ident,u->host);
5074                                 strcat(Return,junk);
5075                         }
5076                         else
5077                         {
5078                                 sprintf(junk,"%s=+%s@%s ",u->nick,u->ident,u->host);
5079                                 strcat(Return,junk);
5080                         }
5081                 }
5082         }
5083         WriteServ(user->fd,Return);
5084 }
5085
5086
5087 void handle_ison(char **parameters, int pcnt, userrec *user)
5088 {
5089         char Return[MAXBUF];
5090         sprintf(Return,"303 %s :",user->nick);
5091         for (int i = 0; i < pcnt; i++)
5092         {
5093                 userrec *u = Find(parameters[i]);
5094                 if (u)
5095                 {
5096                         strcat(Return,u->nick);
5097                         strcat(Return," ");
5098                 }
5099         }
5100         WriteServ(user->fd,Return);
5101 }
5102
5103
5104 void handle_away(char **parameters, int pcnt, userrec *user)
5105 {
5106         if (pcnt)
5107         {
5108                 strcpy(user->awaymsg,parameters[0]);
5109                 WriteServ(user->fd,"306 %s :You have been marked as being away",user->nick);
5110         }
5111         else
5112         {
5113                 strcpy(user->awaymsg,"");
5114                 WriteServ(user->fd,"305 %s :You are no longer marked as being away",user->nick);
5115         }
5116 }
5117
5118 void handle_whowas(char **parameters, int pcnt, userrec* user)
5119 {
5120         user_hash::iterator i = whowas.find(parameters[0]);
5121
5122         if (i == whowas.end())
5123         {
5124                 WriteServ(user->fd,"406 %s %s :There was no such nickname",user->nick,parameters[0]);
5125                 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
5126         }
5127         else
5128         {
5129                 time_t rawtime = i->second->signon;
5130                 tm *timeinfo;
5131                 char b[MAXBUF];
5132                 
5133                 timeinfo = localtime(&rawtime);
5134                 strcpy(b,asctime(timeinfo));
5135                 b[strlen(b)-1] = '\0';
5136                 
5137                 WriteServ(user->fd,"314 %s %s %s %s * :%s",user->nick,i->second->nick,i->second->ident,i->second->dhost,i->second->fullname);
5138                 WriteServ(user->fd,"312 %s %s %s :%s",user->nick,i->second->nick,i->second->server,b);
5139                 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
5140         }
5141
5142 }
5143
5144 void handle_trace(char **parameters, int pcnt, userrec *user)
5145 {
5146         for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
5147         {
5148                 if (i->second)
5149                 {
5150                         if (isnick(i->second->nick))
5151                         {
5152                                 if (strchr(i->second->modes,'o'))
5153                                 {
5154                                         WriteServ(user->fd,"205 %s :Oper 0 %s",user->nick,i->second->nick);
5155                                 }
5156                                 else
5157                                 {
5158                                         WriteServ(user->fd,"204 %s :User 0 %s",user->nick,i->second->nick);
5159                                 }
5160                         }
5161                         else
5162                         {
5163                                 WriteServ(user->fd,"203 %s :???? 0 [%s]",user->nick,i->second->host);
5164                         }
5165                 }
5166         }
5167 }
5168
5169 void handle_modules(char **parameters, int pcnt, userrec *user)
5170 {
5171         for (int i = 0; i < module_names.size(); i++)
5172         {
5173                         Version V = modules[i]->GetVersion();
5174                         char modulename[MAXBUF];
5175                         strncpy(modulename,module_names[i].c_str(),256);
5176                         WriteServ(user->fd,"900 %s :0x%08lx %d.%d.%d.%d %s",user->nick,modules[i],V.Major,V.Minor,V.Revision,V.Build,CleanFilename(modulename));
5177         }
5178 }
5179
5180 // calls a handler function for a command
5181
5182 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
5183 {
5184                 for (int i = 0; i < cmdlist.size(); i++)
5185                 {
5186                         if (!strcasecmp(cmdlist[i].command,commandname))
5187                         {
5188                                 if (cmdlist[i].handler_function)
5189                                 {
5190                                         if (pcnt>=cmdlist[i].min_params)
5191                                         {
5192                                                 if (strchr(user->modes,cmdlist[i].flags_needed))
5193                                                 {
5194                                                         cmdlist[i].handler_function(parameters,pcnt,user);
5195                                                 }
5196                                         }
5197                                 }
5198                         }
5199                 }
5200 }
5201
5202 void handle_stats(char **parameters, int pcnt, userrec *user)
5203 {
5204         if (pcnt != 1)
5205         {
5206                 return;
5207         }
5208         if (strlen(parameters[0])>1)
5209         {
5210                 /* make the stats query 1 character long */
5211                 parameters[0][1] = '\0';
5212         }
5213
5214         /* stats m (list number of times each command has been used, plus bytecount) */
5215         if (!strcasecmp(parameters[0],"m"))
5216         {
5217                 for (int i = 0; i < cmdlist.size(); i++)
5218                 {
5219                         if (cmdlist[i].handler_function)
5220                         {
5221                                 if (cmdlist[i].use_count)
5222                                 {
5223                                         /* RPL_STATSCOMMANDS */
5224                                         WriteServ(user->fd,"212 %s %s %d %d",user->nick,cmdlist[i].command,cmdlist[i].use_count,cmdlist[i].total_bytes);
5225                                 }
5226                         }
5227                 }
5228                         
5229         }
5230
5231         /* stats z (debug and memory info) */
5232         if (!strcasecmp(parameters[0],"z"))
5233         {
5234                 WriteServ(user->fd,"249 %s :Users(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,clientlist.size(),clientlist.size()*sizeof(userrec),clientlist.bucket_count());
5235                 WriteServ(user->fd,"249 %s :Channels(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,chanlist.size(),chanlist.size()*sizeof(chanrec),chanlist.bucket_count());
5236                 WriteServ(user->fd,"249 %s :Commands(VECTOR) %d (%d bytes)",user->nick,cmdlist.size(),cmdlist.size()*sizeof(command_t));
5237                 WriteServ(user->fd,"249 %s :MOTD(VECTOR) %d, RULES(VECTOR) %d",user->nick,MOTD.size(),RULES.size());
5238                 WriteServ(user->fd,"249 %s :address_cache(HASH_MAP) %d (%d buckets)",user->nick,IP.size(),IP.bucket_count());
5239                 WriteServ(user->fd,"249 %s :Modules(VECTOR) %d (%d)",user->nick,modules.size(),modules.size()*sizeof(Module));
5240                 WriteServ(user->fd,"249 %s :ClassFactories(VECTOR) %d (%d)",user->nick,factory.size(),factory.size()*sizeof(ircd_module));
5241                 WriteServ(user->fd,"249 %s :Ports(STATIC_ARRAY) %d",user->nick,boundPortCount);
5242         }
5243         
5244         /* stats o */
5245         if (!strcasecmp(parameters[0],"o"))
5246         {
5247                 for (int i = 0; i < ConfValueEnum("oper",&config_f); i++)
5248                 {
5249                         char LoginName[MAXBUF];
5250                         char HostName[MAXBUF];
5251                         char OperType[MAXBUF];
5252                         ConfValue("oper","name",i,LoginName,&config_f);
5253                         ConfValue("oper","host",i,HostName,&config_f);
5254                         ConfValue("oper","type",i,OperType,&config_f);
5255                         WriteServ(user->fd,"243 %s O %s * %s %s 0",user->nick,HostName,LoginName,OperType);
5256                 }
5257         }
5258         
5259         /* stats l (show user I/O stats) */
5260         if (!strcasecmp(parameters[0],"l"))
5261         {
5262                 WriteServ(user->fd,"211 %s :server:port nick bytes_in cmds_in bytes_out cmds_out",user->nick);
5263                 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
5264                 {
5265                         if (isnick(i->second->nick))
5266                         {
5267                                 WriteServ(user->fd,"211 %s :%s:%d %s %d %d %d %d",user->nick,ServerName,i->second->port,i->second->nick,i->second->bytes_in,i->second->cmds_in,i->second->bytes_out,i->second->cmds_out);
5268                         }
5269                         else
5270                         {
5271                                 WriteServ(user->fd,"211 %s :%s:%d (unknown@%d) %d %d %d %d",user->nick,ServerName,i->second->port,i->second->fd,i->second->bytes_in,i->second->cmds_in,i->second->bytes_out,i->second->cmds_out);
5272                         }
5273                         
5274                 }
5275         }
5276         
5277         /* stats u (show server uptime) */
5278         if (!strcasecmp(parameters[0],"u"))
5279         {
5280                 time_t current_time = 0;
5281                 current_time = time(NULL);
5282                 time_t server_uptime = current_time - startup_time;
5283                 struct tm* stime;
5284                 stime = gmtime(&server_uptime);
5285                 /* i dont know who the hell would have an ircd running for over a year nonstop, but
5286                  * Craig suggested this, and it seemed a good idea so in it went */
5287                 if (stime->tm_year > 70)
5288                 {
5289                         WriteServ(user->fd,"242 %s :Server up %d years, %d days, %.2d:%.2d:%.2d",user->nick,(stime->tm_year-70),stime->tm_yday,stime->tm_hour,stime->tm_min,stime->tm_sec);
5290                 }
5291                 else
5292                 {
5293                         WriteServ(user->fd,"242 %s :Server up %d days, %.2d:%.2d:%.2d",user->nick,stime->tm_yday,stime->tm_hour,stime->tm_min,stime->tm_sec);
5294                 }
5295         }
5296
5297         WriteServ(user->fd,"219 %s %s :End of /STATS report",user->nick,parameters[0]);
5298         WriteOpers("*** Notice: Stats '%s' requested by %s (%s@%s)",parameters[0],user->nick,user->ident,user->host);
5299         
5300 }
5301
5302 void handle_connect(char **parameters, int pcnt, userrec *user)
5303 {
5304         char Link_ServerName[1024];
5305         char Link_IPAddr[1024];
5306         char Link_Port[1024];
5307         char Link_Pass[1024];
5308         int LinkPort;
5309         bool found = false;
5310         
5311         for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
5312         {
5313                 if (!found)
5314                 {
5315                         ConfValue("link","name",i,Link_ServerName,&config_f);
5316                         ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
5317                         ConfValue("link","port",i,Link_Port,&config_f);
5318                         ConfValue("link","sendpass",i,Link_Pass,&config_f);
5319                         log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
5320                         LinkPort = atoi(Link_Port);
5321                         if (match(Link_ServerName,parameters[0])) {
5322                                 found = true;
5323                                 break;
5324                         }
5325                 }
5326         }
5327         
5328         if (!found) {
5329                 WriteServ(user->fd,"NOTICE %s :*** Failed to connect to %s: No servers matching this pattern are configured for linking.",user->nick,parameters[0]);
5330                 return;
5331         }
5332         
5333         // TODO: Perform a check here to stop a server being linked twice!
5334
5335         WriteServ(user->fd,"NOTICE %s :*** Connecting to %s (%s) port %s...",user->nick,Link_ServerName,Link_IPAddr,Link_Port);
5336
5337         if (me[defaultRoute])
5338         {
5339                 me[defaultRoute]->BeginLink(Link_IPAddr,LinkPort,Link_Pass,Link_ServerName);
5340                 return;
5341         }
5342         else
5343         {
5344                 WriteServ(user->fd,"NOTICE %s :No default route is defined for server connections on this server. You must define a server connection to be default route so that sockets can be bound to it.",user->nick);
5345         }
5346 }
5347
5348 void handle_squit(char **parameters, int pcnt, userrec *user)
5349 {
5350         // send out an squit across the mesh and then clear the server list (for local squit)
5351 }
5352
5353 char islast(const char* s)
5354 {
5355         char c = '`';
5356         for (int j = 0; j < 32; j++)
5357         {
5358                 if (me[j] != NULL)
5359                 {
5360                         for (int k = 0; k < me[j]->connectors.size(); k++)
5361                         {
5362                                 if (strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
5363                                 {
5364                                         c = '|';
5365                                 }
5366                                 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),s))
5367                                 {
5368                                         c = '`';
5369                                 }
5370                         }
5371                 }
5372         }
5373         return c;
5374 }
5375
5376 long map_count(const char* s)
5377 {
5378         int c = 0;
5379         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
5380         {
5381                 if ((i->second->fd) && (isnick(i->second->nick)) && (!strcasecmp(i->second->server,s))) c++;
5382         }
5383         return c;
5384 }
5385
5386 void handle_links(char **parameters, int pcnt, userrec *user)
5387 {
5388         WriteServ(user->fd,"364 %s %s %s :0 %s",user->nick,ServerName,ServerName,ServerDesc);
5389         for (int j = 0; j < 32; j++)
5390         {
5391                 if (me[j] != NULL)
5392                 {
5393                         for (int k = 0; k < me[j]->connectors.size(); k++)
5394                         {
5395                                 WriteServ(user->fd,"364 %s %s %s :1 %s",user->nick,me[j]->connectors[k].GetServerName().c_str(),ServerName,me[j]->connectors[k].GetDescription().c_str());
5396                         }
5397                 }
5398         }
5399         WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
5400 }
5401
5402 void handle_map(char **parameters, int pcnt, userrec *user)
5403 {
5404         char line[MAXBUF];
5405         snprintf(line,MAXBUF,"006 %s :%s",user->nick,ServerName);
5406         while (strlen(line) < 50)
5407                 strcat(line," ");
5408         WriteServ(user->fd,"%s%d (%.2f%%)",line,local_count(),(float)(((float)local_count()/(float)usercnt())*100));
5409         for (int j = 0; j < 32; j++)
5410         {
5411                 if (me[j] != NULL)
5412                 {
5413                         for (int k = 0; k < me[j]->connectors.size(); k++)
5414                         {
5415                                 snprintf(line,MAXBUF,"006 %s :%c-%s",user->nick,islast(me[j]->connectors[k].GetServerName().c_str()),me[j]->connectors[k].GetServerName().c_str());
5416                                 while (strlen(line) < 50)
5417                                         strcat(line," ");
5418                                 WriteServ(user->fd,"%s%d (%.2f%%)",line,map_count(me[j]->connectors[k].GetServerName().c_str()),(float)(((float)map_count(me[j]->connectors[k].GetServerName().c_str())/(float)usercnt())*100));
5419                         }
5420                 }
5421         }
5422         WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
5423 }
5424
5425
5426 void handle_oper(char **parameters, int pcnt, userrec *user)
5427 {
5428         char LoginName[MAXBUF];
5429         char Password[MAXBUF];
5430         char OperType[MAXBUF];
5431         char TypeName[MAXBUF];
5432         char Hostname[MAXBUF];
5433         int i,j;
5434
5435         for (int i = 0; i < ConfValueEnum("oper",&config_f); i++)
5436         {
5437                 ConfValue("oper","name",i,LoginName,&config_f);
5438                 ConfValue("oper","password",i,Password,&config_f);
5439                 if ((!strcmp(LoginName,parameters[0])) && (!strcmp(Password,parameters[1])))
5440                 {
5441                         /* correct oper credentials */
5442                         ConfValue("oper","type",i,OperType,&config_f);
5443                         WriteOpers("*** %s (%s@%s) is now an IRC operator of type %s",user->nick,user->ident,user->host,OperType);
5444                         WriteServ(user->fd,"381 %s :You are now an IRC operator of type %s",user->nick,OperType);
5445                         WriteServ(user->fd,"MODE %s :+o",user->nick);
5446                         for (j =0; j < ConfValueEnum("type",&config_f); j++)
5447                         {
5448                                 ConfValue("type","name",j,TypeName,&config_f);
5449                                 if (!strcmp(TypeName,OperType))
5450                                 {
5451                                         /* found this oper's opertype */
5452                                         ConfValue("type","host",j,Hostname,&config_f);
5453                                         strncpy(user->dhost,Hostname,256);
5454                                 }
5455                         }
5456                         if (!strchr(user->modes,'o'))
5457                         {
5458                                 strcat(user->modes,"o");
5459                         }
5460                         FOREACH_MOD OnOper(user);
5461                         return;
5462                 }
5463         }
5464         /* no such oper */
5465         WriteServ(user->fd,"491 %s :Invalid oper credentials",user->nick);
5466         WriteOpers("*** WARNING! Failed oper attempt by %s!%s@%s!",user->nick,user->ident,user->host);
5467 }
5468
5469 void handle_nick(char **parameters, int pcnt, userrec *user)
5470 {
5471         if (pcnt < 1) 
5472         {
5473                 log(DEBUG,"not enough params for handle_nick");
5474                 return;
5475         }
5476         if (!parameters[0])
5477         {
5478                 log(DEBUG,"invalid parameter passed to handle_nick");
5479                 return;
5480         }
5481         if (!strlen(parameters[0]))
5482         {
5483                 log(DEBUG,"zero length new nick passed to handle_nick");
5484                 return;
5485         }
5486         if (!user)
5487         {
5488                 log(DEBUG,"invalid user passed to handle_nick");
5489                 return;
5490         }
5491         if (!user->nick)
5492         {
5493                 log(DEBUG,"invalid old nick passed to handle_nick");
5494                 return;
5495         }
5496         if (!strcasecmp(user->nick,parameters[0]))
5497         {
5498                 log(DEBUG,"old nick is new nick, skipping");
5499                 return;
5500         }
5501         else
5502         {
5503                 if (strlen(parameters[0]) > 1)
5504                 {
5505                         if (parameters[0][0] == ':')
5506                         {
5507                                 *parameters[0]++;
5508                         }
5509                 }
5510                 if ((Find(parameters[0])) && (Find(parameters[0]) != user))
5511                 {
5512                         WriteServ(user->fd,"433 %s %s :Nickname is already in use.",user->nick,parameters[0]);
5513                         return;
5514                 }
5515         }
5516         if (isnick(parameters[0]) == 0)
5517         {
5518                 WriteServ(user->fd,"432 %s %s :Erroneous Nickname",user->nick,parameters[0]);
5519                 return;
5520         }
5521
5522         if (user->registered == 7)
5523         {
5524                 WriteCommon(user,"NICK %s",parameters[0]);
5525                 
5526                 // Q token must go to ALL servers!!!
5527                 char buffer[MAXBUF];
5528                 snprintf(buffer,MAXBUF,"n %s %s",user->nick,parameters[0]);
5529                 NetSendToAll(buffer);
5530                 
5531         }
5532         
5533         /* change the nick of the user in the users_hash */
5534         user = ReHashNick(user->nick, parameters[0]);
5535         /* actually change the nick within the record */
5536         if (!user) return;
5537         if (!user->nick) return;
5538
5539         strncpy(user->nick, parameters[0],NICKMAX);
5540
5541         log(DEBUG,"new nick set: %s",user->nick);
5542         
5543         if (user->registered < 3)
5544                 user->registered = (user->registered | 2);
5545         if (user->registered == 3)
5546         {
5547                 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
5548                 ConnectUser(user);
5549         }
5550         log(DEBUG,"exit nickchange: %s",user->nick);
5551 }
5552
5553 void force_nickchange(userrec* user,const char* newnick)
5554 {
5555         char nick[MAXBUF];
5556         strcpy(nick,"");
5557         
5558         if (user)
5559         {
5560                 if (newnick)
5561                 {
5562                         strncpy(nick,newnick,MAXBUF);
5563                 }
5564                 if (user->registered == 7)
5565                 {
5566                         char* pars[1];
5567                         pars[0] = nick;
5568                         handle_nick(pars,1,user);
5569                 }
5570         }
5571 }
5572                                 
5573
5574 int process_parameters(char **command_p,char *parameters)
5575 {
5576         int i = 0;
5577         int j = 0;
5578         int q = 0;
5579         q = strlen(parameters);
5580         if (!q)
5581         {
5582                 /* no parameters, command_p invalid! */
5583                 return 0;
5584         }
5585         if (parameters[0] == ':')
5586         {
5587                 command_p[0] = parameters+1;
5588                 return 1;
5589         }
5590         if (q)
5591         {
5592                 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
5593                 {
5594                         /* only one parameter */
5595                         command_p[0] = parameters;
5596                         if (parameters[0] == ':')
5597                         {
5598                                 if (strchr(parameters,' ') != NULL)
5599                                 {
5600                                         command_p[0]++;
5601                                 }
5602                         }
5603                         return 1;
5604                 }
5605         }
5606         command_p[j++] = parameters;
5607         for (int i = 0; i <= q; i++)
5608         {
5609                 if (parameters[i] == ' ')
5610                 {
5611                         command_p[j++] = parameters+i+1;
5612                         parameters[i] = '\0';
5613                         if (command_p[j-1][0] == ':')
5614                         {
5615                                 *command_p[j-1]++; /* remove dodgy ":" */
5616                                 break;
5617                                 /* parameter like this marks end of the sequence */
5618                         }
5619                 }
5620         }
5621         return j; /* returns total number of items in the list */
5622 }
5623
5624 void process_command(userrec *user, char* cmd)
5625 {
5626         char *parameters;
5627         char *command;
5628         char *command_p[127];
5629         char p[MAXBUF], temp[MAXBUF];
5630         int i, j, items, cmd_found;
5631
5632         for (int i = 0; i < 127; i++)
5633                 command_p[i] = NULL;
5634
5635         if (!user)
5636         {
5637                 return;
5638         }
5639         if (!cmd)
5640         {
5641                 return;
5642         }
5643         if (!strcmp(cmd,""))
5644         {
5645                 return;
5646         }
5647         
5648         int total_params = 0;
5649         if (strlen(cmd)>2)
5650         {
5651                 for (int q = 0; q < strlen(cmd)-1; q++)
5652                 {
5653                         if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
5654                         {
5655                                 total_params++;
5656                                 // found a 'trailing', we dont count them after this.
5657                                 break;
5658                         }
5659                         if (cmd[q] == ' ')
5660                                 total_params++;
5661                 }
5662         }
5663         
5664         // another phidjit bug...
5665         if (total_params > 126)
5666         {
5667                 kill_link(user,"Protocol violation (1)");
5668                 return;
5669         }
5670         
5671         strcpy(temp,cmd);
5672
5673         std::string tmp = cmd;
5674         for (int i = 0; i <= MODCOUNT; i++)
5675         {
5676                 std::string oldtmp = tmp;
5677                 modules[i]->OnServerRaw(tmp,true);
5678                 if (oldtmp != tmp)
5679                 {
5680                         log(DEBUG,"A Module changed the input string!");
5681                         log(DEBUG,"New string: %s",tmp.c_str());
5682                         log(DEBUG,"Old string: %s",oldtmp.c_str());
5683                         break;
5684                 }
5685         }
5686         strncpy(cmd,tmp.c_str(),MAXBUF);
5687         strcpy(temp,cmd);
5688
5689         if (!strchr(cmd,' '))
5690         {
5691                 /* no parameters, lets skip the formalities and not chop up
5692                  * the string */
5693                 log(DEBUG,"About to preprocess command with no params");
5694                 items = 0;
5695                 command_p[0] = NULL;
5696                 parameters = NULL;
5697                 for (int i = 0; i <= strlen(cmd); i++)
5698                 {
5699                         cmd[i] = toupper(cmd[i]);
5700                 }
5701                 log(DEBUG,"Preprocess done length=%d",strlen(cmd));
5702                 command = cmd;
5703         }
5704         else
5705         {
5706                 strcpy(cmd,"");
5707                 j = 0;
5708                 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
5709                 for (int i = 0; i < strlen(temp); i++)
5710                 {
5711                         if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
5712                         {
5713                                 cmd[j++] = temp[i];
5714                                 cmd[j] = 0;
5715                         }
5716                 }
5717                 /* split the full string into a command plus parameters */
5718                 parameters = p;
5719                 strcpy(p," ");
5720                 command = cmd;
5721                 if (strchr(cmd,' '))
5722                 {
5723                         for (int i = 0; i <= strlen(cmd); i++)
5724                         {
5725                                 /* capitalise the command ONLY, leave params intact */
5726                                 cmd[i] = toupper(cmd[i]);
5727                                 /* are we nearly there yet?! :P */
5728                                 if (cmd[i] == ' ')
5729                                 {
5730                                         command = cmd;
5731                                         parameters = cmd+i+1;
5732                                         cmd[i] = '\0';
5733                                         break;
5734                                 }
5735                         }
5736                 }
5737                 else
5738                 {
5739                         for (int i = 0; i <= strlen(cmd); i++)
5740                         {
5741                                 cmd[i] = toupper(cmd[i]);
5742                         }
5743                 }
5744
5745         }
5746         cmd_found = 0;
5747         
5748         if (strlen(command)>MAXCOMMAND)
5749         {
5750                 kill_link(user,"Protocol violation (2)");
5751                 return;
5752         }
5753         
5754         for (int x = 0; x < strlen(command); x++)
5755         {
5756                 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
5757                 {
5758                         if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
5759                         {
5760                                 if (strchr("@!\"$%^&*(){}[]_-=+;:'#~,.<>/?\\|`",command[x]))
5761                                 {
5762                                         kill_link(user,"Protocol violation (3)");
5763                                         return;
5764                                 }
5765                         }
5766                 }
5767         }
5768
5769         for (int i = 0; i != cmdlist.size(); i++)
5770         {
5771                 if (strcmp(cmdlist[i].command,""))
5772                 {
5773                         if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
5774                         {
5775                                 log(DEBUG,"Found matching command");
5776
5777                                 if (parameters)
5778                                 {
5779                                         if (strcmp(parameters,""))
5780                                         {
5781                                                 items = process_parameters(command_p,parameters);
5782                                         }
5783                                         else
5784                                         {
5785                                                 items = 0;
5786                                                 command_p[0] = NULL;
5787                                         }
5788                                 }
5789                                 else
5790                                 {
5791                                         items = 0;
5792                                         command_p[0] = NULL;
5793                                 }
5794                                 
5795                                 if (user)
5796                                 {
5797                                         log(DEBUG,"Processing command");
5798                                         
5799                                         /* activity resets the ping pending timer */
5800                                         user->nping = time(NULL) + 120;
5801                                         if ((items) < cmdlist[i].min_params)
5802                                         {
5803                                                 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
5804                                                 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
5805                                                 return;
5806                                         }
5807                                         if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
5808                                         {
5809                                                 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
5810                                                 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
5811                                                 cmd_found = 1;
5812                                                 return;
5813                                         }
5814                                         /* if the command isnt USER, PASS, or NICK, and nick is empty,
5815                                          * deny command! */
5816                                         if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
5817                                         {
5818                                                 if ((!isnick(user->nick)) || (user->registered != 7))
5819                                                 {
5820                                                         log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
5821                                                         WriteServ(user->fd,"451 %s :You have not registered",command);
5822                                                         return;
5823                                                 }
5824                                         }
5825                                         if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
5826                                         {
5827                                                 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
5828                                                 if (cmdlist[i].handler_function)
5829                                                 {
5830                                                         /* ikky /stats counters */
5831                                                         if (temp)
5832                                                         {
5833                                                                 if (user)
5834                                                                 {
5835                                                                         user->bytes_in += strlen(temp);
5836                                                                         user->cmds_in++;
5837                                                                 }
5838                                                                 cmdlist[i].use_count++;
5839                                                                 cmdlist[i].total_bytes+=strlen(temp);
5840                                                         }
5841
5842                                                         /* WARNING: nothing may come after the
5843                                                          * command handler call, as the handler
5844                                                          * may free the user structure! */
5845
5846                                                         cmdlist[i].handler_function(command_p,items,user);
5847                                                 }
5848                                                 return;
5849                                         }
5850                                         else
5851                                         {
5852                                                 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
5853                                                 WriteServ(user->fd,"451 %s :You have not registered",command);
5854                                                 return;
5855                                         }
5856                                 }
5857                                 cmd_found = 1;
5858                         }
5859                 }
5860         }
5861         if ((!cmd_found) && (user))
5862         {
5863                 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
5864                 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
5865         }
5866 }
5867
5868
5869 void createcommand(char* cmd, handlerfunc f, char flags, int minparams)
5870 {
5871         command_t comm;
5872         /* create the command and push it onto the table */     
5873         strcpy(comm.command,cmd);
5874         comm.handler_function = f;
5875         comm.flags_needed = flags;
5876         comm.min_params = minparams;
5877         comm.use_count = 0;
5878         comm.total_bytes = 0;
5879         cmdlist.push_back(comm);
5880         log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
5881 }
5882
5883 void SetupCommandTable(void)
5884 {
5885         createcommand("USER",handle_user,0,4);
5886         createcommand("NICK",handle_nick,0,1);
5887         createcommand("QUIT",handle_quit,0,0);
5888         createcommand("VERSION",handle_version,0,0);
5889         createcommand("PING",handle_ping,0,1);
5890         createcommand("PONG",handle_pong,0,1);
5891         createcommand("ADMIN",handle_admin,0,0);
5892         createcommand("PRIVMSG",handle_privmsg,0,2);
5893         createcommand("INFO",handle_info,0,0);
5894         createcommand("TIME",handle_time,0,0);
5895         createcommand("WHOIS",handle_whois,0,1);
5896         createcommand("WALLOPS",handle_wallops,'o',1);
5897         createcommand("NOTICE",handle_notice,0,2);
5898         createcommand("JOIN",handle_join,0,1);
5899         createcommand("NAMES",handle_names,0,1);
5900         createcommand("PART",handle_part,0,1);
5901         createcommand("KICK",handle_kick,0,2);
5902         createcommand("MODE",handle_mode,0,1);
5903         createcommand("TOPIC",handle_topic,0,1);
5904         createcommand("WHO",handle_who,0,1);
5905         createcommand("MOTD",handle_motd,0,0);
5906         createcommand("RULES",handle_rules,0,0);
5907         createcommand("OPER",handle_oper,0,2);
5908         createcommand("LIST",handle_list,0,0);
5909         createcommand("DIE",handle_die,'o',1);
5910         createcommand("RESTART",handle_restart,'o',1);
5911         createcommand("KILL",handle_kill,'o',2);
5912         createcommand("REHASH",handle_rehash,'o',0);
5913         createcommand("LUSERS",handle_lusers,0,0);
5914         createcommand("STATS",handle_stats,0,1);
5915         createcommand("USERHOST",handle_userhost,0,1);
5916         createcommand("AWAY",handle_away,0,0);
5917         createcommand("ISON",handle_ison,0,0);
5918         createcommand("SUMMON",handle_summon,0,0);
5919         createcommand("USERS",handle_users,0,0);
5920         createcommand("INVITE",handle_invite,0,2);
5921         createcommand("PASS",handle_pass,0,1);
5922         createcommand("TRACE",handle_trace,'o',0);
5923         createcommand("WHOWAS",handle_whowas,0,1);
5924         createcommand("CONNECT",handle_connect,'o',1);
5925         createcommand("SQUIT",handle_squit,'o',1);
5926         createcommand("MODULES",handle_modules,'o',0);
5927         createcommand("LINKS",handle_links,0,0);
5928         createcommand("MAP",handle_map,0,0);
5929 }
5930
5931 void process_buffer(const char* cmdbuf,userrec *user)
5932 {
5933         if (!user)
5934         {
5935                 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
5936                 return;
5937         }
5938         char cmd[MAXBUF];
5939         int i;
5940         if (!cmdbuf)
5941         {
5942                 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
5943                 return;
5944         }
5945         if (!strcmp(cmdbuf,""))
5946         {
5947                 return;
5948         }
5949         strncpy(cmd,cmdbuf,MAXBUF);
5950         if (!strcmp(cmd,""))
5951         {
5952                 return;
5953         }
5954         if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
5955         {
5956                 cmd[strlen(cmd)-1] = '\0';
5957         }
5958         if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
5959         {
5960                 cmd[strlen(cmd)-1] = '\0';
5961         }
5962         if (!strcmp(cmd,""))
5963         {
5964                 return;
5965         }
5966         log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
5967         tidystring(cmd);
5968         if ((user) && (cmd))
5969         {
5970                 process_command(user,cmd);
5971         }
5972 }
5973
5974 void DoSync(serverrec* serv, char* udp_host)
5975 {
5976         char data[MAXBUF];
5977         // send start of sync marker: Y <timestamp>
5978         // at this point the ircd receiving it starts broadcasting this netburst to all ircds
5979         // except the ones its receiving it from.
5980         snprintf(data,MAXBUF,"Y %d",time(NULL));
5981         serv->SendPacket(data,udp_host);
5982         // send users and channels
5983         for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
5984         {
5985                 snprintf(data,MAXBUF,"N %d %s %s %s %s +%s %s :%s",u->second->age,u->second->nick,u->second->host,u->second->dhost,u->second->ident,u->second->modes,u->second->server,u->second->fullname);
5986                 serv->SendPacket(data,udp_host);
5987                 if (strcmp(chlist(u->second),""))
5988                 {
5989                         snprintf(data,MAXBUF,"J %s %s",u->second->nick,chlist(u->second));
5990                         serv->SendPacket(data,udp_host);
5991                 }
5992         }
5993         // send channel modes, topics etc...
5994         for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
5995         {
5996                 snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
5997                 serv->SendPacket(data,udp_host);
5998                 if (strcmp(c->second->topic,""))
5999                 {
6000                         snprintf(data,MAXBUF,"T %d %s %s :%s",c->second->topicset,c->second->setby,c->second->name,c->second->topic);
6001                         serv->SendPacket(data,udp_host);
6002                 }
6003                 // send current banlist
6004                 
6005                 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
6006                 {
6007                         snprintf(data,MAXBUF,"M %s +b %s",b->set_time,c->second->name,b->data);
6008                         serv->SendPacket(data,udp_host);
6009                 }
6010         }
6011         // send end of sync marker: E <timestamp>
6012         snprintf(data,MAXBUF,"F %d",time(NULL));
6013         serv->SendPacket(data,udp_host);
6014         // ircd sends its serverlist after the end of sync here
6015 }
6016
6017
6018 void handle_V(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6019 {
6020         char* src = strtok(params," ");
6021         char* dest = strtok(NULL," :");
6022         char* text = strtok(NULL,"\r\n");
6023         text++;
6024         
6025         userrec* user = Find(src);
6026         if (user)
6027         {
6028                 userrec* dst = Find(dest);
6029                 
6030                 if (dst)
6031                 {
6032                         WriteTo(user, dst, "NOTICE %s :%s", dst->nick, text);
6033                 }
6034                 else
6035                 {
6036                         chanrec* d = FindChan(dest);
6037                         if (d)
6038                         {
6039                                 ChanExceptSender(d, user, "NOTICE %s :%s", d->name, text);
6040                         }
6041                 }
6042         }
6043         
6044 }
6045
6046
6047 void handle_P(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6048 {
6049         char* src = strtok(params," ");
6050         char* dest = strtok(NULL," :");
6051         char* text = strtok(NULL,"\r\n");
6052         text++;
6053         
6054         userrec* user = Find(src);
6055         if (user)
6056         {
6057                 userrec* dst = Find(dest);
6058                 
6059                 if (dst)
6060                 {
6061                         WriteTo(user, dst, "PRIVMSG %s :%s", dst->nick, text);
6062                 }
6063                 else
6064                 {
6065                         chanrec* d = FindChan(dest);
6066                         if (d)
6067                         {
6068                                 ChanExceptSender(d, user, "PRIVMSG %s :%s", d->name, text);
6069                         }
6070                 }
6071         }
6072         
6073 }
6074
6075 void handle_i(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6076 {
6077         char* nick = strtok(params," ");
6078         char* from = strtok(NULL," ");
6079         char* channel = strtok(NULL," ");
6080         userrec* u = Find(nick);
6081         userrec* user = Find(from);
6082         chanrec* c = FindChan(channel);
6083         if ((c) && (u) && (user))
6084         {
6085                 u->InviteTo(c->name);
6086                 WriteFrom(u->fd,user,"INVITE %s :%s",u->nick,c->name);
6087         }
6088 }
6089
6090 void handle_t(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6091 {
6092         char* setby = strtok(params," ");
6093         char* channel = strtok(NULL," :");
6094         char* topic = strtok(NULL,"\r\n");
6095         topic++;
6096         userrec* u = Find(setby);
6097         chanrec* c = FindChan(channel);
6098         if ((c) && (u))
6099         {
6100                 WriteChannelLocal(c,u,"TOPIC %s :%s",c->name,topic);
6101                 strncpy(c->topic,topic,MAXTOPIC);
6102                 strncpy(c->setby,u->nick,NICKMAX);
6103         }       
6104 }
6105         
6106
6107 void handle_T(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6108 {
6109         char* tm = strtok(params," ");
6110         char* setby = strtok(NULL," ");
6111         char* channel = strtok(NULL," :");
6112         char* topic = strtok(NULL,"\r\n");
6113         topic++;
6114         time_t TS = atoi(tm);
6115         chanrec* c = FindChan(channel);
6116         if (c)
6117         {
6118                 // in the case of topics and TS, the *NEWER* 
6119                 if (TS <= c->topicset)
6120                 {
6121                         WriteChannelLocal(c,NULL,"TOPIC %s :%s",c->name,topic);
6122                         strncpy(c->topic,topic,MAXTOPIC);
6123                         strncpy(c->setby,setby,NICKMAX);
6124                 }
6125         }       
6126 }
6127         
6128 void handle_M(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6129 {
6130         char* pars[128];
6131         char original[MAXBUF],target[MAXBUF];
6132         strncpy(original,params,MAXBUF);
6133         int index = 0;
6134         char* parameter = strtok(params," ");
6135         strncpy(target,parameter,MAXBUF);
6136         while (parameter)
6137         {
6138                 pars[index++] = parameter;
6139                 parameter = strtok(NULL," ");
6140         }
6141         merge_mode(pars,index);
6142         if (FindChan(target))
6143         {
6144                 WriteChannelLocal(FindChan(target), NULL, "MODE %s",original);
6145         }
6146         if (Find(target))
6147         {
6148                 WriteTo(NULL,Find(target),"MODE %s",original);
6149         }
6150 }
6151
6152 // m is modes set by users only (not servers) valid targets are channels or users.
6153
6154 void handle_m(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6155 {
6156         // m blah #chatspike +b *!test@*4
6157         char* pars[128];
6158         char original[MAXBUF];
6159         strncpy(original,params,MAXBUF);
6160         
6161         if (!strchr(params,' '))
6162         {
6163                 WriteOpers("WARNING! 'm' token in data stream without any parameters! Something fishy is going on!");
6164                 return;
6165         }
6166         
6167         int index = 0;
6168         
6169         char* src = strtok(params," ");
6170         userrec* user = Find(src);
6171         
6172         if (user)
6173         {
6174                 log(DEBUG,"Found user: %s",user->nick);
6175                 char* parameter = strtok(NULL," ");
6176                 while (parameter)
6177                 {
6178                         pars[index++] = parameter;
6179                         parameter = strtok(NULL," ");
6180                 }
6181                 
6182                 log(DEBUG,"Calling merge_mode2");
6183                 merge_mode2(pars,index,user);
6184         }
6185 }
6186
6187
6188 void handle_L(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6189 {
6190         char* nick = strtok(params," ");
6191         char* channel = strtok(NULL," :");
6192         char* reason = strtok(NULL,"\r\n");
6193         userrec* user = Find(nick);
6194         reason++;
6195         if (user)
6196         {
6197                 if (strcmp(reason,""))
6198                 {
6199                         del_channel(user,channel,reason,true);
6200                 }
6201                 else
6202                 {
6203                         del_channel(user,channel,NULL,true);
6204                 }
6205         }
6206 }
6207
6208 void handle_K(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6209 {
6210         char* src = strtok(params," ");
6211         char* nick = strtok(NULL," :");
6212         char* reason = strtok(NULL,"\r\n");
6213         char kreason[MAXBUF];
6214         reason++;
6215
6216         userrec* u = Find(nick);
6217         userrec* user = Find(src);
6218         
6219         if ((user) && (u))
6220         {
6221                 WriteTo(user, u, "KILL %s :%s!%s!%s!%s (%s)", u->nick, source->name, ServerName, user->dhost,user->nick,reason);
6222                 WriteOpers("*** Remote kill from %s by %s: %s!%s@%s (%s)",source->name,user->nick,u->nick,u->ident,u->host,reason);
6223                 snprintf(kreason,MAXBUF,"[%s] Killed (%s (%s))",source->name,user->nick,reason);
6224                 kill_link(u,kreason);
6225         }
6226 }
6227
6228 void handle_Q(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6229 {
6230         char* nick = strtok(params," :");
6231         char* reason = strtok(NULL,"\r\n");
6232         reason++;
6233
6234         userrec* user = Find(nick);
6235         
6236         if (user)
6237         {
6238                 if (strlen(reason)>MAXQUIT)
6239                 {
6240                         reason[MAXQUIT-1] = '\0';
6241                 }
6242
6243
6244                 WriteCommonExcept(user,"QUIT :%s",reason);
6245
6246                 user_hash::iterator iter = clientlist.find(user->nick);
6247         
6248                 if (iter != clientlist.end())
6249                 {
6250                         log(DEBUG,"deleting user hash value %d",iter->second);
6251                         if ((iter->second) && (user->registered == 7)) {
6252                                 delete iter->second;
6253                         }
6254                         clientlist.erase(iter);
6255                 }
6256
6257                 purge_empty_chans();
6258         }
6259 }
6260
6261 void handle_n(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6262 {
6263         char* oldnick = strtok(params," ");
6264         char* newnick = strtok(NULL," ");
6265         
6266         userrec* user = Find(oldnick);
6267         
6268         if (user)
6269         {
6270                 WriteCommon(user,"NICK %s",newnick);
6271                 user = ReHashNick(user->nick, newnick);
6272                 if (!user) return;
6273                 if (!user->nick) return;
6274                 strncpy(user->nick, newnick,NICKMAX);
6275                 log(DEBUG,"new nick set: %s",user->nick);
6276         }
6277 }
6278
6279 // k <SOURCE> <DEST> <CHANNEL> :<REASON>
6280 void handle_k(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6281 {
6282         char* src = strtok(params," ");
6283         char* dest = strtok(NULL," ");
6284         char* channel = strtok(NULL," :");
6285         char* reason = strtok(NULL,"\r\n");
6286         reason++;
6287         userrec* s = Find(src);
6288         userrec* d = Find(dest);
6289         chanrec* c = FindChan(channel);
6290         if ((s) && (d) && (c))
6291         {
6292                 kick_channel(s,d,c,reason);
6293         }
6294 }
6295
6296 void handle_AT(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6297 {
6298         char* who = strtok(params," :");
6299         char* text = strtok(NULL,"\r\n");
6300         text++;
6301         userrec* s = Find(who);
6302         if (s)
6303         {
6304                 WriteWallOps(s,true,text);
6305         }
6306 }
6307
6308
6309 void handle_N(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6310 {
6311         char* tm = strtok(params," ");
6312         char* nick = strtok(NULL," ");
6313         char* host = strtok(NULL," ");
6314         char* dhost = strtok(NULL," ");
6315         char* ident = strtok(NULL," ");
6316         char* modes = strtok(NULL," ");
6317         char* server = strtok(NULL," :");
6318         char* gecos = strtok(NULL,"\r\n");
6319         gecos++;
6320         modes++;
6321         time_t TS = atoi(tm);
6322         user_hash::iterator iter = clientlist.find(nick);
6323         if (iter != clientlist.end())
6324         {
6325                 // nick collision
6326                 WriteOpers("Nickname collision: %s@%s != %s@%s",nick,server,iter->second->nick,iter->second->server);
6327                 if (TS >= iter->second->age)
6328                 {
6329                         char str[MAXBUF];
6330                         snprintf(str,MAXBUF,"Killed (Nick Collision (%s@%s < %s@%s))",nick,server,iter->second->nick,iter->second->server);
6331                         WriteServ(iter->second->fd, "KILL %s :%s",iter->second->nick,str);
6332                         // client on remote server is older than the local user, kill the local user
6333                         kill_link(iter->second,str);
6334                 }
6335         }
6336         clientlist[nick] = new userrec();
6337         // remote users have an fd of -1. This is so that our Write abstraction
6338         // routines know to route any messages to this record away to whatever server
6339         // theyre on.
6340         clientlist[nick]->fd = -1;
6341         strncpy(clientlist[nick]->nick, nick,NICKMAX);
6342         strncpy(clientlist[nick]->host, host,160);
6343         strncpy(clientlist[nick]->dhost, dhost,160);
6344         strncpy(clientlist[nick]->server, server,256);
6345         strncpy(clientlist[nick]->ident, ident,10); // +1 char to compensate for tilde
6346         strncpy(clientlist[nick]->fullname, gecos,128);
6347         clientlist[nick]->signon = TS;
6348         clientlist[nick]->nping = 0; // this is ignored for a remote user anyway.
6349         clientlist[nick]->lastping = 1;
6350         clientlist[nick]->port = 0; // so is this...
6351         clientlist[nick]->registered = 7; // this however we need to set for them to receive messages and appear online
6352         clientlist[nick]->idle_lastmsg = time(NULL); // this is unrealiable and wont actually be used locally
6353         for (int i = 0; i < MAXCHANS; i++)
6354         {
6355                 clientlist[nick]->chans[i].channel = NULL;
6356                 clientlist[nick]->chans[i].uc_modes = 0;
6357         }
6358 }
6359
6360 void handle_F(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6361 {
6362         long tdiff = time(NULL) - atoi(params);
6363         if (tdiff)
6364                 WriteOpers("TS split for %s -> %s: %d",source->name,reply->name,tdiff);
6365 }
6366
6367 void handle_a(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6368 {
6369         char* nick = strtok(params," :");
6370         char* gecos = strtok(NULL,"\r\n");
6371         
6372         userrec* user = Find(nick);
6373
6374         if (user)
6375                 strncpy(user->fullname,gecos,MAXBUF);
6376 }
6377
6378 void handle_b(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6379 {
6380         char* nick = strtok(params," :");
6381         char* host = strtok(NULL,"\r\n");
6382         
6383         userrec* user = Find(nick);
6384
6385         if (user)
6386                 strncpy(user->dhost,host,160);
6387 }
6388
6389 void handle_plus(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6390 {
6391         // %s %s %d %d
6392         // + test3.chatspike.net 7010 -2016508415
6393         char* servername = strtok(params," ");
6394         char* ipaddr = strtok(NULL," ");
6395         char* ipport = strtok(NULL," ");
6396         char* cookie = strtok(NULL," ");
6397         log(DEBUG," ");
6398         log(DEBUG," ");
6399         log(DEBUG,"*** Connecting back to %s:%d",ipaddr,atoi(ipport));
6400         me[defaultRoute]->MeshCookie(ipaddr,atoi(ipport),atoi(cookie),servername);
6401         log(DEBUG," ");
6402 }
6403
6404
6405 void handle_J(char token,char* params,serverrec* source,serverrec* reply, char* udp_host)
6406 {
6407         // IMPORTANT NOTE
6408         // The J token currently has no timestamp - this needs looking at
6409         // because it will allow splitriding.
6410         char* nick = strtok(params," ");
6411         char* channel = strtok(NULL," ");
6412         userrec* user = Find(nick);
6413         while (channel)
6414         {
6415                 if ((user != NULL) && (strcmp(channel,"")))
6416                 {
6417                         char privilage = '\0';
6418                         if (channel[0] != '#')
6419                         {
6420                                 privilage = channel[0];
6421                                 channel++;
6422                         }
6423                         add_channel(user,channel,"",true);
6424
6425                         // now work out the privilages they should have on each channel
6426                         // and send the appropriate servermodes.
6427                         for (int i = 0; i != MAXCHANS; i++)
6428                         {
6429                                 if (user->chans[i].channel)
6430                                 {
6431                                         if (!strcasecmp(user->chans[i].channel->name,channel))
6432                                         {
6433                                                 if (privilage == '@')
6434                                                 {
6435                                                         user->chans[i].uc_modes = user->chans[i].uc_modes | UCMODE_OP;
6436                                                         WriteChannelLocal(user->chans[i].channel, NULL, "MODE %s +o %s",channel,user->nick);
6437                                                 }
6438                                                 if (privilage == '%')
6439                                                 {
6440                                                         user->chans[i].uc_modes = user->chans[i].uc_modes | UCMODE_HOP;
6441                                                         WriteChannelLocal(user->chans[i].channel, NULL, "MODE %s +h %s",channel,user->nick);
6442                                                 }
6443                                                 if (privilage == '+')
6444                                                 {
6445                                                         user->chans[i].uc_modes = user->chans[i].uc_modes | UCMODE_VOICE;
6446                                                         WriteChannelLocal(user->chans[i].channel, NULL, "MODE %s +v %s",channel,user->nick);
6447                                                 }
6448                                         }
6449                                 }
6450                         }
6451
6452                 }
6453                 channel = strtok(NULL," ");
6454         }
6455 }
6456
6457
6458 void process_restricted_commands(char token,char* params,serverrec* source,serverrec* reply, char* udp_host,char* ipaddr,int port)
6459 {
6460         long authcookie = rand()*rand();
6461         char buffer[MAXBUF];
6462
6463         switch(token)
6464         {
6465                 // Y <TS>
6466                 // start netburst
6467                 case 'Y':
6468                         nb_start = time(NULL);
6469                         WriteOpers("Server %s is starting netburst.",udp_host);
6470                         // now broadcast this new servers address out to all servers that are linked to us,
6471                         // except the newcomer. They'll all attempt to connect back to it.
6472
6473                         // give the server its authcookie.
6474                         snprintf(buffer,MAXBUF,"~ %d",authcookie);
6475                         source->SendPacket(buffer,udp_host);
6476                         // tell all the other servers to use this authcookie to connect back again
6477                         // got '+ test3.chatspike.net 7010 -2016508415' from test.chatspike.net
6478                         snprintf(buffer,MAXBUF,"+ %s %s %d %d",udp_host,ipaddr,port,authcookie);
6479                         NetSendToAllExcept(udp_host,buffer);
6480                 break;
6481                 // ~
6482                 // Store authcookie
6483                 // once stored, this authcookie permits other servers to log in
6484                 // without user or password, using it.
6485                 case '~':
6486                         auth_cookies.push_back(atoi(params));
6487                         log(DEBUG,"*** Stored auth cookie, will permit servers with auth-cookie %d",atoi(params));
6488                 break;
6489                 // connect back to a server using an authcookie
6490                 case '+':
6491                         handle_plus(token,params,source,reply,udp_host);
6492                 break;
6493                 // ?
6494                 // ping
6495                 case '?':
6496                         reply->SendPacket("!",udp_host);
6497                 break;
6498                 // ?
6499                 // pong
6500                 case '!':
6501                 break;
6502                 // *
6503                 // no operation
6504                 case '*':
6505                 break;
6506                 // N <TS> <NICK> <HOST> <DHOST> <IDENT> <MODES> <SERVER> :<GECOS>
6507                 // introduce remote client
6508                 case 'N':
6509                         handle_N(token,params,source,reply,udp_host);
6510                 break;
6511                 // a <NICK> :<GECOS>
6512                 // change GECOS (SETNAME)
6513                 case 'a':
6514                         handle_a(token,params,source,reply,udp_host);
6515                 break;
6516                 // b <NICK> :<HOST>
6517                 // change displayed host (SETHOST)
6518                 case 'b':
6519                         handle_b(token,params,source,reply,udp_host);
6520                 break;
6521                 // t <NICK> <CHANNEL> :<TOPIC>
6522                 // change a channel topic
6523                 case 't':
6524                         handle_t(token,params,source,reply,udp_host);
6525                 break;
6526                 // i <NICK> <CHANNEL>
6527                 // invite a user to a channel
6528                 case 'i':
6529                         handle_i(token,params,source,reply,udp_host);
6530                 break;
6531                 // k <SOURCE> <DEST> <CHANNEL> :<REASON>
6532                 // kick a user from a channel
6533                 case 'k':
6534                         handle_k(token,params,source,reply,udp_host);
6535                 break;
6536                 // n <NICK> <NEWNICK>
6537                 // change nickname of client -- a server should only be able to
6538                 // change the nicknames of clients that reside on it unless
6539                 // they are ulined.
6540                 case 'n':
6541                         handle_n(token,params,source,reply,udp_host);
6542                 break;
6543                 // J <NICK> <CHANLIST>
6544                 // Join user to channel list, merge channel permissions
6545                 case 'J':
6546                         handle_J(token,params,source,reply,udp_host);
6547                 break;
6548                 // T <TS> <CHANNEL> <TOPICSETTER> :<TOPIC>
6549                 // change channel topic (netburst only)
6550                 case 'T':
6551                         handle_T(token,params,source,reply,udp_host);
6552                 break;
6553                 // M <TARGET> <MODES> [MODE-PARAMETERS]
6554                 // Server setting modes on an object
6555                 case 'M':
6556                         handle_M(token,params,source,reply,udp_host);
6557                 break;
6558                 // m <SOURCE> <TARGET> <MODES> [MODE-PARAMETERS]
6559                 // User setting modes on an object
6560                 case 'm':
6561                         handle_m(token,params,source,reply,udp_host);
6562                 break;
6563                 // P <SOURCE> <TARGET> :<TEXT>
6564                 // Send a private/channel message
6565                 case 'P':
6566                         handle_P(token,params,source,reply,udp_host);
6567                 break;
6568                 // V <SOURCE> <TARGET> :<TEXT>
6569                 // Send a private/channel notice
6570                 case 'V':
6571                         handle_V(token,params,source,reply,udp_host);
6572                 break;
6573                 // L <SOURCE> <CHANNEL> :<REASON>
6574                 // User parting a channel
6575                 case 'L':
6576                         handle_L(token,params,source,reply,udp_host);
6577                 break;
6578                 // Q <SOURCE> :<REASON>
6579                 // user quitting
6580                 case 'Q':
6581                         handle_Q(token,params,source,reply,udp_host);
6582                 break;
6583                 // K <SOURCE> <DEST> :<REASON>
6584                 // remote kill
6585                 case 'K':
6586                         handle_K(token,params,source,reply,udp_host);
6587                 break;
6588                 // @ <SOURCE> :<TEXT>
6589                 // wallops
6590                 case '@':
6591                         handle_AT(token,params,source,reply,udp_host);
6592                 break;
6593                 // F <TS>
6594                 // end netburst
6595                 case 'F':
6596                         WriteOpers("Server %s has completed netburst. (%d secs)",udp_host,time(NULL)-nb_start);
6597                         handle_F(token,params,source,reply,udp_host);
6598                         nb_start = 0;
6599                 break;
6600                 // X <reserved>
6601                 // Send netburst now
6602                 case 'X':
6603                         WriteOpers("Sending my netburst to %s",udp_host);
6604                         DoSync(source,udp_host);
6605                         WriteOpers("Send of netburst to %s completed",udp_host);
6606                 
6607                 break;
6608                 // anything else
6609                 default:
6610                         WriteOpers("WARNING! Unknown datagram type '%c'",token);
6611                 break;
6612         }
6613 }
6614
6615
6616 void handle_link_packet(char* udp_msg, char* udp_host, serverrec *serv)
6617 {
6618         char response[10240];
6619         char token = udp_msg[0];
6620         char* params = udp_msg + 2;
6621         char finalparam[1024];
6622         strcpy(finalparam," :xxxx");
6623         if (strstr(params," :")) {
6624                 strncpy(finalparam,strstr(params," :"),1024);
6625         }
6626         if (token == '-') {
6627                 char* cookie = strtok(params," ");
6628                 char* servername = strtok(NULL," ");
6629                 char* serverdesc = finalparam+2;
6630                 WriteOpers("AuthCookie CONNECT from %s (%s)",servername,udp_host);
6631                 for (int u = 0; u < auth_cookies.size(); u++)
6632                 {
6633                         if (auth_cookies[u] == atoi(cookie))
6634                         {
6635                                 WriteOpers("Allowed cookie from %s, is now part of the mesh",servername);
6636
6637
6638                                 for (int j = 0; j < 32; j++)
6639                                 {
6640                                         if (me[j] != NULL)
6641                                         {
6642                                                 for (int k = 0; k < me[j]->connectors.size(); k++)
6643                                                 {
6644                                                         if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),udp_host))
6645                                                         {
6646                                                                 me[j]->connectors[k].SetServerName(servername);
6647                                                                 return;
6648                                                         }
6649                                                 }
6650                                         }
6651                                         WriteOpers("\2WARNING!\2 %s sent us an authentication packet but we are not authenticating with this server right now! Possible intrusion attempt!",udp_host);
6652                                         return;
6653                                 }
6654
6655
6656                                 return;
6657                         }
6658                 }
6659                 WriteOpers("Bad cookie from %s!",servername);
6660                 return;
6661         }
6662         else
6663         if (token == 'S') {
6664                 // S test.chatspike.net password :ChatSpike InspIRCd test server
6665                 char* servername = strtok(params," ");
6666                 char* password = strtok(NULL," ");
6667                 char* serverdesc = finalparam+2;
6668                 WriteOpers("CONNECT from %s (%s)",servername,udp_host);
6669                 
6670                 for (int j = 0; j < serv->connectors.size(); j++)
6671                 {
6672                         if (!strcasecmp(serv->connectors[j].GetServerName().c_str(),udp_host))
6673                         {
6674                                 serv->connectors[j].SetServerName(servername);
6675                         }
6676                 }
6677                 
6678                 
6679                 char Link_ServerName[1024];
6680                 char Link_IPAddr[1024];
6681                 char Link_Port[1024];
6682                 char Link_Pass[1024];
6683                 char Link_SendPass[1024];
6684                 int LinkPort = 0;
6685                 
6686                 // search for a corresponding <link> block in the config files
6687                 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
6688                 {
6689                         ConfValue("link","name",i,Link_ServerName,&config_f);
6690                         ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
6691                         ConfValue("link","port",i,Link_Port,&config_f);
6692                         ConfValue("link","recvpass",i,Link_Pass,&config_f);
6693                         ConfValue("link","sendpass",i,Link_SendPass,&config_f);
6694                         log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
6695                         LinkPort = atoi(Link_Port);
6696                         if (!strcasecmp(Link_ServerName,servername))
6697                         {
6698                                 // we have a matching link line -
6699                                 // send a 'diminutive' server message back...
6700                                 snprintf(response,10240,"s %s %s :%s",ServerName,Link_SendPass,ServerDesc);
6701                                 serv->SendPacket(response,servername);
6702                                 return;
6703                         }
6704                 }
6705                 char buffer[MAXBUF];
6706                 sprintf(buffer,"E :Access is denied (no matching link block)");
6707                 serv->SendPacket(buffer,udp_host);
6708                 WriteOpers("CONNECT from %s denied, no matching link block",servername);
6709                 return;
6710         }
6711         else
6712         if (token == 's') {
6713                 // S test.chatspike.net password :ChatSpike InspIRCd test server
6714                 char* servername = strtok(params," ");
6715                 char* password = strtok(NULL," ");
6716                 char* serverdesc = finalparam+2;
6717                 
6718                 // TODO: we should do a check here to ensure that this server is one we recently initiated a
6719                 // link with, and didnt hear an 's' or 'E' back from yet (these are the only two valid responses
6720                 // to an 'S' command. If we didn't recently send an 'S' to this server, theyre trying to spoof
6721                 // a connect, so put out an oper alert!
6722                 
6723                 
6724                 
6725                 
6726                 // for now, just accept all, we'll fix that later.
6727                 WriteOpers("%s accepted our link credentials ",servername);
6728                 
6729                 char Link_ServerName[1024];
6730                 char Link_IPAddr[1024];
6731                 char Link_Port[1024];
6732                 char Link_Pass[1024];
6733                 char Link_SendPass[1024];
6734                 int LinkPort = 0;
6735                 
6736                 // search for a corresponding <link> block in the config files
6737                 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
6738                 {
6739                         ConfValue("link","name",i,Link_ServerName,&config_f);
6740                         ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
6741                         ConfValue("link","port",i,Link_Port,&config_f);
6742                         ConfValue("link","recvpass",i,Link_Pass,&config_f);
6743                         ConfValue("link","sendpass",i,Link_SendPass,&config_f);
6744                         log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
6745                         LinkPort = atoi(Link_Port);
6746                         if (!strcasecmp(Link_ServerName,servername))
6747                         {
6748                                 // matching link at this end too, we're all done!
6749                                 // at this point we must begin key exchange and insert this
6750                                 // server into our 'active' table.
6751                                 for (int j = 0; j < 32; j++)
6752                                 {
6753                                         if (me[j] != NULL)
6754                                         {
6755                                                 for (int k = 0; k < me[j]->connectors.size(); k++)
6756                                                 {
6757                                                         if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),udp_host))
6758                                                         {
6759                                                                 char buffer[MAXBUF];
6760                                                                 sprintf(buffer,"X 0");
6761                                                                 serv->SendPacket(buffer,udp_host);
6762                                                                 DoSync(me[j],udp_host);
6763                                                                 return;
6764                                                         }
6765                                                 }
6766                                         }
6767                                         WriteOpers("\2WARNING!\2 %s sent us an authentication packet but we are not authenticating with this server right noe! Possible intrusion attempt!",udp_host);
6768                                         return;
6769                                 }
6770                         }
6771                         else {
6772                                 log(DEBUG,"Server names '%s' and '%s' don't match",Link_ServerName,servername);
6773                         }
6774                 }
6775                 char buffer[MAXBUF];
6776                 sprintf(buffer,"E :Access is denied (no matching link block)");
6777                 serv->SendPacket(buffer,udp_host);
6778                 WriteOpers("CONNECT from %s denied, no matching link block",servername);
6779                 return;
6780         }
6781         else
6782         if (token == 'E') {
6783                 char* error_message = finalparam+2;
6784                 WriteOpers("ERROR from %s: %s",udp_host,error_message);
6785                 // remove this server from any lists
6786                 return;
6787         }
6788         else {
6789
6790                 serverrec* source_server = NULL;
6791
6792                 for (int j = 0; j < 32; j++)
6793                 {
6794                         if (me[j] != NULL)
6795                         {
6796                                 for (int x = 0; x < me[j]->connectors.size(); x++)
6797                                 {
6798                                         log(DEBUG,"Servers are: '%s' '%s'",udp_host,me[j]->connectors[x].GetServerName().c_str());
6799                                         if (!strcasecmp(me[j]->connectors[x].GetServerName().c_str(),udp_host))
6800                                         {
6801                                                 log(DEBUG,"match! process restricted stuff here");
6802                                                 // found a valid ircd_connector.
6803                                                 // TODO: Fix this so it only lets servers in that are in the 
6804                                                 // STATE_CONNECTED state!!!
6805                                                 process_restricted_commands(token,params,me[j],serv,udp_host,me[j]->connectors[x].GetServerIP(),me[j]->connectors[x].GetServerPort());
6806                                                 return;
6807                                         }
6808                                 }
6809                         }
6810                 }
6811
6812                 log(DEBUG,"Unrecognised token or unauthenticated host in datagram from %s: %c",udp_host,token);
6813         }
6814 }
6815
6816 int reap_counter = 0;
6817
6818 int InspIRCd(void)
6819 {
6820         struct sockaddr_in client, server;
6821         char addrs[MAXBUF][255];
6822         int openSockfd[MAXSOCKS], incomingSockfd, result = TRUE;
6823         socklen_t length;
6824         int count = 0, scanDetectTrigger = TRUE, showBanner = FALSE;
6825         int selectResult = 0, selectResult2 = 0;
6826         char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
6827         char resolvedHost[MAXBUF];
6828         fd_set selectFds;
6829         struct timeval tv;
6830
6831         log_file = fopen("ircd.log","a+");
6832         if (!log_file)
6833         {
6834                 printf("ERROR: Could not write to logfile ircd.log, bailing!\n\n");
6835                 Exit(ERROR);
6836         }
6837
6838         log(DEBUG,"InspIRCd: startup: begin");
6839         log(DEBUG,"$Id$");
6840         if (geteuid() == 0)
6841         {
6842                 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
6843                 Exit(ERROR);
6844                 log(DEBUG,"InspIRCd: startup: not starting with UID 0!");
6845         }
6846         SetupCommandTable();
6847         log(DEBUG,"InspIRCd: startup: default command table set up");
6848         
6849         ReadConfig();
6850         if (strcmp(DieValue,"")) 
6851         { 
6852                 printf("WARNING: %s\n\n",DieValue);
6853                 exit(0); 
6854         }  
6855         log(DEBUG,"InspIRCd: startup: read config");
6856           
6857         int count2 = 0, count3 = 0;
6858
6859         for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
6860         {
6861                 ConfValue("bind","port",count,configToken,&config_f);
6862                 ConfValue("bind","address",count,Addr,&config_f);
6863                 ConfValue("bind","type",count,Type,&config_f);
6864                 if (!strcmp(Type,"servers"))
6865                 {
6866                         char Default[MAXBUF];
6867                         strcpy(Default,"no");
6868                         ConfValue("bind","default",count,Default,&config_f);
6869                         if (strchr(Default,'y'))
6870                         {
6871                                 defaultRoute = count3;
6872                                 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
6873                         }
6874                         me[count3] = new serverrec(ServerName,100L,false);
6875                         me[count3]->CreateListener(Addr,atoi(configToken));
6876                         count3++;
6877                 }
6878                 else
6879                 {
6880                         ports[count2] = atoi(configToken);
6881                         strcpy(addrs[count2],Addr);
6882                         count2++;
6883                 }
6884                 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
6885         }
6886         portCount = count2;
6887         UDPportCount = count3;
6888           
6889         log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
6890         
6891         log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
6892         
6893         printf("\n");
6894         
6895         /* BugFix By Craig! :p */
6896         count = 0;
6897         for (count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
6898         {
6899                 char modfile[MAXBUF];
6900                 ConfValue("module","name",count2,configToken,&config_f);
6901                 sprintf(modfile,"%s/%s",MOD_PATH,configToken,&config_f);
6902                 printf("Loading module... \033[1;37m%s\033[0;37m\n",modfile);
6903                 log(DEBUG,"InspIRCd: startup: Loading module: %s",modfile);
6904                 /* If The File Doesnt exist, Trying to load it
6905                  * Will Segfault the IRCd.. So, check to see if
6906                  * it Exists, Before Proceeding. */
6907                 if (FileExists(modfile))
6908                 {
6909                         factory[count] = new ircd_module(modfile);
6910                         if (factory[count]->LastError())
6911                         {
6912                                 log(DEBUG,"Unable to load %s: %s",modfile,factory[count]->LastError());
6913                                 sprintf("Unable to load %s: %s\nExiting...\n",modfile,factory[count]->LastError());
6914                                 Exit(ERROR);
6915                         }
6916                         if (factory[count]->factory)
6917                         {
6918                                 modules[count] = factory[count]->factory->CreateModule();
6919                                 /* save the module and the module's classfactory, if
6920                                  * this isnt done, random crashes can occur :/ */
6921                                 module_names.push_back(modfile);        
6922                         }
6923                         else
6924                         {
6925                                 log(DEBUG,"Unable to load %s",modfile);
6926                                 sprintf("Unable to load %s\nExiting...\n",modfile);
6927                                 Exit(ERROR);
6928                         }
6929                         /* Increase the Count */
6930                         count++;
6931                 }
6932                 else
6933                 {
6934                         log(DEBUG,"InspIRCd: startup: Module Not Found %s",modfile);
6935                         printf("Module Not Found: \033[1;37m%s\033[0;37m, Skipping\n",modfile);
6936                 }
6937         }
6938         MODCOUNT = count - 1;
6939         log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
6940         
6941         printf("\nInspIRCd is now running!\n");
6942         
6943         startup_time = time(NULL);
6944           
6945         if (nofork)
6946         {
6947                 log(VERBOSE,"Not forking as -nofork was specified");
6948         }
6949         else
6950         {
6951                 if (DaemonSeed() == ERROR)
6952                 {
6953                         log(DEBUG,"InspIRCd: startup: can't daemonise");
6954                         printf("ERROR: could not go into daemon mode. Shutting down.\n");
6955                         Exit(ERROR);
6956                 }
6957         }
6958           
6959           
6960         /* setup select call */
6961         FD_ZERO(&selectFds);
6962         log(DEBUG,"InspIRCd: startup: zero selects");
6963         log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
6964         
6965         for (count = 0; count < portCount; count++)
6966         {
6967                 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
6968                 {
6969                         log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
6970                         return(ERROR);
6971                 }
6972                 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
6973                 {
6974                         log(DEBUG,"InspIRCd: startup: failed to bind port %d",ports[count]);
6975                 }
6976                 else    /* well we at least bound to one socket so we'll continue */
6977                 {
6978                         boundPortCount++;
6979                 }
6980         }
6981         
6982         log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
6983           
6984         /* if we didn't bind to anything then abort */
6985         if (boundPortCount == 0)
6986         {
6987                 log(DEBUG,"InspIRCd: startup: no ports bound, bailing!");
6988                 return (ERROR);
6989         }
6990         
6991
6992         length = sizeof (client);
6993         char udp_msg[MAXBUF], udp_host[MAXBUF];
6994           
6995         /* main loop, this never returns */
6996         for (;;)
6997         {
6998
6999                 fd_set sfd;
7000                 timeval tval;
7001                 FD_ZERO(&sfd);
7002
7003                 user_hash::iterator count2 = clientlist.begin();
7004
7005                 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
7006                 // them in a list, then reap the list every second or so.
7007                 if (reap_counter>5000)
7008                 {
7009                         if (fd_reap.size() > 0)
7010                         {
7011                                 for( int n = 0; n < fd_reap.size(); n++)
7012                                 {
7013                                         Blocking(fd_reap[n]);
7014                                         close(fd_reap[n]);
7015                                         NonBlocking(fd_reap[n]);
7016                                 }
7017                         }
7018                         fd_reap.clear();
7019                         reap_counter=0;
7020                 }
7021
7022                 fd_set serverfds;
7023                 FD_ZERO(&serverfds);
7024                 timeval tvs;
7025                 
7026                 for (int x = 0; x != UDPportCount; x++)
7027                 {
7028                         FD_SET(me[x]->fd, &serverfds);
7029                 }
7030                 
7031                 tvs.tv_usec = 0;                
7032                 tvs.tv_sec = 0;
7033                 
7034                 int servresult = select(32767, &serverfds, NULL, NULL, &tvs);
7035                 if (servresult > 0)
7036                 {
7037                         for (int x = 0; x != UDPportCount; x++)
7038                         {
7039                                 if (FD_ISSET (me[x]->fd, &serverfds))
7040                                 {
7041                                         char remotehost[MAXBUF],resolved[MAXBUF];
7042                                         length = sizeof (client);
7043                                         incomingSockfd = accept (me[x]->fd, (sockaddr *) &client, &length);
7044                                         strncpy(remotehost,(char *)inet_ntoa(client.sin_addr),MAXBUF);
7045                                         if(CleanAndResolve(resolved, remotehost) != TRUE)
7046                                         {
7047                                                 strncpy(resolved,remotehost,MAXBUF);
7048                                         }
7049                                         log(DEBUG," ");
7050                                         log(DEBUG," ");
7051                                         log(DEBUG,"Resolved: '%s'",resolved);
7052                                         log(DEBUG," ");
7053                                         // add to this connections ircd_connector vector
7054                                         me[x]->AddIncoming(incomingSockfd,resolved,ntohs(client.sin_port));
7055                                 }
7056                         }
7057                 }
7058      
7059                 for (int x = 0; x < UDPportCount; x++)
7060                 {
7061                         std::deque<std::string> msgs;
7062                         msgs.clear();
7063                         if (me[x]->RecvPacket(msgs, udp_host))
7064                         {
7065                                 for (int ctr = 0; ctr < msgs.size(); ctr++)
7066                                 {
7067                                         char udp_msg[MAXBUF];
7068                                         strncpy(udp_msg,msgs[ctr].c_str(),MAXBUF);
7069                                         if (strlen(udp_msg)<1)
7070                                         {
7071                                                 log(DEBUG,"Invalid string from %s [route%d]",udp_host,x);
7072                                                 break;
7073                                         }
7074                                         // during a netburst, send all data to all other linked servers
7075                                         if ((nb_start>0) && (udp_msg[0] != 'Y') && (udp_msg[0] != 'X') && (udp_msg[0] != 'F'))
7076                                         {
7077                                                 NetSendToAllExcept(udp_host,udp_msg);
7078                                         }
7079                                         FOREACH_MOD OnPacketReceive(udp_msg);
7080                                         handle_link_packet(udp_msg, udp_host, me[x]);
7081                                 }
7082                                 goto label;
7083                         }
7084                 }
7085         
7086
7087         while (count2 != clientlist.end())
7088         {
7089                 char data[10240];
7090                 tval.tv_usec = tval.tv_sec = 0;
7091                 FD_ZERO(&sfd);
7092                 int total_in_this_set = 0;
7093
7094                 user_hash::iterator xcount = count2;
7095                 user_hash::iterator endingiter = count2;
7096
7097                 if (!count2->second) break;
7098                 
7099                 if (count2->second)
7100                 if (count2->second->fd != 0)
7101                 {
7102                         // assemble up to 64 sockets into an fd_set
7103                         // to implement a pooling mechanism.
7104                         //
7105                         // This should be up to 64x faster than the
7106                         // old implementation.
7107                         while (total_in_this_set < 64)
7108                         {
7109                                 if (count2 != clientlist.end())
7110                                 {
7111                                         // we don't check the state of remote users.
7112                                         if (count2->second->fd > 0)
7113                                         {
7114                                                 FD_SET (count2->second->fd, &sfd);
7115
7116                                                 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
7117                                                 // their connection class.
7118                                                 if ((time(NULL) > count2->second->timeout) && (count2->second->registered != 7)) 
7119                                                 {
7120                                                         log(DEBUG,"InspIRCd: registration timeout: %s",count2->second->nick);
7121                                                         kill_link(count2->second,"Registration timeout");
7122                                                         goto label;
7123                                                 }
7124                                                 if (((time(NULL)) > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
7125                                                 {
7126                                                         if ((!count2->second->lastping) && (count2->second->registered == 7))
7127                                                         {
7128                                                                 log(DEBUG,"InspIRCd: ping timeout: %s",count2->second->nick);
7129                                                                 kill_link(count2->second,"Ping timeout");
7130                                                                 goto label;
7131                                                         }
7132                                                         Write(count2->second->fd,"PING :%s",ServerName);
7133                                                         log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
7134                                                         count2->second->lastping = 0;
7135                                                         count2->second->nping = time(NULL)+120;
7136                                                 }
7137                                         }
7138                                         count2++;
7139                                         total_in_this_set++;
7140                                 }
7141                                 else break;
7142                         }
7143    
7144                         endingiter = count2;
7145                         count2 = xcount; // roll back to where we were
7146         
7147                         int v = 0;
7148
7149                         tval.tv_usec = 0;
7150                         tval.tv_sec = 0;
7151                         selectResult2 = select(65535, &sfd, NULL, NULL, &tval);
7152                         
7153                         // now loop through all of the items in this pool if any are waiting
7154                         //if (selectResult2 > 0)
7155                         for (user_hash::iterator count2a = xcount; count2a != endingiter; count2a++)
7156                         {
7157                                 result = EAGAIN;
7158                                 if ((count2a->second->fd != -1) && (FD_ISSET (count2a->second->fd, &sfd)))
7159                                 {
7160                                         log(DEBUG,"Reading fd %d",count2a->second->fd);
7161                                         memset(data, 0, 10240);
7162                                         result = read(count2a->second->fd, data, 10240);
7163                                         
7164                                         if (result)
7165                                         {
7166                                                 log(DEBUG,"Read %d characters from socket",result);
7167                                                 userrec* current = count2a->second;
7168                                                 int currfd = current->fd;
7169                                                 char* l = strtok(data,"\n");
7170                                                 int floodlines = 0;
7171                                                 while (l)
7172                                                 {
7173                                                         floodlines++;
7174                                                         if ((floodlines > current->flood) && (current->flood != 0))
7175                                                         {
7176                                                                 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
7177                                                                 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
7178                                                                 kill_link(current,"Excess flood");
7179                                                                 goto label;
7180                                                         }
7181                                                         char sanitized[NetBufferSize];
7182                                                         memset(sanitized, 0, NetBufferSize);
7183                                                         int ptt = 0;
7184                                                         for (int pt = 0; pt < strlen(l); pt++)
7185                                                         {
7186                                                                 if (l[pt] != '\r')
7187                                                                 {
7188                                                                         sanitized[ptt++] = l[pt];
7189                                                                 }
7190                                                         }
7191                                                         sanitized[ptt] = '\0';
7192                                                         if (strlen(sanitized))
7193                                                         {
7194
7195
7196                                                                 // we're gonna re-scan to check if the nick is gone, after every
7197                                                                 // command - if it has, we're gonna bail
7198                                                                 bool find_again = false;
7199                                                                 process_buffer(sanitized,current);
7200         
7201                                                                 // look for the user's record in case it's changed
7202                                                                 for (user_hash::iterator c2 = clientlist.begin(); c2 != clientlist.end(); c2++)
7203                                                                 {
7204                                                                         if (c2->second->fd == currfd)
7205                                                                         {
7206                                                                                 // found again, update pointer
7207                                                                                 current == c2->second;
7208                                                                                 find_again = true;
7209                                                                                 break;
7210                                                                         }
7211                                                                 }
7212                                                                 if (!find_again)
7213                                                                         goto label;
7214
7215                                                         }
7216                                                         l = strtok(NULL,"\n");
7217                                                 }
7218                                                 goto label;
7219                                         }
7220
7221                                         if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
7222                                         {
7223                                                 log(DEBUG,"killing: %s",count2a->second->nick);
7224                                                 kill_link(count2a->second,strerror(errno));
7225                                                 goto label;
7226                                         }
7227                                 }
7228                                 // result EAGAIN means nothing read
7229                                 if (result == EAGAIN)
7230                                 {
7231                                 }
7232                                 else
7233                                 if (result == 0)
7234                                 {
7235                                         if (count2->second)
7236                                         {
7237                                                 log(DEBUG,"InspIRCd: Exited: %s",count2a->second->nick);
7238                                                 kill_link(count2a->second,"Client exited");
7239                                                 // must bail here? kill_link removes the hash, corrupting the iterator
7240                                                 log(DEBUG,"Bailing from client exit");
7241                                                 goto label;
7242                                         }
7243                                 }
7244                                 else if (result > 0)
7245                                 {
7246                                 }
7247                         }
7248                 }
7249                 for (int q = 0; q < total_in_this_set; q++)
7250                 {
7251                         // there is no iterator += operator :(
7252                         //if (count2 != clientlist.end())
7253                         //{
7254                                 count2++;
7255                         //}
7256                 }
7257         }
7258         
7259         // set up select call
7260         for (count = 0; count < boundPortCount; count++)
7261         {
7262                 FD_SET (openSockfd[count], &selectFds);
7263         }
7264
7265         reap_counter++;
7266         tv.tv_usec = 1;
7267         selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
7268
7269         /* select is reporting a waiting socket. Poll them all to find out which */
7270         if (selectResult > 0)
7271         {
7272                 char target[MAXBUF], resolved[MAXBUF];
7273                 for (count = 0; count < boundPortCount; count++)                
7274                 {
7275                         if (FD_ISSET (openSockfd[count], &selectFds))
7276                         {
7277                                 length = sizeof (client);
7278                                 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
7279                               
7280                                 address_cache::iterator iter = IP.find(client.sin_addr);
7281                                 bool iscached = false;
7282                                 if (iter == IP.end())
7283                                 {
7284                                         /* ip isn't in cache, add it */
7285                                         strncpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
7286                                         if(CleanAndResolve(resolved, target) != TRUE)
7287                                         {
7288                                                 strncpy(resolved,target,MAXBUF);
7289                                         }
7290                                         /* hostname now in 'target' */
7291                                         IP[client.sin_addr] = new string(resolved);
7292                                         /* hostname in cache */
7293                                 }
7294                                 else
7295                                 {
7296                                         /* found ip (cached) */
7297                                         strncpy(resolved, iter->second->c_str(), MAXBUF);
7298                                         iscached = true;
7299                                 }
7300                         
7301                                 if (incomingSockfd < 0)
7302                                 {
7303                                         WriteOpers("*** WARNING: Accept failed on port %d (%s)", ports[count],target);
7304                                         log(DEBUG,"InspIRCd: accept failed: %d",ports[count]);
7305                                 }
7306                                 else
7307                                 {
7308                                         AddClient(incomingSockfd, resolved, ports[count], iscached);
7309                                         log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
7310                                 }
7311                                 goto label;
7312                         }
7313                 }
7314         }
7315         label:
7316         if(0) {}; // "Label must be followed by a statement"... so i gave it one.
7317 }
7318 /* not reached */
7319 close (incomingSockfd);
7320 }
7321