]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
Added support for module-based chanmodes with parameters and the ability to query...
[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 #include "inspircd.h"
20 #include "inspircd_io.h"
21 #include "inspircd_util.h"
22 #include "inspircd_config.h"
23 #include <unistd.h>
24 #include <fcntl.h>
25 #include <sys/errno.h>
26 #include <sys/ioctl.h>
27 #include <sys/utsname.h>
28 #include <cstdio>
29 #include <time.h>
30 #include <string>
31 #ifdef GCC3
32 #include <ext/hash_map>
33 #else
34 #include <hash_map>
35 #endif
36 #include <map>
37 #include <sstream>
38 #include <vector>
39 #include <errno.h>
40 #include <deque>
41 #include "connection.h"
42 #include "users.h"
43 #include "servers.h"
44 #include "ctables.h"
45 #include "globals.h"
46 #include "modules.h"
47 #include "dynamic.h"
48 #include "wildcard.h"
49
50 using namespace std;
51
52 #ifdef GCC3
53 #define nspace __gnu_cxx
54 #else
55 #define nspace std
56 #endif
57
58 int LogLevel = DEFAULT;
59 char ServerName[MAXBUF];
60 char Network[MAXBUF];
61 char ServerDesc[MAXBUF];
62 char AdminName[MAXBUF];
63 char AdminEmail[MAXBUF];
64 char AdminNick[MAXBUF];
65 char diepass[MAXBUF];
66 char restartpass[MAXBUF];
67 char motd[MAXBUF];
68 char rules[MAXBUF];
69 char list[MAXBUF];
70 char PrefixQuit[MAXBUF];
71 char DieValue[MAXBUF];
72 int debugging =  0;
73 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
74 int WHOWAS_MAX = 100;  // default 100 people maximum in the WHOWAS list
75 int DieDelay  =  5;
76 time_t startup_time = time(NULL);
77
78 extern vector<Module*> modules;
79 vector<string> module_names;
80 extern vector<ircd_module*> factory;
81 vector<int> fd_reap;
82
83 extern int MODCOUNT;
84
85 bool nofork = false;
86
87 namespace nspace
88 {
89         template<> struct nspace::hash<in_addr>
90         {
91                 size_t operator()(const struct in_addr &a) const
92                 {
93                         size_t q;
94                         memcpy(&q,&a,sizeof(size_t));
95                         return q;
96                 }
97         };
98
99         template<> struct nspace::hash<string>
100         {
101                 size_t operator()(const string &s) const
102                 {
103                         char a[MAXBUF];
104                         static struct hash<const char *> strhash;
105                         strcpy(a,s.c_str());
106                         strlower(a);
107                         return strhash(a);
108                 }
109         };
110 }       
111
112
113 struct StrHashComp
114 {
115
116         bool operator()(const string& s1, const string& s2) const
117         {
118                 char a[MAXBUF],b[MAXBUF];
119                 strcpy(a,s1.c_str());
120                 strcpy(b,s2.c_str());
121                 return (strcasecmp(a,b) == 0);
122         }
123
124 };
125
126 struct InAddr_HashComp
127 {
128
129         bool operator()(const in_addr &s1, const in_addr &s2) const
130         {
131                 size_t q;
132                 size_t p;
133                 
134                 memcpy(&q,&s1,sizeof(size_t));
135                 memcpy(&p,&s2,sizeof(size_t));
136                 
137                 return (q == p);
138         }
139
140 };
141
142
143 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, StrHashComp> user_hash;
144 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, StrHashComp> chan_hash;
145 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, InAddr_HashComp> address_cache;
146 typedef std::deque<command_t> command_table;
147
148 serverrec* me[32];
149 serverrec* servers[255];
150
151 FILE *log_file;
152
153 user_hash clientlist;
154 chan_hash chanlist;
155 user_hash whowas;
156 command_table cmdlist;
157 file_cache MOTD;
158 file_cache RULES;
159 address_cache IP;
160
161 ClassVector Classes;
162
163 struct linger linger = { 0 };
164 char bannerBuffer[MAXBUF];
165 int boundPortCount = 0;
166 int portCount = 0, UDPportCount = 0, ports[MAXSOCKS];
167 int defaultRoute = 0;
168
169 connection C;
170
171 long MyKey = C.GenKey();
172
173 /* prototypes */
174
175 int has_channel(userrec *u, chanrec *c);
176 int usercount(chanrec *c);
177 int usercount_i(chanrec *c);
178 void update_stats_l(int fd,int data_out);
179 char* Passwd(userrec *user);
180 bool IsDenied(userrec *user);
181 void AddWhoWas(userrec* u);
182
183
184 void safedelete(userrec *p)
185 {
186         if (p)
187         {
188                 log(DEBUG,"deleting %s %s %s %s",p->nick,p->ident,p->dhost,p->fullname);
189                 log(DEBUG,"safedelete(userrec*): pointer is safe to delete");
190                 delete p;
191         }
192         else
193         {
194                 log(DEBUG,"safedelete(userrec*): unsafe pointer operation squished");
195         }
196 }
197
198 void safedelete(chanrec *p)
199 {
200         if (p)
201         {
202                 delete p;
203                 log(DEBUG,"safedelete(chanrec*): pointer is safe to delete");
204         }
205         else
206         {
207                 log(DEBUG,"safedelete(chanrec*): unsafe pointer operation squished");
208         }
209 }
210
211
212 void tidystring(char* str)
213 {
214         // strips out double spaces before a : parameter
215         
216         char temp[MAXBUF];
217         bool go_again = true;
218         
219         if (!str)
220         {
221                 return;
222         }
223         
224         while ((str[0] == ' ') && (strlen(str)>0))
225         {
226                 str++;
227         }
228         
229         while (go_again)
230         {
231                 bool noparse = false;
232                 int t = 0, a = 0;
233                 go_again = false;
234                 while (a < strlen(str))
235                 {
236                         if ((a<strlen(str)-1) && (noparse==false))
237                         {
238                                 if ((str[a] == ' ') && (str[a+1] == ' '))
239                                 {
240                                         log(DEBUG,"Tidied extra space out of string: %s",str);
241                                         go_again = true;
242                                         a++;
243                                 }
244                         }
245                         
246                         if (a<strlen(str)-1)
247                         {
248                                 if ((str[a] == ' ') && (str[a+1] == ':'))
249                                 {
250                                         noparse = true;
251                                 }
252                         }
253                         
254                         temp[t++] = str[a++];
255                 }
256                 temp[t] = '\0';
257                 strncpy(str,temp,MAXBUF);
258         }
259 }
260
261 /* chop a string down to 512 characters and preserve linefeed (irc max
262  * line length) */
263
264 void chop(char* str)
265 {
266
267   string temp = str;
268   FOREACH_MOD OnServerRaw(temp,false);
269   const char* str2 = temp.c_str();
270   sprintf(str,"%s",str2);
271   
272
273   if (strlen(str) >= 512)
274   {
275         str[509] = '\r';
276         str[510] = '\n';
277         str[511] = '\0';
278   }
279 }
280
281
282 std::string getservername()
283 {
284         return ServerName;
285 }
286
287 std::string getserverdesc()
288 {
289         return ServerDesc;
290 }
291
292 std::string getnetworkname()
293 {
294         return Network;
295 }
296
297 std::string getadminname()
298 {
299         return AdminName;
300 }
301
302 std::string getadminemail()
303 {
304         return AdminEmail;
305 }
306
307 std::string getadminnick()
308 {
309         return AdminNick;
310 }
311
312 void log(int level,char *text, ...)
313 {
314         char textbuffer[MAXBUF];
315         va_list argsPtr;
316         time_t rawtime;
317         struct tm * timeinfo;
318         if (level < LogLevel)
319                 return;
320
321         time(&rawtime);
322         timeinfo = localtime (&rawtime);
323
324         if (log_file)
325         {
326                 char b[MAXBUF];
327                 va_start (argsPtr, text);
328                 vsnprintf(textbuffer, MAXBUF, text, argsPtr);
329                 va_end(argsPtr);
330                 strcpy(b,asctime(timeinfo));
331                 b[strlen(b)-1] = ':';
332                 fprintf(log_file,"%s %s\n",b,textbuffer);
333                 if (nofork)
334                 {
335                         // nofork enabled? display it on terminal too
336                         printf("%s %s\n",b,textbuffer);
337                 }
338         }
339 }
340
341 void readfile(file_cache &F, const char* fname)
342 {
343   FILE* file;
344   char linebuf[MAXBUF];
345
346   log(DEBUG,"readfile: loading %s",fname);
347   F.clear();
348   file =  fopen(fname,"r");
349   if (file)
350   {
351         while (!feof(file))
352         {
353                 fgets(linebuf,sizeof(linebuf),file);
354                 linebuf[strlen(linebuf)-1]='\0';
355                 if (!strcmp(linebuf,""))
356                 {
357                         strcpy(linebuf,"  ");
358                 }
359                 if (!feof(file))
360                 {
361                         F.push_back(linebuf);
362                 }
363         }
364         fclose(file);
365   }
366   else
367   {
368           log(DEBUG,"readfile: failed to load file: %s",fname);
369   }
370   log(DEBUG,"readfile: loaded %s, %d lines",fname,F.size());
371 }
372
373 void ReadConfig(void)
374 {
375   char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF];
376   ConnectClass c;
377
378   ConfValue("server","name",0,ServerName);
379   ConfValue("server","description",0,ServerDesc);
380   ConfValue("server","network",0,Network);
381   ConfValue("admin","name",0,AdminName);
382   ConfValue("admin","email",0,AdminEmail);
383   ConfValue("admin","nick",0,AdminNick);
384   ConfValue("files","motd",0,motd);
385   ConfValue("files","rules",0,rules);
386   ConfValue("power","diepass",0,diepass);
387   ConfValue("power","pause",0,pauseval);
388   ConfValue("power","restartpass",0,restartpass);
389   ConfValue("options","prefixquit",0,PrefixQuit);
390   ConfValue("die","value",0,DieValue);
391   ConfValue("options","loglevel",0,dbg);
392   if (!strcmp(dbg,"debug"))
393         LogLevel = DEBUG;
394   if (!strcmp(dbg,"verbose"))
395         LogLevel = VERBOSE;
396   if (!strcmp(dbg,"default"))
397         LogLevel = DEFAULT;
398   if (!strcmp(dbg,"sparse"))
399         LogLevel = SPARSE;
400   if (!strcmp(dbg,"none"))
401         LogLevel = NONE;
402   readfile(RULES,rules);
403   log(DEBUG,"Reading connect classes");
404   Classes.clear();
405   for (int i = 0; i < ConfValueEnum("connect"); i++)
406   {
407         strcpy(Value,"");
408         ConfValue("connect","allow",i,Value);
409         if (strcmp(Value,""))
410         {
411                 strcpy(c.host,Value);
412                 c.type = CC_ALLOW;
413                 strcpy(Value,"");
414                 ConfValue("connect","password",i,Value);
415                 strcpy(c.pass,Value);
416                 Classes.push_back(c);
417                 log(DEBUG,"Read connect class type ALLOW, host=%s password=%s",c.host,c.pass);
418         }
419         else
420         {
421                 ConfValue("connect","deny",i,Value);
422                 strcpy(c.host,Value);
423                 c.type = CC_DENY;
424                 Classes.push_back(c);
425                 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
426         }
427         
428   }
429 }
430
431 void Blocking(int s)
432 {
433   int flags;
434   log(DEBUG,"Blocking: %d",s);
435   flags = fcntl(s, F_GETFL, 0);
436   fcntl(s, F_SETFL, flags ^ O_NONBLOCK);
437 }
438
439 void NonBlocking(int s)
440 {
441   int flags;
442   log(DEBUG,"NonBlocking: %d",s);
443   flags = fcntl(s, F_GETFL, 0);
444   fcntl(s, F_SETFL, flags | O_NONBLOCK);
445 }
446
447
448 int CleanAndResolve (char *resolvedHost, const char *unresolvedHost)
449 {
450   struct hostent *hostPtr = NULL;
451   struct in_addr addr;
452
453   memset (resolvedHost, '\0',MAXBUF);
454   if(unresolvedHost == NULL)
455         return(ERROR);
456   if ((inet_aton(unresolvedHost,&addr)) == 0)
457         return(ERROR);
458   hostPtr = gethostbyaddr ((char *)&addr.s_addr,sizeof(addr.s_addr),AF_INET);
459   if (hostPtr != NULL)
460         snprintf(resolvedHost,MAXBUF,"%s",hostPtr->h_name);
461   else
462         snprintf(resolvedHost,MAXBUF,"%s",unresolvedHost);
463   return (TRUE);
464 }
465
466 /* write formatted text to a socket, in same format as printf */
467
468 void Write(int sock,char *text, ...)
469 {
470   if (!text)
471   {
472         log(DEFAULT,"*** BUG *** Write was given an invalid parameter");
473         return;
474   }
475   char textbuffer[MAXBUF];
476   va_list argsPtr;
477   char tb[MAXBUF];
478
479   va_start (argsPtr, text);
480   vsnprintf(textbuffer, MAXBUF, text, argsPtr);
481   va_end(argsPtr);
482   sprintf(tb,"%s\r\n",textbuffer);
483   chop(tb);
484   write(sock,tb,strlen(tb));
485   update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
486 }
487
488 /* write a server formatted numeric response to a single socket */
489
490 void WriteServ(int sock, char* text, ...)
491 {
492   if (!text)
493   {
494         log(DEFAULT,"*** BUG *** WriteServ was given an invalid parameter");
495         return;
496   }
497   char textbuffer[MAXBUF],tb[MAXBUF];
498   va_list argsPtr;
499   va_start (argsPtr, text);
500
501   vsnprintf(textbuffer, MAXBUF, text, argsPtr);
502   va_end(argsPtr);
503   sprintf(tb,":%s %s\r\n",ServerName,textbuffer);
504   chop(tb);
505   write(sock,tb,strlen(tb));
506   update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
507 }
508
509 /* write text from an originating user to originating user */
510
511 void WriteFrom(int sock, userrec *user,char* text, ...)
512 {
513   if ((!text) || (!user))
514   {
515         log(DEFAULT,"*** BUG *** WriteFrom was given an invalid parameter");
516         return;
517   }
518   char textbuffer[MAXBUF],tb[MAXBUF];
519   va_list argsPtr;
520   va_start (argsPtr, text);
521
522   vsnprintf(textbuffer, MAXBUF, text, argsPtr);
523   va_end(argsPtr);
524   sprintf(tb,":%s!%s@%s %s\r\n",user->nick,user->ident,user->dhost,textbuffer);
525   chop(tb);
526   write(sock,tb,strlen(tb));
527   update_stats_l(sock,strlen(tb)); /* add one line-out to stats L for this fd */
528 }
529
530 /* write text to an destination user from a source user (e.g. user privmsg) */
531
532 void WriteTo(userrec *source, userrec *dest,char *data, ...)
533 {
534         if ((!source) || (!dest) || (!data))
535         {
536                 log(DEFAULT,"*** BUG *** WriteTo was given an invalid parameter");
537                 return;
538         }
539         char textbuffer[MAXBUF],tb[MAXBUF];
540         va_list argsPtr;
541         va_start (argsPtr, data);
542         vsnprintf(textbuffer, MAXBUF, data, argsPtr);
543         va_end(argsPtr);
544         chop(tb);
545         WriteFrom(dest->fd,source,"%s",textbuffer);
546 }
547
548 /* write formatted text from a source user to all users on a channel
549  * including the sender (NOT for privmsg, notice etc!) */
550
551 void WriteChannel(chanrec* Ptr, userrec* user, char* text, ...)
552 {
553         if ((!Ptr) || (!user) || (!text))
554         {
555                 log(DEFAULT,"*** BUG *** WriteChannel was given an invalid parameter");
556                 return;
557         }
558         char textbuffer[MAXBUF];
559         va_list argsPtr;
560         va_start (argsPtr, text);
561         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
562         va_end(argsPtr);
563         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
564         {
565                 if (has_channel(i->second,Ptr))
566                 {
567                         WriteTo(user,i->second,"%s",textbuffer);
568                 }
569         }
570 }
571
572 void WriteChannelWithServ(char* ServerName, chanrec* Ptr, userrec* user, char* text, ...)
573 {
574         if ((!Ptr) || (!user) || (!text))
575         {
576                 log(DEFAULT,"*** BUG *** WriteChannelWithServ was given an invalid parameter");
577                 return;
578         }
579         char textbuffer[MAXBUF];
580         va_list argsPtr;
581         va_start (argsPtr, text);
582         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
583         va_end(argsPtr);
584         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
585         {
586                 if (i->second)
587                 {
588                         if (has_channel(i->second,Ptr))
589                         {
590                                 WriteServ(i->second->fd,"%s",textbuffer);
591                         }
592                 }
593         }
594 }
595
596
597 /* write formatted text from a source user to all users on a channel except
598  * for the sender (for privmsg etc) */
599
600 void ChanExceptSender(chanrec* Ptr, userrec* user, char* text, ...)
601 {
602         if ((!Ptr) || (!user) || (!text))
603         {
604                 log(DEFAULT,"*** BUG *** ChanExceptSender was given an invalid parameter");
605                 return;
606         }
607         char textbuffer[MAXBUF];
608         va_list argsPtr;
609         va_start (argsPtr, text);
610         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
611         va_end(argsPtr);
612
613         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
614         {
615                 if (i->second)
616                 {
617                         if (has_channel(i->second,Ptr) && (user != i->second))
618                         {
619                                 WriteTo(user,i->second,"%s",textbuffer);
620                         }
621                 }
622         }
623 }
624
625 int c_count(userrec* u)
626 {
627         int z = 0;
628         for (int i =0; i != MAXCHANS; i++)
629                 if (u->chans[i].channel != NULL)
630                         z++;
631         return z;
632
633 }
634
635 /* return 0 or 1 depending if users u and u2 share one or more common channels
636  * (used by QUIT, NICK etc which arent channel specific notices) */
637
638 int common_channels(userrec *u, userrec *u2)
639 {
640         int i = 0;
641         int z = 0;
642
643         if ((!u) || (!u2))
644         {
645                 log(DEFAULT,"*** BUG *** common_channels was given an invalid parameter");
646                 return 0;
647         }
648         for (i = 0; i != MAXCHANS; i++)
649         {
650                 for (z = 0; z != MAXCHANS; z++)
651                 {
652                         if ((u->chans[i].channel != NULL) && (u2->chans[z].channel != NULL))
653                         {
654                                 if ((u->chans[i].channel == u2->chans[z].channel) && (u->chans[i].channel) && (u2->chans[z].channel) && (u->registered == 7) && (u2->registered == 7))
655                                 {
656                                         if ((c_count(u)) && (c_count(u2)))
657                                         {
658                                                 return 1;
659                                         }
660                                 }
661                         }
662                 }
663         }
664         return 0;
665 }
666
667 /* write a formatted string to all users who share at least one common
668  * channel, including the source user e.g. for use in NICK */
669
670 void WriteCommon(userrec *u, char* text, ...)
671 {
672         if (!u)
673         {
674                 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
675                 return;
676         }
677
678         if (u->registered != 7) {
679                 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
680                 return;
681         }
682         
683         char textbuffer[MAXBUF];
684         va_list argsPtr;
685         va_start (argsPtr, text);
686         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
687         va_end(argsPtr);
688
689         WriteFrom(u->fd,u,"%s",textbuffer);
690
691         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
692         {
693                 if (i->second)
694                 {
695                         if (common_channels(u,i->second) && (i->second != u))
696                         {
697                                 WriteFrom(i->second->fd,u,"%s",textbuffer);
698                         }
699                 }
700         }
701 }
702
703 /* write a formatted string to all users who share at least one common
704  * channel, NOT including the source user e.g. for use in QUIT */
705
706 void WriteCommonExcept(userrec *u, char* text, ...)
707 {
708         if (!u)
709         {
710                 log(DEFAULT,"*** BUG *** WriteCommon was given an invalid parameter");
711                 return;
712         }
713
714         if (u->registered != 7) {
715                 log(DEFAULT,"*** BUG *** WriteCommon on an unregistered user");
716                 return;
717         }
718
719         char textbuffer[MAXBUF];
720         va_list argsPtr;
721         va_start (argsPtr, text);
722         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
723         va_end(argsPtr);
724
725         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
726         {
727                 if (i->second)
728                 {
729                         if ((common_channels(u,i->second)) && (u != i->second))
730                         {
731                                 WriteFrom(i->second->fd,u,"%s",textbuffer);
732                         }
733                 }
734         }
735 }
736
737 void WriteOpers(char* text, ...)
738 {
739         if (!text)
740         {
741                 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
742                 return;
743         }
744
745         char textbuffer[MAXBUF];
746         va_list argsPtr;
747         va_start (argsPtr, text);
748         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
749         va_end(argsPtr);
750
751         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
752         {
753                 if (i->second)
754                 {
755                         if (strchr(i->second->modes,'o'))
756                         {
757                                 if (strchr(i->second->modes,'s'))
758                                 {
759                                         // send server notices to all with +s
760                                         // (TODO: needs SNOMASKs)
761                                         WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,textbuffer);
762                                 }
763                         }
764                 }
765         }
766 }
767
768 void WriteWallOps(userrec *source, char* text, ...)  
769 {  
770         if ((!text) || (!source))
771         {
772                 log(DEFAULT,"*** BUG *** WriteOpers was given an invalid parameter");
773                 return;
774         }
775
776         int i = 0;  
777         char textbuffer[MAXBUF];  
778         va_list argsPtr;  
779         va_start (argsPtr, text);  
780         vsnprintf(textbuffer, MAXBUF, text, argsPtr);  
781         va_end(argsPtr);  
782   
783         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
784         {
785                 if (i->second)
786                 {
787                         if (strchr(i->second->modes,'w'))
788                         {  
789                                 WriteTo(source,i->second,"WALLOPS %s",textbuffer);
790                         }
791                 }
792         }
793 }  
794
795 /* convert a string to lowercase. Note following special circumstances
796  * taken from RFC 1459. Many "official" server branches still hold to this
797  * rule so i will too;
798  *
799  *  Because of IRC's scandanavian origin, the characters {}| are
800  *  considered to be the lower case equivalents of the characters []\,
801  *  respectively. This is a critical issue when determining the
802  *  equivalence of two nicknames.
803  */
804
805 void strlower(char *n)
806 {
807         if (!n)
808         {
809                 return;
810         }
811         for (int i = 0; i != strlen(n); i++)
812         {
813                 n[i] = tolower(n[i]);
814                 if (n[i] == '[')
815                         n[i] = '{';
816                 if (n[i] == ']')
817                         n[i] = '}';
818                 if (n[i] == '\\')
819                         n[i] = '|';
820         }
821 }
822
823 /* verify that a user's ident and nickname is valid */
824
825 int isident(const char* n)
826 {
827         int i = 0;
828         char v[MAXBUF];
829         if (!n)
830
831         {
832                 return 0;
833         }
834         if (!strcmp(n,""))
835         {
836                 return 0;
837         }
838         for (i = 0; i != strlen(n); i++)
839         {
840                 if ((n[i] < 33) || (n[i] > 125))
841                 {
842                         return 0;
843                 }
844                 /* can't occur ANYWHERE in an Ident! */
845                 if (strchr("<>,./?:;@'~#=+()*&%$£ \"!",n[i]))
846                 {
847                         return 0;
848                 }
849         }
850         return 1;
851 }
852
853
854 int isnick(const char* n)
855 {
856         int i = 0;
857         char v[MAXBUF];
858         if (!n)
859         {
860                 return 0;
861         }
862         if (!strcmp(n,""))
863         {
864                 return 0;
865         }
866         if (strlen(n) > NICKMAX-1)
867         {
868                 return 0;
869         }
870         for (i = 0; i != strlen(n); i++)
871         {
872                 if ((n[i] < 33) || (n[i] > 125))
873                 {
874                         return 0;
875                 }
876                 /* can't occur ANYWHERE in a nickname! */
877                 if (strchr("<>,./?:;@'~#=+()*&%$£ \"!",n[i]))
878                 {
879                         return 0;
880                 }
881                 /* can't occur as the first char of a nickname... */
882                 if ((strchr("0123456789",n[i])) && (!i))
883                 {
884                         return 0;
885                 }
886         }
887         return 1;
888 }
889
890 /* Find a user record by nickname and return a pointer to it */
891
892 userrec* Find(string nick)
893 {
894         user_hash::iterator iter = clientlist.find(nick);
895
896         if (iter == clientlist.end())
897                 /* Couldn't find it */
898                 return NULL;
899
900         return iter->second;
901 }
902
903 void update_stats_l(int fd,int data_out) /* add one line-out to stats L for this fd */
904 {
905         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
906         {
907                 if (i->second)
908                 {
909                         if (i->second->fd == fd)
910                         {
911                                 i->second->bytes_out+=data_out;
912                                 i->second->cmds_out++;
913                         }
914                 }
915         }
916 }
917
918
919 /* find a channel record by channel name and return a pointer to it */
920
921 chanrec* FindChan(const char* chan)
922 {
923         if (!chan)
924         {
925                 log(DEFAULT,"*** BUG *** Findchan was given an invalid parameter");
926                 return NULL;
927         }
928
929         chan_hash::iterator iter = chanlist.find(chan);
930
931         if (iter == chanlist.end())
932                 /* Couldn't find it */
933                 return NULL;
934
935         return iter->second;
936 }
937
938
939 void purge_empty_chans(void)
940 {
941         int go_again = 1, purge = 0;
942         
943         while (go_again)
944         {
945                 go_again = 0;
946                 for (chan_hash::iterator i = chanlist.begin(); i != chanlist.end(); i++)
947                 {
948                         if (i->second) {
949                                 if (!usercount(i->second))
950                                 {
951                                         /* kill the record */
952                                         if (i != chanlist.end())
953                                         {
954                                                 log(DEBUG,"del_channel: destroyed: %s",i->second->name);
955                                                 delete i->second;
956                                                 chanlist.erase(i);
957                                                 go_again = 1;
958                                                 purge++;
959                                                 break;
960                                         }
961                                 }
962                                 else
963                                 {
964                                         log(DEBUG,"skipped purge for %s",i->second->name);
965                                 }
966                         }
967                 }
968         }
969         log(DEBUG,"completed channel purge, killed %d",purge);
970 }
971
972 /* returns the status character for a given user on a channel, e.g. @ for op,
973  * % for halfop etc. If the user has several modes set, the highest mode
974  * the user has must be returned. */
975
976 char* cmode(userrec *user, chanrec *chan)
977 {
978         if ((!user) || (!chan))
979         {
980                 log(DEFAULT,"*** BUG *** cmode was given an invalid parameter");
981                 return "";
982         }
983
984         int i;
985         for (i = 0; i != MAXCHANS; i++)
986         {
987                 if ((user->chans[i].channel == chan) && (chan != NULL))
988                 {
989                         if ((user->chans[i].uc_modes & UCMODE_OP) > 0)
990                         {
991                                 return "@";
992                         }
993                         if ((user->chans[i].uc_modes & UCMODE_HOP) > 0)
994                         {
995                                 return "%";
996                         }
997                         if ((user->chans[i].uc_modes & UCMODE_VOICE) > 0)
998                         {
999                                 return "+";
1000                         }
1001                         return "";
1002                 }
1003         }
1004 }
1005
1006 char scratch[MAXMODES];
1007 char sparam[MAXMODES];
1008
1009 char* chanmodes(chanrec *chan)
1010 {
1011         if (!chan)
1012         {
1013                 log(DEFAULT,"*** BUG *** chanmodes was given an invalid parameter");
1014                 strcpy(scratch,"");
1015                 return scratch;
1016         }
1017
1018         strcpy(scratch,"");
1019         strcpy(sparam,"");
1020         if (chan->noexternal)
1021         {
1022                 strcat(scratch,"n");
1023         }
1024         if (chan->topiclock)
1025         {
1026                 strcat(scratch,"t");
1027         }
1028         if (strcmp(chan->key,""))
1029         {
1030                 strcat(scratch,"k");
1031         }
1032         if (chan->limit)
1033         {
1034                 strcat(scratch,"l");
1035         }
1036         if (chan->inviteonly)
1037         {
1038                 strcat(scratch,"i");
1039         }
1040         if (chan->moderated)
1041         {
1042                 strcat(scratch,"m");
1043         }
1044         if (chan->secret)
1045         {
1046                 strcat(scratch,"s");
1047         }
1048         if (chan->c_private)
1049         {
1050                 strcat(scratch,"p");
1051         }
1052         if (strcmp(chan->key,""))
1053         {
1054                 strcat(sparam,chan->key);
1055         }
1056         if (chan->limit)
1057         {
1058                 char foo[24];
1059                 sprintf(foo," %d",chan->limit);
1060                 strcat(sparam,foo);
1061         }
1062         if (strlen(chan->custom_modes))
1063         {
1064                 // TODO: Tack on mode parameters here -
1065                 // IN ORDER OF CUSTOM_MODES!
1066                 strncat(scratch,chan->custom_modes,MAXMODES);
1067         }
1068         log(DEBUG,"chanmodes: %s %s%s",chan->name,scratch,sparam);
1069         strncat(scratch,sparam,MAXMODES);
1070         return scratch;
1071 }
1072
1073 /* returns the status value for a given user on a channel, e.g. STATUS_OP for
1074  * op, STATUS_VOICE for voice etc. If the user has several modes set, the
1075  * highest mode the user has must be returned. */
1076
1077 int cstatus(userrec *user, chanrec *chan)
1078 {
1079         if ((!chan) || (!user))
1080         {
1081                 log(DEFAULT,"*** BUG *** cstatus was given an invalid parameter");
1082                 return 0;
1083         }
1084
1085         int i;
1086         for (i = 0; i != MAXCHANS; i++)
1087         {
1088                 if ((user->chans[i].channel == chan) && (chan != NULL))
1089                 {
1090                         if ((user->chans[i].uc_modes & UCMODE_OP) > 0)
1091                         {
1092                                 return STATUS_OP;
1093                         }
1094                         if ((user->chans[i].uc_modes & UCMODE_HOP) > 0)
1095                         {
1096                                 return STATUS_HOP;
1097                         }
1098                         if ((user->chans[i].uc_modes & UCMODE_VOICE) > 0)
1099                         {
1100                                 return STATUS_VOICE;
1101                         }
1102                         return STATUS_NORMAL;
1103                 }
1104         }
1105 }
1106
1107
1108 /* compile a userlist of a channel into a string, each nick seperated by
1109  * spaces and op, voice etc status shown as @ and + */
1110
1111 void userlist(userrec *user,chanrec *c)
1112 {
1113         if ((!c) || (!user))
1114         {
1115                 log(DEFAULT,"*** BUG *** userlist was given an invalid parameter");
1116                 return;
1117         }
1118
1119         sprintf(list,"353 %s = %s :", user->nick, c->name);
1120         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1121         {
1122                 if (has_channel(i->second,c))
1123                 {
1124                         if (isnick(i->second->nick))
1125                         {
1126                                 if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1127                                 {
1128                                         /* user is +i, and source not on the channel, does not show
1129                                          * nick in NAMES list */
1130                                         continue;
1131                                 }
1132                                 strcat(list,cmode(i->second,c));
1133                                 strcat(list,i->second->nick);
1134                                 strcat(list," ");
1135                                 if (strlen(list)>(480-NICKMAX))
1136                                 {
1137                                         /* list overflowed into
1138                                          * multiple numerics */
1139                                         WriteServ(user->fd,list);
1140                                         sprintf(list,"353 %s = %s :", user->nick, c->name);
1141                                 }
1142                         }
1143                 }
1144         }
1145         /* if whats left in the list isnt empty, send it */
1146         if (list[strlen(list)-1] != ':')
1147         {
1148                 WriteServ(user->fd,list);
1149         }
1150 }
1151
1152 /* return a count of the users on a specific channel accounting for
1153  * invisible users who won't increase the count. e.g. for /LIST */
1154
1155 int usercount_i(chanrec *c)
1156 {
1157         int i = 0;
1158         int count = 0;
1159         
1160         if (!c)
1161         {
1162                 log(DEFAULT,"*** BUG *** usercount_i was given an invalid parameter");
1163                 return 0;
1164         }
1165
1166         strcpy(list,"");
1167         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1168         {
1169                 if (i->second)
1170                 {
1171                         if (has_channel(i->second,c))
1172                         {
1173                                 if (isnick(i->second->nick))
1174                                 {
1175                                         if ((!has_channel(i->second,c)) && (strchr(i->second->modes,'i')))
1176                                         {
1177                                                 /* user is +i, and source not on the channel, does not show
1178                                                  * nick in NAMES list */
1179                                                 continue;
1180                                         }
1181                                         count++;
1182                                 }
1183                         }
1184                 }
1185         }
1186         log(DEBUG,"usercount_i: %s %d",c->name,count);
1187         return count;
1188 }
1189
1190
1191 int usercount(chanrec *c)
1192 {
1193         int i = 0;
1194         int count = 0;
1195         
1196         if (!c)
1197         {
1198                 log(DEFAULT,"*** BUG *** usercount was given an invalid parameter");
1199                 return 0;
1200         }
1201
1202         strcpy(list,"");
1203         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1204         {
1205                 if (i->second)
1206                 {
1207                         if (has_channel(i->second,c))
1208                         {
1209                                 if ((isnick(i->second->nick)) && (i->second->registered == 7))
1210                                 {
1211                                         count++;
1212                                 }
1213                         }
1214                 }
1215         }
1216         log(DEBUG,"usercount: %s %d",c->name,count);
1217         return count;
1218 }
1219
1220
1221 /* add a channel to a user, creating the record for it if needed and linking
1222  * it to the user record */
1223
1224 chanrec* add_channel(userrec *user, char* cname, char* key)
1225 {
1226
1227         if ((!user) || (!cname))
1228         {
1229                 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
1230                 return 0;
1231         }
1232
1233         int i = 0;
1234         chanrec* Ptr;
1235         int created = 0;
1236         
1237         // we MUST declare this wherever we use FOREACH_RESULT
1238         int MOD_RESULT = 0;
1239
1240         if ((!cname) || (!user))
1241         {
1242                 return NULL;
1243         }
1244         if (strlen(cname) > CHANMAX-1)
1245         {
1246                 cname[CHANMAX-1] = '\0';
1247         }
1248
1249         log(DEBUG,"add_channel: %s %s",user->nick,cname);
1250         
1251         if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
1252         {
1253                 return NULL; // already on the channel!
1254         }
1255
1256
1257         if (!FindChan(cname))
1258         {
1259                 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
1260                 if (MOD_RESULT) {
1261                         return NULL;
1262                 }
1263
1264                 /* create a new one */
1265                 log(DEBUG,"add_channel: creating: %s",cname);
1266                 {
1267                         chanlist[cname] = new chanrec();
1268
1269                         strcpy(chanlist[cname]->name, cname);
1270                         chanlist[cname]->topiclock = 1;
1271                         chanlist[cname]->noexternal = 1;
1272                         chanlist[cname]->created = time(NULL);
1273                         strcpy(chanlist[cname]->topic, "");
1274                         strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
1275                         chanlist[cname]->topicset = 0;
1276                         Ptr = chanlist[cname];
1277                         log(DEBUG,"add_channel: created: %s",cname);
1278                         /* set created to 2 to indicate user
1279                          * is the first in the channel
1280                          * and should be given ops */
1281                         created = 2;
1282                 }
1283         }
1284         else
1285         {
1286                 /* channel exists, just fish out a pointer to its struct */
1287                 Ptr = FindChan(cname);
1288                 if (Ptr)
1289                 {
1290                         FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
1291                         if (MOD_RESULT) {
1292                                 return NULL;
1293                         }
1294                         
1295                         log(DEBUG,"add_channel: joining to: %s",Ptr->name);
1296                         if (strcmp(Ptr->key,""))
1297                         {
1298                                 log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
1299                                 if (!key)
1300                                 {
1301                                         log(DEBUG,"add_channel: no key given in JOIN");
1302                                         WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
1303                                         return NULL;
1304                                 }
1305                                 else
1306                                 {
1307                                         log(DEBUG,"key at %p is %s",key,key);
1308                                         if (strcasecmp(key,Ptr->key))
1309                                         {
1310                                                 log(DEBUG,"add_channel: bad key given in JOIN");
1311                                                 WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
1312                                                 return NULL;
1313                                         }
1314                                 }
1315                         }
1316                         log(DEBUG,"add_channel: no key");
1317
1318                         if (Ptr->inviteonly)
1319                         {
1320                                 log(DEBUG,"add_channel: channel is +i");
1321                                 if (user->IsInvited(Ptr->name))
1322                                 {
1323                                         /* user was invited to channel */
1324                                         /* there may be an optional channel NOTICE here */
1325                                 }
1326                                 else
1327                                 {
1328                                         WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
1329                                         return NULL;
1330                                 }
1331                         }
1332                         log(DEBUG,"add_channel: channel is not +i");
1333
1334                         if (Ptr->limit)
1335                         {
1336                                 if (usercount(Ptr) == Ptr->limit)
1337                                 {
1338                                         WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
1339                                         return NULL;
1340                                 }
1341                         }
1342                         
1343                         log(DEBUG,"add_channel: about to walk banlist");
1344
1345                         /* check user against the channel banlist */
1346                         for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
1347                         {
1348                                 if (match(user->GetFullHost(),i->data))
1349                                 {
1350                                         WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
1351                                         return NULL;
1352                                 }
1353                         }
1354
1355                         log(DEBUG,"add_channel: bans checked");
1356
1357                         user->RemoveInvite(Ptr->name);
1358
1359                         log(DEBUG,"add_channel: invites removed");
1360                         
1361                 }
1362                 created = 1;
1363         }
1364
1365         log(DEBUG,"Passed channel checks");
1366         
1367         for (i =0; i != MAXCHANS; i++)
1368         {
1369                 if (user->chans[i].channel == NULL)
1370                 {
1371                         log(DEBUG,"Adding into their channel list");
1372
1373                         if (created == 2) 
1374                         {
1375                                 /* first user in is given ops */
1376                                 user->chans[i].uc_modes = UCMODE_OP;
1377                         }
1378                         else
1379                         {
1380                                 user->chans[i].uc_modes = 0;
1381                         }
1382                         user->chans[i].channel = Ptr;
1383                         WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
1384
1385                         log(DEBUG,"Sent JOIN to client");
1386
1387                         if (Ptr->topicset)
1388                         {
1389                                 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
1390                                 WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
1391                         }
1392                         userlist(user,Ptr);
1393                         WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
1394                         WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
1395                         WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
1396                         FOREACH_MOD OnUserJoin(user,Ptr);
1397                         return Ptr;
1398                 }
1399         }
1400         log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
1401         WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
1402         return NULL;
1403 }
1404
1405 /* remove a channel from a users record, and remove the record from memory
1406  * if the channel has become empty */
1407
1408 chanrec* del_channel(userrec *user, char* cname, char* reason)
1409 {
1410         if ((!user) || (!cname))
1411         {
1412                 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
1413                 return NULL;
1414         }
1415
1416         int i = 0;
1417         chanrec* Ptr;
1418         int created = 0;
1419
1420         if ((!cname) || (!user))
1421         {
1422                 return NULL;
1423         }
1424
1425         Ptr = FindChan(cname);
1426         
1427         if (!Ptr)
1428         {
1429                 return NULL;
1430         }
1431
1432         FOREACH_MOD OnUserPart(user,Ptr);
1433         log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
1434         
1435         for (i =0; i != MAXCHANS; i++)
1436         {
1437                 /* zap it from the channel list of the user */
1438                 if (user->chans[i].channel == Ptr)
1439                 {
1440                         if (reason)
1441                         {
1442                                 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
1443                         }
1444                         else
1445                         {
1446                                 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
1447                         }
1448                         user->chans[i].uc_modes = 0;
1449                         user->chans[i].channel = NULL;
1450                         log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1451                         break;
1452                 }
1453         }
1454         
1455         /* if there are no users left on the channel */
1456         if (!usercount(Ptr))
1457         {
1458                 chan_hash::iterator iter = chanlist.find(Ptr->name);
1459
1460                 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1461
1462                 /* kill the record */
1463                 if (iter != chanlist.end())
1464                 {
1465                         log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1466                         delete iter->second;
1467                         chanlist.erase(iter);
1468                 }
1469         }
1470 }
1471
1472
1473 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
1474 {
1475         if ((!src) || (!user) || (!Ptr) || (!reason))
1476         {
1477                 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
1478                 return;
1479         }
1480
1481         int i = 0;
1482         int created = 0;
1483
1484         if ((!Ptr) || (!user) || (!src))
1485         {
1486                 return;
1487         }
1488
1489         log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
1490
1491         if (!has_channel(user,Ptr))
1492         {
1493                 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
1494                 return;
1495         }
1496         if ((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr)))
1497         {
1498                 if (cstatus(src,Ptr) == STATUS_HOP)
1499                 {
1500                         WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
1501                 }
1502                 else
1503                 {
1504                         WriteServ(src->fd,"482 %s %s :You must be at least a half-operator",src->nick, Ptr->name);
1505                 }
1506                 
1507                 return;
1508         }
1509         
1510         for (i =0; i != MAXCHANS; i++)
1511         {
1512                 /* zap it from the channel list of the user */
1513                 if (user->chans[i].channel == Ptr)
1514                 {
1515                         WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
1516                         user->chans[i].uc_modes = 0;
1517                         user->chans[i].channel = NULL;
1518                         log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
1519                         break;
1520                 }
1521         }
1522         
1523         /* if there are no users left on the channel */
1524         if (!usercount(Ptr))
1525         {
1526                 chan_hash::iterator iter = chanlist.find(Ptr->name);
1527
1528                 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
1529
1530                 /* kill the record */
1531                 if (iter != chanlist.end())
1532                 {
1533                         log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
1534                         delete iter->second;
1535                         chanlist.erase(iter);
1536                 }
1537         }
1538 }
1539
1540
1541 /* returns 1 if user u has channel c in their record, 0 if not */
1542
1543 int has_channel(userrec *u, chanrec *c)
1544 {
1545         int i = 0;
1546
1547         if ((!u) || (!c))
1548         {
1549                 log(DEFAULT,"*** BUG *** has_channel was given an invalid parameter");
1550                 return 0;
1551         }
1552         for (i =0; i != MAXCHANS; i++)
1553         {
1554                 if (u->chans[i].channel == c)
1555                 {
1556                         return 1;
1557                 }
1558         }
1559         return 0;
1560 }
1561
1562 int give_ops(userrec *user,char *dest,chanrec *chan,int status)
1563 {
1564         userrec *d;
1565         int i;
1566         
1567         if ((!user) || (!dest) || (!chan))
1568         {
1569                 log(DEFAULT,"*** BUG *** give_ops was given an invalid parameter");
1570                 return 0;
1571         }
1572         if (status != STATUS_OP)
1573         {
1574                 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1575                 return 0;
1576         }
1577         else
1578         {
1579                 if (!isnick(dest))
1580                 {
1581                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1582                         return 0;
1583                 }
1584                 d = Find(dest);
1585                 if (!d)
1586                 {
1587                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1588                         return 0;
1589                 }
1590                 else
1591                 {
1592                         for (i = 0; i != MAXCHANS; i++)
1593                         {
1594                                 if ((d->chans[i].channel == chan) && (chan != NULL))
1595                                 {
1596                                         if (d->chans[i].uc_modes & UCMODE_OP)
1597                                         {
1598                                                 /* mode already set on user, dont allow multiple */
1599                                                 return 0;
1600                                         }
1601                                         d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_OP;
1602                                         log(DEBUG,"gave ops: %s %s",d->chans[i].channel->name,d->nick);
1603                                 }
1604                         }
1605                 }
1606         }
1607         return 1;
1608 }
1609
1610 int give_hops(userrec *user,char *dest,chanrec *chan,int status)
1611 {
1612         userrec *d;
1613         int i;
1614         
1615         if ((!user) || (!dest) || (!chan))
1616         {
1617                 log(DEFAULT,"*** BUG *** give_hops was given an invalid parameter");
1618                 return 0;
1619         }
1620         if (status != STATUS_OP)
1621         {
1622                 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1623                 return 0;
1624         }
1625         else
1626         {
1627                 d = Find(dest);
1628                 if (!isnick(dest))
1629                 {
1630                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1631                         return 0;
1632                 }
1633                 if (!d)
1634                 {
1635                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1636                         return 0;
1637                 }
1638                 else
1639                 {
1640                         for (i = 0; i != MAXCHANS; i++)
1641                         {
1642                                 if ((d->chans[i].channel == chan) && (chan != NULL))
1643                                 {
1644                                         if (d->chans[i].uc_modes & UCMODE_HOP)
1645                                         {
1646                                                 /* mode already set on user, dont allow multiple */
1647                                                 return 0;
1648                                         }
1649                                         d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_HOP;
1650                                         log(DEBUG,"gave h-ops: %s %s",d->chans[i].channel->name,d->nick);
1651                                 }
1652                         }
1653                 }
1654         }
1655         return 1;
1656 }
1657
1658 int give_voice(userrec *user,char *dest,chanrec *chan,int status)
1659 {
1660         userrec *d;
1661         int i;
1662         
1663         if ((!user) || (!dest) || (!chan))
1664         {
1665                 log(DEFAULT,"*** BUG *** give_voice was given an invalid parameter");
1666                 return 0;
1667         }
1668         if (status < STATUS_HOP)
1669         {
1670                 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator",user->nick, chan->name);
1671                 return 0;
1672         }
1673         else
1674         {
1675                 d = Find(dest);
1676                 if (!isnick(dest))
1677                 {
1678                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1679                         return 0;
1680                 }
1681                 if (!d)
1682                 {
1683                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1684                         return 0;
1685                 }
1686                 else
1687                 {
1688                         for (i = 0; i != MAXCHANS; i++)
1689                         {
1690                                 if ((d->chans[i].channel == chan) && (chan != NULL))
1691                                 {
1692                                         if (d->chans[i].uc_modes & UCMODE_VOICE)
1693                                         {
1694                                                 /* mode already set on user, dont allow multiple */
1695                                                 return 0;
1696                                         }
1697                                         d->chans[i].uc_modes = d->chans[i].uc_modes | UCMODE_VOICE;
1698                                         log(DEBUG,"gave voice: %s %s",d->chans[i].channel->name,d->nick);
1699                                 }
1700                         }
1701                 }
1702         }
1703         return 1;
1704 }
1705
1706 int take_ops(userrec *user,char *dest,chanrec *chan,int status)
1707 {
1708         userrec *d;
1709         int i;
1710         
1711         if ((!user) || (!dest) || (!chan))
1712         {
1713                 log(DEFAULT,"*** BUG *** take_ops was given an invalid parameter");
1714                 return 0;
1715         }
1716         if (status != STATUS_OP)
1717         {
1718                 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1719                 return 0;
1720         }
1721         else
1722         {
1723                 d = Find(dest);
1724                 if (!isnick(dest))
1725                 {
1726                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1727                         return 0;
1728                 }
1729                 if (!d)
1730                 {
1731                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1732                         return 0;
1733                 }
1734                 else
1735                 {
1736                         for (i = 0; i != MAXCHANS; i++)
1737                         {
1738                                 if ((d->chans[i].channel == chan) && (chan != NULL))
1739                                 {
1740                                         if ((d->chans[i].uc_modes & UCMODE_OP) == 0)
1741                                         {
1742                                                 /* mode already set on user, dont allow multiple */
1743                                                 return 0;
1744                                         }
1745                                         d->chans[i].uc_modes ^= UCMODE_OP;
1746                                         log(DEBUG,"took ops: %s %s",d->chans[i].channel->name,d->nick);
1747                                 }
1748                         }
1749                 }
1750         }
1751         return 1;
1752 }
1753
1754 int take_hops(userrec *user,char *dest,chanrec *chan,int status)
1755 {
1756         userrec *d;
1757         int i;
1758         
1759         if ((!user) || (!dest) || (!chan))
1760         {
1761                 log(DEFAULT,"*** BUG *** take_hops was given an invalid parameter");
1762                 return 0;
1763         }
1764         if (status != STATUS_OP)
1765         {
1766                 WriteServ(user->fd,"482 %s %s :You're not a channel operator",user->nick, chan->name);
1767                 return 0;
1768         }
1769         else
1770         {
1771                 d = Find(dest);
1772                 if (!isnick(dest))
1773                 {
1774                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1775                         return 0;
1776                 }
1777                 if (!d)
1778                 {
1779                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1780                         return 0;
1781                 }
1782                 else
1783                 {
1784                         for (i = 0; i != MAXCHANS; i++)
1785                         {
1786                                 if ((d->chans[i].channel == chan) && (chan != NULL))
1787                                 {
1788                                         if ((d->chans[i].uc_modes & UCMODE_HOP) == 0)
1789                                         {
1790                                                 /* mode already set on user, dont allow multiple */
1791                                                 return 0;
1792                                         }
1793                                         d->chans[i].uc_modes ^= UCMODE_HOP;
1794                                         log(DEBUG,"took h-ops: %s %s",d->chans[i].channel->name,d->nick);
1795                                 }
1796                         }
1797                 }
1798         }
1799         return 1;
1800 }
1801
1802 int take_voice(userrec *user,char *dest,chanrec *chan,int status)
1803 {
1804         userrec *d;
1805         int i;
1806         
1807         if ((!user) || (!dest) || (!chan))
1808         {
1809                 log(DEFAULT,"*** BUG *** take_voice was given an invalid parameter");
1810                 return 0;
1811         }
1812         if (status < STATUS_HOP)
1813         {
1814                 WriteServ(user->fd,"482 %s %s :You must be at least a half-operator",user->nick, chan->name);
1815                 return 0;
1816         }
1817         else
1818         {
1819                 d = Find(dest);
1820                 if (!isnick(dest))
1821                 {
1822                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1823                         return 0;
1824                 }
1825                 if (!d)
1826                 {
1827                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, dest);
1828                         return 0;
1829                 }
1830                 else
1831                 {
1832                         for (i = 0; i != MAXCHANS; i++)
1833                         {
1834                                 if ((d->chans[i].channel == chan) && (chan != NULL))
1835                                 {
1836                                         if ((d->chans[i].uc_modes & UCMODE_VOICE) == 0)
1837                                         {
1838                                                 /* mode already set on user, dont allow multiple */
1839                                                 return 0;
1840                                         }
1841                                         d->chans[i].uc_modes ^= UCMODE_VOICE;
1842                                         log(DEBUG,"took voice: %s %s",d->chans[i].channel->name,d->nick);
1843                                 }
1844                         }
1845                 }
1846         }
1847         return 1;
1848 }
1849
1850 void TidyBan(char *ban)
1851 {
1852         if (!ban) {
1853                 log(DEFAULT,"*** BUG *** TidyBan was given an invalid parameter");
1854                 return;
1855         }
1856         
1857         char temp[MAXBUF],NICK[MAXBUF],IDENT[MAXBUF],HOST[MAXBUF];
1858
1859         strcpy(temp,ban);
1860
1861         char* pos_of_pling = strchr(temp,'!');
1862         char* pos_of_at = strchr(temp,'@');
1863
1864         pos_of_pling[0] = '\0';
1865         pos_of_at[0] = '\0';
1866         pos_of_pling++;
1867         pos_of_at++;
1868
1869         strncpy(NICK,temp,NICKMAX);
1870         strncpy(IDENT,pos_of_pling,IDENTMAX+1);
1871         strncpy(HOST,pos_of_at,160);
1872
1873         sprintf(ban,"%s!%s@%s",NICK,IDENT,HOST);
1874 }
1875
1876 int add_ban(userrec *user,char *dest,chanrec *chan,int status)
1877 {
1878         if ((!user) || (!dest) || (!chan)) {
1879                 log(DEFAULT,"*** BUG *** add_ban was given an invalid parameter");
1880                 return 0;
1881         }
1882
1883         BanItem b;
1884         if ((!user) || (!dest) || (!chan))
1885                 return 0;
1886         if (strchr(dest,'!')==0)
1887                 return 0;
1888         if (strchr(dest,'@')==0)
1889                 return 0;
1890         for (int i = 0; i < strlen(dest); i++)
1891                 if (dest[i] < 32)
1892                         return 0;
1893         for (int i = 0; i < strlen(dest); i++)
1894                 if (dest[i] > 126)
1895                         return 0;
1896         int c = 0;
1897         for (int i = 0; i < strlen(dest); i++)
1898                 if (dest[i] == '!')
1899                         c++;
1900         if (c>1)
1901                 return 0;
1902         c = 0;
1903         for (int i = 0; i < strlen(dest); i++)
1904                 if (dest[i] == '@')
1905                         c++;
1906         if (c>1)
1907                 return 0;
1908         log(DEBUG,"add_ban: %s %s",chan->name,user->nick);
1909
1910         TidyBan(dest);
1911         for (BanList::iterator i = chan->bans.begin(); i != chan->bans.end(); i++)
1912         {
1913                 if (!strcasecmp(i->data,dest))
1914                 {
1915                         // dont allow a user to set the same ban twice
1916                         return 0;
1917                 }
1918         }
1919
1920         b.set_time = time(NULL);
1921         strncpy(b.data,dest,MAXBUF);
1922         strncpy(b.set_by,user->nick,NICKMAX);
1923         chan->bans.push_back(b);
1924         return 1;
1925 }
1926
1927 int take_ban(userrec *user,char *dest,chanrec *chan,int status)
1928 {
1929         if ((!user) || (!dest) || (!chan)) {
1930                 log(DEFAULT,"*** BUG *** take_ban was given an invalid parameter");
1931                 return 0;
1932         }
1933
1934         log(DEBUG,"del_ban: %s %s",chan->name,user->nick);
1935         for (BanList::iterator i = chan->bans.begin(); i != chan->bans.end(); i++)
1936         {
1937                 if (!strcasecmp(i->data,dest))
1938                 {
1939                         chan->bans.erase(i);
1940                         return 1;
1941                 }
1942         }
1943         return 0;
1944 }
1945
1946 void process_modes(char **parameters,userrec* user,chanrec *chan,int status, int pcnt, bool servermode)
1947 {
1948         if ((!parameters) || (!user)) {
1949                 log(DEFAULT,"*** BUG *** process_modes was given an invalid parameter");
1950                 return;
1951         }
1952
1953
1954         char modelist[MAXBUF];
1955         char outlist[MAXBUF];
1956         char outstr[MAXBUF];
1957         char outpars[32][MAXBUF];
1958         int param = 2;
1959         int pc = 0;
1960         int ptr = 0;
1961         int mdir = 1;
1962         int r = 0;
1963         bool k_set = false, l_set = false;
1964
1965         if (pcnt < 2)
1966         {
1967                 return;
1968         }
1969
1970         log(DEBUG,"process_modes: start");
1971
1972         strcpy(modelist,parameters[1]); /* mode list, e.g. +oo-o */
1973                                         /* parameters[2] onwards are parameters for
1974                                          * modes that require them :) */
1975         strcpy(outlist,"+");
1976         mdir = 1;
1977
1978         log(DEBUG,"process_modes: modelist: %s",modelist);
1979
1980         for (ptr = 0; ptr < strlen(modelist); ptr++)
1981         {
1982                 r = 0;
1983
1984                 {
1985                         log(DEBUG,"process_modes: modechar: %c",modelist[ptr]);
1986                         char modechar = modelist[ptr];
1987                         switch (modelist[ptr])
1988                         {
1989                                 case '-':
1990                                         if (mdir != 0)
1991                                         {
1992                                                 if ((outlist[strlen(outlist)-1] == '+') || (outlist[strlen(outlist)-1] == '-'))
1993                                                 {
1994                                                         outlist[strlen(outlist)-1] = '-';
1995                                                 }
1996                                                 else
1997                                                 {
1998                                                         strcat(outlist,"-");
1999                                                 }
2000                                         }
2001                                         mdir = 0;
2002                                         
2003                                 break;                  
2004
2005                                 case '+':
2006                                         if (mdir != 1)
2007                                         {
2008                                                 if ((outlist[strlen(outlist)-1] == '+') || (outlist[strlen(outlist)-1] == '-'))
2009                                                 {
2010                                                         outlist[strlen(outlist)-1] = '+';
2011                                                 }
2012                                                 else
2013                                                 {
2014                                                         strcat(outlist,"+");
2015                                                 }
2016                                         }
2017                                         mdir = 1;
2018                                 break;
2019
2020                                 case 'o':
2021                                         if ((param >= pcnt)) break;
2022                                         if (mdir == 1)
2023                                         {
2024                                                 r = give_ops(user,parameters[param++],chan,status);
2025                                         }
2026                                         else
2027                                         {
2028                                                 r = take_ops(user,parameters[param++],chan,status);
2029                                         }
2030                                         if (r)
2031                                         {
2032                                                 strcat(outlist,"o");
2033                                                 strcpy(outpars[pc++],parameters[param-1]);
2034                                         }
2035                                 break;
2036                         
2037                                 case 'h':
2038                                         if ((param >= pcnt)) break;
2039                                         if (mdir == 1)
2040                                         {
2041                                                 r = give_hops(user,parameters[param++],chan,status);
2042                                         }
2043                                         else
2044                                         {
2045                                                 r = take_hops(user,parameters[param++],chan,status);
2046                                         }
2047                                         if (r)
2048                                         {
2049                                                 strcat(outlist,"h");
2050                                                 strcpy(outpars[pc++],parameters[param-1]);
2051                                         }
2052                                 break;
2053                         
2054                                 
2055                                 case 'v':
2056                                         if ((param >= pcnt)) break;
2057                                         if (mdir == 1)
2058                                         {
2059                                                 r = give_voice(user,parameters[param++],chan,status);
2060                                         }
2061                                         else
2062                                         {
2063                                                 r = take_voice(user,parameters[param++],chan,status);
2064                                         }
2065                                         if (r)
2066                                         {
2067                                                 strcat(outlist,"v");
2068                                                 strcpy(outpars[pc++],parameters[param-1]);
2069                                         }
2070                                 break;
2071                                 
2072                                 case 'b':
2073                                         if ((param >= pcnt)) break;
2074                                         if (mdir == 1)
2075                                         {
2076                                                 r = add_ban(user,parameters[param++],chan,status);
2077                                         }
2078                                         else
2079                                         {
2080                                                 r = take_ban(user,parameters[param++],chan,status);
2081                                         }
2082                                         if (r)
2083                                         {
2084                                                 strcat(outlist,"b");
2085                                                 strcpy(outpars[pc++],parameters[param-1]);
2086                                         }
2087                                 break;
2088
2089
2090                                 case 'k':
2091                                         if ((param >= pcnt))
2092                                                 break;
2093
2094                                         if (mdir == 1)
2095                                         {
2096                                                 if (k_set)
2097                                                         break;
2098                                                 
2099                                                 if (!strcmp(chan->key,""))
2100                                                 {
2101                                                         strcat(outlist,"k");
2102                                                         char key[MAXBUF];
2103                                                         strcpy(key,parameters[param++]);
2104                                                         if (strlen(key)>32) {
2105                                                                 key[31] = '\0';
2106                                                         }
2107                                                         strcpy(outpars[pc++],key);
2108                                                         strcpy(chan->key,key);
2109                                                         k_set = true;
2110                                                 }
2111                                         }
2112                                         else
2113                                         {
2114                                                 /* checks on -k are case sensitive and only accurate to the
2115                                                    first 32 characters */
2116                                                 char key[MAXBUF];
2117                                                 strcpy(key,parameters[param++]);
2118                                                 if (strlen(key)>32) {
2119                                                         key[31] = '\0';
2120                                                 }
2121                                                 /* only allow -k if correct key given */
2122                                                 if (!strcmp(chan->key,key))
2123                                                 {
2124                                                         strcat(outlist,"k");
2125                                                         strcpy(chan->key,"");
2126                                                         strcpy(outpars[pc++],key);
2127                                                 }
2128                                         }
2129                                 break;
2130                                 
2131                                 case 'l':
2132                                         if (mdir == 0)
2133                                         {
2134                                                 if (chan->limit)
2135                                                 {
2136                                                         strcat(outlist,"l");
2137                                                         chan->limit = 0;
2138                                                 }
2139                                         }
2140                                         
2141                                         if ((param >= pcnt)) break;
2142                                         if (mdir == 1)
2143                                         {
2144                                                 if (l_set)
2145                                                         break;
2146                                                 
2147                                                 bool invalid = false;
2148                                                 for (int i = 0; i < strlen(parameters[param]); i++)
2149                                                 {
2150                                                         if ((parameters[param][i] < '0') || (parameters[param][i] > '9'))
2151                                                         {
2152                                                                 invalid = true;
2153                                                         }
2154                                                 }
2155                                                 if (atoi(parameters[param]) < 1)
2156                                                 {
2157                                                         invalid = true;
2158                                                 }
2159
2160                                                 if (invalid)
2161                                                         break;
2162                                                 
2163                                                 chan->limit = atoi(parameters[param]);
2164                                                 if (chan->limit)
2165                                                 {
2166                                                         strcat(outlist,"l");
2167                                                         strcpy(outpars[pc++],parameters[param++]);
2168                                                         l_set = true;
2169                                                 }
2170                                         }
2171                                 break;
2172                                 
2173                                 case 'i':
2174                                         if (chan->inviteonly != mdir)
2175                                         {
2176                                                 strcat(outlist,"i");
2177                                         }
2178                                         chan->inviteonly = mdir;
2179                                 break;
2180                                 
2181                                 case 't':
2182                                         if (chan->topiclock != mdir)
2183                                         {
2184                                                 strcat(outlist,"t");
2185                                         }
2186                                         chan->topiclock = mdir;
2187                                 break;
2188                                 
2189                                 case 'n':
2190                                         if (chan->noexternal != mdir)
2191                                         {
2192                                                 strcat(outlist,"n");
2193                                         }
2194                                         chan->noexternal = mdir;
2195                                 break;
2196                                 
2197                                 case 'm':
2198                                         if (chan->moderated != mdir)
2199                                         {
2200                                                 strcat(outlist,"m");
2201                                         }
2202                                         chan->moderated = mdir;
2203                                 break;
2204                                 
2205                                 case 's':
2206                                         if (chan->secret != mdir)
2207                                         {
2208                                                 strcat(outlist,"s");
2209                                                 if (chan->c_private)
2210                                                 {
2211                                                         chan->c_private = 0;
2212                                                         if (mdir)
2213                                                         {
2214                                                                 strcat(outlist,"-p+");
2215                                                         }
2216                                                         else
2217                                                         {
2218                                                                 strcat(outlist,"+p-");
2219                                                         }
2220                                                 }
2221                                         }
2222                                         chan->secret = mdir;
2223                                 break;
2224                                 
2225                                 case 'p':
2226                                         if (chan->c_private != mdir)
2227                                         {
2228                                                 strcat(outlist,"p");
2229                                                 if (chan->secret)
2230                                                 {
2231                                                         chan->secret = 0;
2232                                                         if (mdir)
2233                                                         {
2234                                                                 strcat(outlist,"-s+");
2235                                                         }
2236                                                         else
2237                                                         {
2238                                                                 strcat(outlist,"+s-");
2239                                                         }
2240                                                 }
2241                                         }
2242                                         chan->c_private = mdir;
2243                                 break;
2244                                 
2245                                 default:
2246                                         log(DEBUG,"Preprocessing custom mode %c",modechar);
2247                                         string_list p;
2248                                         p.clear();
2249                                         if (((!strchr(chan->custom_modes,modechar)) && (!mdir)) || ((strchr(chan->custom_modes,modechar)) && (mdir)))
2250                                         {
2251                                                 log(DEBUG,"Mode %c isnt set on %s but trying to remove!",modechar,chan->name);
2252                                                 break;
2253                                         }
2254                                         if (ModeDefined(modechar,MT_CHANNEL))
2255                                         {
2256                                                 log(DEBUG,"A module has claimed this mode");
2257                                                 if (param<pcnt)
2258                                                 {
2259                                                         if ((ModeDefinedOn(modechar,MT_CHANNEL)>0) && (mdir))
2260                                                         {
2261                                                                 p.push_back(parameters[param]);
2262                                                         }
2263                                                         if ((ModeDefinedOff(modechar,MT_CHANNEL)>0) && (!mdir))
2264                                                         {
2265                                                                 p.push_back(parameters[param]);
2266                                                         }
2267                                                 }
2268                                                 bool handled = false;
2269                                                 if (param>=pcnt)
2270                                                 {
2271                                                         log(DEBUG,"Not enough parameters for module-mode %c",modechar);
2272                                                         // we're supposed to have a parameter, but none was given... so dont handle the mode.
2273                                                         if (((ModeDefinedOn(modechar,MT_CHANNEL)>0) && (mdir)) || ((ModeDefinedOff(modechar,MT_CHANNEL)>0) && (!mdir))) 
2274                                                         {
2275                                                                 handled = true;
2276                                                                 param++;
2277                                                         }
2278                                                 }
2279                                                 for (int i = 0; i <= MODCOUNT; i++)
2280                                                 {
2281                                                         if (!handled)
2282                                                         {
2283                                                                 if (modules[i]->OnExtendedMode(user,chan,modechar,MT_CHANNEL,mdir,p))
2284                                                                 {
2285                                                                         log(DEBUG,"OnExtendedMode returned nonzero for a module");
2286                                                                         char app[] = {modechar, 0};
2287                                                                         if (ptr>0)
2288                                                                         {
2289                                                                                 if ((modelist[ptr-1] == '+') || (modelist[ptr-1] == '-'))
2290                                                                                 {
2291                                                                                         strcat(outlist, app);
2292                                                                                 }
2293                                                                                 else if (!strchr(outlist,modechar))
2294                                                                                 {
2295                                                                                         strcat(outlist, app);
2296                                                                                 }
2297                                                                         }
2298                                                                         chan->SetCustomMode(modechar,mdir);
2299                                                                         // include parameters in output if mode has them
2300                                                                         if ((ModeDefinedOn(modechar,MT_CHANNEL)>0) && (mdir))
2301                                                                         {
2302                                                                                 chan->SetCustomModeParam(modelist[ptr],parameters[param],mdir);
2303                                                                                 strcpy(outpars[pc++],parameters[param++]);
2304                                                                         }
2305                                                                         // break, because only one module can handle the mode.
2306                                                                         handled = true;
2307                                                                 }
2308                                                         }
2309                                                 }
2310                                         }
2311                                 break;
2312                                 
2313                         }
2314                 }
2315         }
2316
2317         /* this ensures only the *valid* modes are sent out onto the network */
2318         while ((outlist[strlen(outlist)-1] == '-') || (outlist[strlen(outlist)-1] == '+'))
2319         {
2320                 outlist[strlen(outlist)-1] = '\0';
2321         }
2322         if (strcmp(outlist,""))
2323         {
2324                 strcpy(outstr,outlist);
2325                 for (ptr = 0; ptr < pc; ptr++)
2326                 {
2327                         strcat(outstr," ");
2328                         strcat(outstr,outpars[ptr]);
2329                 }
2330                 if (servermode)
2331                 {
2332                         WriteChannelWithServ(ServerName,chan,user,"MODE %s %s",chan->name,outstr);
2333                 }
2334                 else
2335                 {
2336                         WriteChannel(chan,user,"MODE %s %s",chan->name,outstr);
2337                 }
2338         }
2339 }
2340
2341 void handle_mode(char **parameters, int pcnt, userrec *user)
2342 {
2343         chanrec* Ptr;
2344         userrec* dest;
2345         int can_change,i;
2346         int direction = 1;
2347         char outpars[MAXBUF];
2348
2349         dest = Find(parameters[0]);
2350
2351         if ((dest) && (pcnt == 1))
2352         {
2353                 WriteServ(user->fd,"221 %s :+%s",user->nick,user->modes);
2354                 return;
2355         }
2356         if ((dest) && (pcnt > 1))
2357         {
2358                 can_change = 0;
2359                 if (user != dest)
2360                 {
2361                         if (strchr(user->modes,'o'))
2362                         {
2363                                 can_change = 1;
2364                         }
2365                 }
2366                 else
2367                 {
2368                         can_change = 1;
2369                 }
2370                 if (!can_change)
2371                 {
2372                         WriteServ(user->fd,"482 %s :Can't change mode for other users",user->nick);
2373                         return;
2374                 }
2375                 
2376                 strcpy(outpars,"+");
2377                 direction = 1;
2378
2379                 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
2380                         return;
2381
2382                 for (i = 0; i < strlen(parameters[1]); i++)
2383                 {
2384                         if (parameters[1][i] == '+')
2385                         {
2386                                 if (direction != 1)
2387                                 {
2388                                         if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2389                                         {
2390                                                 outpars[strlen(outpars)-1] = '+';
2391                                         }
2392                                         else
2393                                         {
2394                                                 strcat(outpars,"+");
2395                                         }
2396                                 }
2397                                 direction = 1;
2398                         }
2399                         else
2400                         if (parameters[1][i] == '-')
2401                         {
2402                                 if (direction != 0)
2403                                 {
2404                                         if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2405                                         {
2406                                                 outpars[strlen(outpars)-1] = '-';
2407                                         }
2408                                         else
2409                                         {
2410                                                 strcat(outpars,"-");
2411                                         }
2412                                 }
2413                                 direction = 0;
2414                         }
2415                         else
2416                         {
2417                                 can_change = 0;
2418                                 if (strchr(user->modes,'o'))
2419                                 {
2420                                         can_change = 1;
2421                                 }
2422                                 else
2423                                 {
2424                                         if ((parameters[1][i] == 'i') || (parameters[1][i] == 'w') || (parameters[1][i] == 's'))
2425                                         {
2426                                                 can_change = 1;
2427                                         }
2428                                 }
2429                                 if (can_change)
2430                                 {
2431                                         if (direction == 1)
2432                                         {
2433                                                 if (!strchr(dest->modes,parameters[1][i]))
2434                                                 {
2435                                                         dest->modes[strlen(dest->modes)+1]='\0';
2436                                                         dest->modes[strlen(dest->modes)] = parameters[1][i];
2437                                                         outpars[strlen(outpars)+1]='\0';
2438                                                         outpars[strlen(outpars)] = parameters[1][i];
2439                                                 }
2440                                         }
2441                                         else
2442                                         {
2443                                                 int q = 0;
2444                                                 char temp[MAXBUF];
2445                                                 char moo[MAXBUF];
2446
2447                                                 outpars[strlen(outpars)+1]='\0';
2448                                                 outpars[strlen(outpars)] = parameters[1][i];
2449                                                 
2450                                                 strcpy(temp,"");
2451                                                 for (q = 0; q < strlen(user->modes); q++)
2452                                                 {
2453                                                         if (user->modes[q] != parameters[1][i])
2454                                                         {
2455                                                                 moo[0] = user->modes[q];
2456                                                                 moo[1] = '\0';
2457                                                                 strcat(temp,moo);
2458                                                         }
2459                                                 }
2460                                                 strcpy(user->modes,temp);
2461                                         }
2462                                 }
2463                         }
2464                 }
2465                 if (strlen(outpars))
2466                 {
2467                         char b[MAXBUF];
2468                         strcpy(b,"");
2469                         int z = 0;
2470                         int i = 0;
2471                         while (i < strlen (outpars))
2472                         {
2473                                 b[z++] = outpars[i++];
2474                                 b[z] = '\0';
2475                                 if (i<strlen(outpars)-1)
2476                                 {
2477                                         if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
2478                                         {
2479                                                 // someones playing silly buggers and trying
2480                                                 // to put a +- or -+ into the line...
2481                                                 i++;
2482                                         }
2483                                 }
2484                                 if (i == strlen(outpars)-1)
2485                                 {
2486                                         if ((outpars[i] == '-') || (outpars[i] == '+'))
2487                                         {
2488                                                 i++;
2489                                         }
2490                                 }
2491                         }
2492
2493                         z = strlen(b)-1;
2494                         if ((b[z] == '-') || (b[z] == '+'))
2495                                 b[z] == '\0';
2496
2497                         if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
2498                                 return;
2499
2500                         WriteTo(user, dest, "MODE %s :%s", dest->nick, b);
2501                 }
2502                 return;
2503         }
2504         
2505         Ptr = FindChan(parameters[0]);
2506         if (Ptr)
2507         {
2508                 if (pcnt == 1)
2509                 {
2510                         /* just /modes #channel */
2511                         WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name, chanmodes(Ptr));
2512                         WriteServ(user->fd,"329 %s %s %d", user->nick, Ptr->name, Ptr->created);
2513                         return;
2514                 }
2515                 else
2516                 if (pcnt == 2)
2517                 {
2518                         if ((!strcmp(parameters[1],"+b")) || (!strcmp(parameters[1],"b")))
2519                         {
2520
2521                                 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
2522                                 {
2523                                         WriteServ(user->fd,"367 %s %s %s %s %d",user->nick, Ptr->name, i->data, i->set_by, i->set_time);
2524                                 }
2525                                 WriteServ(user->fd,"368 %s %s :End of channel ban list",user->nick, Ptr->name);
2526                         }
2527                 }
2528
2529                 if ((cstatus(user,Ptr) < STATUS_HOP) && (Ptr))
2530                 {
2531                         WriteServ(user->fd,"482 %s %s :You must be at least a half-operator",user->nick, Ptr->name);
2532                         return;
2533                 }
2534
2535                 process_modes(parameters,user,Ptr,cstatus(user,Ptr),pcnt,false);
2536         }
2537         else
2538         {
2539                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2540         }
2541 }
2542
2543
2544
2545
2546 void server_mode(char **parameters, int pcnt, userrec *user)
2547 {
2548         chanrec* Ptr;
2549         userrec* dest;
2550         int can_change,i;
2551         int direction = 1;
2552         char outpars[MAXBUF];
2553
2554         dest = Find(parameters[0]);
2555
2556         if ((dest) && (pcnt > 1))
2557         {
2558                 strcpy(outpars,"+");
2559                 direction = 1;
2560
2561                 if ((parameters[1][0] != '+') && (parameters[1][0] != '-'))
2562                         return;
2563
2564                 for (i = 0; i < strlen(parameters[1]); i++)
2565                 {
2566                         if (parameters[1][i] == '+')
2567                         {
2568                                 if (direction != 1)
2569                                 {
2570                                         if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2571                                         {
2572                                                 outpars[strlen(outpars)-1] = '+';
2573                                         }
2574                                         else
2575                                         {
2576                                                 strcat(outpars,"+");
2577                                         }
2578                                 }
2579                                 direction = 1;
2580                         }
2581                         else
2582                         if (parameters[1][i] == '-')
2583                         {
2584                                 if (direction != 0)
2585                                 {
2586                                         if ((outpars[strlen(outpars)-1] == '+') || (outpars[strlen(outpars)-1] == '-'))
2587                                         {
2588                                                 outpars[strlen(outpars)-1] = '-';
2589                                         }
2590                                         else
2591                                         {
2592                                                 strcat(outpars,"-");
2593                                         }
2594                                 }
2595                                 direction = 0;
2596                         }
2597                         else
2598                         {
2599                                 can_change = 0;
2600                                 if (strchr(user->modes,'o'))
2601                                 {
2602                                         can_change = 1;
2603                                 }
2604                                 else
2605                                 {
2606                                         if ((parameters[1][i] == 'i') || (parameters[1][i] == 'w') || (parameters[1][i] == 's'))
2607                                         {
2608                                                 can_change = 1;
2609                                         }
2610                                 }
2611                                 if (can_change)
2612                                 {
2613                                         if (direction == 1)
2614                                         {
2615                                                 if (!strchr(dest->modes,parameters[1][i]))
2616                                                 {
2617                                                         dest->modes[strlen(dest->modes)+1]='\0';
2618                                                         dest->modes[strlen(dest->modes)] = parameters[1][i];
2619                                                         outpars[strlen(outpars)+1]='\0';
2620                                                         outpars[strlen(outpars)] = parameters[1][i];
2621                                                 }
2622                                         }
2623                                         else
2624                                         {
2625                                                 int q = 0;
2626                                                 char temp[MAXBUF];
2627                                                 char moo[MAXBUF];
2628
2629                                                 outpars[strlen(outpars)+1]='\0';
2630                                                 outpars[strlen(outpars)] = parameters[1][i];
2631                                                 
2632                                                 strcpy(temp,"");
2633                                                 for (q = 0; q < strlen(user->modes); q++)
2634                                                 {
2635                                                         if (user->modes[q] != parameters[1][i])
2636                                                         {
2637                                                                 moo[0] = user->modes[q];
2638                                                                 moo[1] = '\0';
2639                                                                 strcat(temp,moo);
2640                                                         }
2641                                                 }
2642                                                 strcpy(user->modes,temp);
2643                                         }
2644                                 }
2645                         }
2646                 }
2647                 if (strlen(outpars))
2648                 {
2649                         char b[MAXBUF];
2650                         strcpy(b,"");
2651                         int z = 0;
2652                         int i = 0;
2653                         while (i < strlen (outpars))
2654                         {
2655                                 b[z++] = outpars[i++];
2656                                 b[z] = '\0';
2657                                 if (i<strlen(outpars)-1)
2658                                 {
2659                                         if (((outpars[i] == '-') || (outpars[i] == '+')) && ((outpars[i+1] == '-') || (outpars[i+1] == '+')))
2660                                         {
2661                                                 // someones playing silly buggers and trying
2662                                                 // to put a +- or -+ into the line...
2663                                                 i++;
2664                                         }
2665                                 }
2666                                 if (i == strlen(outpars)-1)
2667                                 {
2668                                         if ((outpars[i] == '-') || (outpars[i] == '+'))
2669                                         {
2670                                                 i++;
2671                                         }
2672                                 }
2673                         }
2674
2675                         z = strlen(b)-1;
2676                         if ((b[z] == '-') || (b[z] == '+'))
2677                                 b[z] == '\0';
2678
2679                         if ((!strcmp(b,"+")) || (!strcmp(b,"-")))
2680                                 return;
2681
2682                         WriteTo(user, dest, "MODE %s :%s", dest->nick, b);
2683                 }
2684                 return;
2685         }
2686         
2687         Ptr = FindChan(parameters[0]);
2688         if (Ptr)
2689         {
2690                 process_modes(parameters,user,Ptr,STATUS_OP,pcnt,true);
2691         }
2692         else
2693         {
2694                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2695         }
2696 }
2697
2698
2699 /* This function pokes and hacks at a parameter list like the following:
2700  *
2701  * PART #winbot, #darkgalaxy :m00!
2702  *
2703  * to turn it into a series of individual calls like this:
2704  *
2705  * PART #winbot :m00!
2706  * PART #darkgalaxy :m00!
2707  *
2708  * The seperate calls are sent to a callback function provided by the caller
2709  * (the caller will usually call itself recursively). The callback function
2710  * must be a command handler. Calling this function on a line with no list causes
2711  * no action to be taken. You must provide a starting and ending parameter number
2712  * where the range of the list can be found, useful if you have a terminating
2713  * parameter as above which is actually not part of the list, or parameters
2714  * before the actual list as well. This code is used by many functions which
2715  * can function as "one to list" (see the RFC) */
2716
2717 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
2718 {
2719         char plist[MAXBUF];
2720         char *param;
2721         char *pars[32];
2722         char blog[32][MAXBUF];
2723         char blog2[32][MAXBUF];
2724         int i = 0, j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
2725         char keystr[MAXBUF];
2726         char moo[MAXBUF];
2727
2728         for (i = 0; i <32; i++)
2729                 strcpy(blog[i],"");
2730
2731         for (i = 0; i <32; i++)
2732                 strcpy(blog2[i],"");
2733
2734         strcpy(moo,"");
2735         for (i = 0; i <10; i++)
2736         {
2737                 if (!parameters[i])
2738                 {
2739                         parameters[i] = moo;
2740                 }
2741         }
2742         if (joins)
2743         {
2744                 if (pcnt > 1) /* we have a key to copy */
2745                 {
2746                         strcpy(keystr,parameters[1]);
2747                 }
2748         }
2749
2750         if (!parameters[start])
2751         {
2752                 return 0;
2753         }
2754         if (!strchr(parameters[start],','))
2755         {
2756                 return 0;
2757         }
2758         strcpy(plist,"");
2759         for (i = start; i <= end; i++)
2760         {
2761                 if (parameters[i])
2762                 {
2763                         strcat(plist,parameters[i]);
2764                 }
2765         }
2766         
2767         j = 0;
2768         param = plist;
2769
2770         t = strlen(plist);
2771         for (i = 0; i < t; i++)
2772         {
2773                 if (plist[i] == ',')
2774                 {
2775                         plist[i] = '\0';
2776                         strcpy(blog[j++],param);
2777                         param = plist+i+1;
2778                 }
2779         }
2780         strcpy(blog[j++],param);
2781         total = j;
2782
2783         if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
2784         {
2785                 strcat(keystr,",");
2786         }
2787         
2788         if ((joins) && (keystr))
2789         {
2790                 if (strchr(keystr,','))
2791                 {
2792                         j = 0;
2793                         param = keystr;
2794                         t2 = strlen(keystr);
2795                         for (i = 0; i < t2; i++)
2796                         {
2797                                 if (keystr[i] == ',')
2798                                 {
2799                                         keystr[i] = '\0';
2800                                         strcpy(blog2[j++],param);
2801                                         param = keystr+i+1;
2802                                 }
2803                         }
2804                         strcpy(blog2[j++],param);
2805                         total2 = j;
2806                 }
2807         }
2808
2809         for (j = 0; j < total; j++)
2810         {
2811                 if (blog[j])
2812                 {
2813                         pars[0] = blog[j];
2814                 }
2815                 for (q = end; q < pcnt-1; q++)
2816                 {
2817                         if (parameters[q+1])
2818                         {
2819                                 pars[q-end+1] = parameters[q+1];
2820                         }
2821                 }
2822                 if ((joins) && (parameters[1]))
2823                 {
2824                         if (pcnt > 1)
2825                         {
2826                                 pars[1] = blog2[j];
2827                         }
2828                         else
2829                         {
2830                                 pars[1] = NULL;
2831                         }
2832                 }
2833                 /* repeatedly call the function with the hacked parameter list */
2834                 if ((joins) && (pcnt > 1))
2835                 {
2836                         if (pars[1])
2837                         {
2838                                 // pars[1] already set up and containing key from blog2[j]
2839                                 fn(pars,2,u);
2840                         }
2841                         else
2842                         {
2843                                 pars[1] = parameters[1];
2844                                 fn(pars,2,u);
2845                         }
2846                 }
2847                 else
2848                 {
2849                         fn(pars,pcnt-(end-start),u);
2850                 }
2851         }
2852
2853         return 1;
2854 }
2855
2856
2857 void handle_join(char **parameters, int pcnt, userrec *user)
2858 {
2859         chanrec* Ptr;
2860         int i = 0;
2861         
2862         if (loop_call(handle_join,parameters,pcnt,user,0,0,1))
2863                 return;
2864         if (parameters[0][0] == '#')
2865         {
2866                 Ptr = add_channel(user,parameters[0],parameters[1]);
2867         }
2868 }
2869
2870
2871 void handle_part(char **parameters, int pcnt, userrec *user)
2872 {
2873         chanrec* Ptr;
2874
2875         if (pcnt > 1)
2876         {
2877                 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-2,0))
2878                         return;
2879                 del_channel(user,parameters[0],parameters[1]);
2880         }
2881         else
2882         {
2883                 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-1,0))
2884                         return;
2885                 del_channel(user,parameters[0],NULL);
2886         }
2887 }
2888
2889 void handle_kick(char **parameters, int pcnt, userrec *user)
2890 {
2891         chanrec* Ptr = FindChan(parameters[0]);
2892         userrec* u   = Find(parameters[1]);
2893
2894         if ((!u) || (!Ptr))
2895         {
2896                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
2897                 return;
2898         }
2899         
2900         if (!has_channel(u,Ptr))
2901         {
2902                 WriteServ(user->fd,"442 %s %s :You're not on that channel!",user->nick, parameters[0]);
2903                 return;
2904         }
2905         
2906         if (pcnt > 2)
2907         {
2908                 char reason[MAXBUF];
2909                 strncpy(reason,parameters[2],MAXBUF);
2910                 if (strlen(reason)>MAXKICK)
2911                 {
2912                         reason[MAXKICK-1] = '\0';
2913                 }
2914
2915                 kick_channel(user,u,Ptr,reason);
2916         }
2917         else
2918         {
2919                 kick_channel(user,u,Ptr,user->nick);
2920         }
2921 }
2922
2923
2924 void handle_die(char **parameters, int pcnt, userrec *user)
2925 {
2926         log(DEBUG,"die: %s",user->nick);
2927         if (!strcmp(parameters[0],diepass))
2928         {
2929                 WriteOpers("*** DIE command from %s!%s@%s, terminating...",user->nick,user->ident,user->host);
2930                 sleep(DieDelay);
2931                 Exit(ERROR);
2932         }
2933         else
2934         {
2935                 WriteOpers("*** Failed DIE Command from %s!%s@%s.",user->nick,user->ident,user->host);
2936         }
2937 }
2938
2939 void handle_restart(char **parameters, int pcnt, userrec *user)
2940 {
2941         log(DEBUG,"restart: %s",user->nick);
2942         if (!strcmp(parameters[0],restartpass))
2943         {
2944                 WriteOpers("*** RESTART command from %s!%s@%s, Pretending to restart till this is finished :D",user->nick,user->ident,user->host);
2945                 sleep(DieDelay);
2946                 Exit(ERROR);
2947                 /* Will finish this later when i can be arsed :) */
2948         }
2949         else
2950         {
2951                 WriteOpers("*** Failed RESTART Command from %s!%s@%s.",user->nick,user->ident,user->host);
2952         }
2953 }
2954
2955
2956 void kill_link(userrec *user,char* reason)
2957 {
2958         user_hash::iterator iter = clientlist.find(user->nick);
2959
2960         if (strlen(reason)>MAXQUIT)
2961         {
2962                 reason[MAXQUIT-1] = '\0';
2963         }
2964
2965         log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
2966         Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
2967         log(DEBUG,"closing fd %d",user->fd);
2968
2969         /* bugfix, cant close() a nonblocking socket (sux!) */
2970         if (user->registered == 7) {
2971                 FOREACH_MOD OnUserQuit(user);
2972                 WriteCommonExcept(user,"QUIT :%s",reason);
2973         }
2974
2975         /* push the socket on a stack of sockets due to be closed at the next opportunity */
2976         fd_reap.push_back(user->fd);
2977         
2978         bool do_purge = false;
2979         
2980         if (user->registered == 7) {
2981                 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
2982                 AddWhoWas(user);
2983         }
2984
2985         if (iter != clientlist.end())
2986         {
2987                 log(DEBUG,"deleting user hash value %d",iter->second);
2988                 if ((iter->second) && (user->registered == 7)) {
2989                         delete iter->second;
2990                 }
2991                 clientlist.erase(iter);
2992         }
2993
2994         if (user->registered == 7) {
2995                 purge_empty_chans();
2996         }
2997 }
2998
2999
3000 void handle_kill(char **parameters, int pcnt, userrec *user)
3001 {
3002         userrec *u = Find(parameters[0]);
3003         char killreason[MAXBUF];
3004         
3005         log(DEBUG,"kill: %s %s",parameters[0],parameters[1]);
3006         if (u)
3007         {
3008                 WriteTo(user, u, "KILL %s :%s!%s!%s (%s)", u->nick, ServerName,user->dhost,user->nick,parameters[1]);
3009                 // :Brain!brain@NetAdmin.chatspike.net KILL [Brain] :homer!NetAdmin.chatspike.net!Brain (test kill)
3010                 WriteOpers("*** Local Kill by %s: %s!%s@%s (%s)",user->nick,u->nick,u->ident,u->host,parameters[1]);
3011                 sprintf(killreason,"Killed (%s (%s))",user->nick,parameters[1]);
3012                 kill_link(u,killreason);
3013         }
3014         else
3015         {
3016                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3017         }
3018 }
3019
3020 void handle_summon(char **parameters, int pcnt, userrec *user)
3021 {
3022         WriteServ(user->fd,"445 %s :SUMMON has been disabled (depreciated command)",user->nick);
3023 }
3024
3025 void handle_users(char **parameters, int pcnt, userrec *user)
3026 {
3027         WriteServ(user->fd,"445 %s :USERS has been disabled (depreciated command)",user->nick);
3028 }
3029
3030
3031 // looks up a users password for their connection class (<ALLOW>/<DENY> tags)
3032
3033 char* Passwd(userrec *user)
3034 {
3035         for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
3036         {
3037                 if (match(user->host,i->host) && (i->type == CC_ALLOW))
3038                 {
3039                         return i->pass;
3040                 }
3041         }
3042         return "";
3043 }
3044
3045 bool IsDenied(userrec *user)
3046 {
3047         for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
3048         {
3049                 if (match(user->host,i->host) && (i->type == CC_DENY))
3050                 {
3051                         return true;
3052                 }
3053         }
3054         return false;
3055 }
3056
3057
3058 void handle_pass(char **parameters, int pcnt, userrec *user)
3059 {
3060         if (!strcasecmp(parameters[0],Passwd(user)))
3061         {
3062                 user->haspassed = true;
3063         }
3064 }
3065
3066 void handle_invite(char **parameters, int pcnt, userrec *user)
3067 {
3068         userrec* u = Find(parameters[0]);
3069         chanrec* c = FindChan(parameters[1]);
3070
3071         if ((!c) || (!u))
3072         {
3073                 if (!c)
3074                 {
3075                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[1]);
3076                 }
3077                 else
3078                 {
3079                         if (c->inviteonly)
3080                         {
3081                                 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[0]);
3082                         }
3083                 }
3084
3085                 return;
3086         }
3087
3088         if (c->inviteonly)
3089         {
3090                 if (cstatus(user,c) < STATUS_HOP)
3091                 {
3092                         WriteServ(user->fd,"482 %s %s :You must be at least a half-operator",user->nick, c->name);
3093                         return;
3094                 }
3095
3096                 u->InviteTo(c->name);
3097                 WriteFrom(u->fd,user,"INVITE %s :%s",u->nick,c->name);
3098                 WriteServ(user->fd,"341 %s %s %s",user->nick,u->nick,c->name);
3099         }
3100 }
3101
3102 void handle_topic(char **parameters, int pcnt, userrec *user)
3103 {
3104         chanrec* Ptr;
3105
3106         if (pcnt == 1)
3107         {
3108                 if (strlen(parameters[0]) <= CHANMAX)
3109                 {
3110                         Ptr = FindChan(parameters[0]);
3111                         if (Ptr)
3112                         {
3113                                 if (Ptr->topicset)
3114                                 {
3115                                         WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
3116                                         WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
3117                                 }
3118                                 else
3119                                 {
3120                                         WriteServ(user->fd,"331 %s %s :No topic is set.", user->nick, Ptr->name);
3121                                 }
3122                         }
3123                         else
3124                         {
3125                                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3126                         }
3127                 }
3128                 return;
3129         }
3130         else if (pcnt>1)
3131         {
3132                 if (strlen(parameters[0]) <= CHANMAX)
3133                 {
3134                         Ptr = FindChan(parameters[0]);
3135                         if (Ptr)
3136                         {
3137                                 if ((Ptr->topiclock) && (cstatus(user,Ptr)<STATUS_HOP))
3138                                 {
3139                                         WriteServ(user->fd,"482 %s %s :You must be at least a half-operator", user->nick, Ptr->name);
3140                                         return;
3141                                 }
3142                                 
3143                                 char topic[MAXBUF];
3144                                 strncpy(topic,parameters[1],MAXBUF);
3145                                 if (strlen(topic)>MAXTOPIC)
3146                                 {
3147                                         topic[MAXTOPIC-1] = '\0';
3148                                 }
3149                                         
3150                                 strcpy(Ptr->topic,topic);
3151                                 strcpy(Ptr->setby,user->nick);
3152                                 Ptr->topicset = time(NULL);
3153                                 WriteChannel(Ptr,user,"TOPIC %s :%s",Ptr->name, Ptr->topic);
3154                         }
3155                         else
3156                         {
3157                                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3158                         }
3159                 }
3160         }
3161 }
3162
3163 /* sends out an error notice to all connected clients (not to be used
3164  * lightly!) */
3165
3166 void send_error(char *s)
3167 {
3168         log(DEBUG,"send_error: %s",s);
3169         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3170         {
3171                 WriteServ(i->second->fd,"NOTICE %s :%s",i->second->nick,s);
3172         }
3173 }
3174
3175 void Error(int status)
3176 {
3177         signal (SIGALRM, SIG_IGN);
3178         signal (SIGPIPE, SIG_IGN);
3179         signal (SIGTERM, SIG_IGN);
3180         signal (SIGABRT, SIG_IGN);
3181         signal (SIGSEGV, SIG_IGN);
3182         signal (SIGURG, SIG_IGN);
3183         signal (SIGKILL, SIG_IGN);
3184         log(DEBUG,"*** fell down a pothole in the road to perfection ***");
3185         send_error("Error! Segmentation fault! save meeeeeeeeeeeeee *splat!*");
3186         exit(status);
3187 }
3188
3189 int main (int argc, char *argv[])
3190 {
3191         Start();
3192         log(DEBUG,"*** InspIRCd starting up!");
3193         if (!FileExists(CONFIG_FILE))
3194         {
3195                 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
3196                 log(DEBUG,"main: no config");
3197                 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
3198                 Exit(ERROR);
3199         }
3200         if (argc > 1) {
3201                 if (!strcmp(argv[1],"-nofork")) {
3202                         nofork = true;
3203                 }
3204         }
3205         if (InspIRCd() == ERROR)
3206         {
3207                 log(DEBUG,"main: daemon function bailed");
3208                 printf("ERROR: could not initialise. Shutting down.\n");
3209                 Exit(ERROR);
3210         }
3211         Exit(TRUE);
3212         return 0;
3213 }
3214
3215 template<typename T> inline string ConvToStr(const T &in)
3216 {
3217         stringstream tmp;
3218         if (!(tmp << in)) return string();
3219         return tmp.str();
3220 }
3221
3222 /* re-allocates a nick in the user_hash after they change nicknames,
3223  * returns a pointer to the new user as it may have moved */
3224
3225 userrec* ReHashNick(char* Old, char* New)
3226 {
3227         user_hash::iterator newnick;
3228         user_hash::iterator oldnick = clientlist.find(Old);
3229
3230         log(DEBUG,"ReHashNick: %s %s",Old,New);
3231         
3232         if (!strcasecmp(Old,New))
3233         {
3234                 log(DEBUG,"old nick is new nick, skipping");
3235                 return oldnick->second;
3236         }
3237         
3238         if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
3239
3240         log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
3241
3242         clientlist[New] = new userrec();
3243         clientlist[New] = oldnick->second;
3244         /*delete oldnick->second; */
3245         clientlist.erase(oldnick);
3246
3247         log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
3248         
3249         return clientlist[New];
3250 }
3251
3252 /* adds or updates an entry in the whowas list */
3253 void AddWhoWas(userrec* u)
3254 {
3255         user_hash::iterator iter = whowas.find(u->nick);
3256         userrec *a = new userrec();
3257         strcpy(a->nick,u->nick);
3258         strcpy(a->ident,u->ident);
3259         strcpy(a->dhost,u->dhost);
3260         strcpy(a->host,u->host);
3261         strcpy(a->fullname,u->fullname);
3262         strcpy(a->server,u->server);
3263         a->signon = u->signon;
3264
3265         /* MAX_WHOWAS:   max number of /WHOWAS items
3266          * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
3267          *               can be replaced by a newer one
3268          */
3269         
3270         if (iter == whowas.end())
3271         {
3272                 if (whowas.size() == WHOWAS_MAX)
3273                 {
3274                         for (user_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
3275                         {
3276                                 // 3600 seconds in an hour ;)
3277                                 if ((i->second->signon)<(time(NULL)-(WHOWAS_STALE*3600)))
3278                                 {
3279                                         delete i->second;
3280                                         i->second = a;
3281                                         log(DEBUG,"added WHOWAS entry, purged an old record");
3282                                         return;
3283                                 }
3284                         }
3285                 }
3286                 else
3287                 {
3288                         log(DEBUG,"added fresh WHOWAS entry");
3289                         whowas[a->nick] = a;
3290                 }
3291         }
3292         else
3293         {
3294                 log(DEBUG,"updated WHOWAS entry");
3295                 delete iter->second;
3296                 iter->second = a;
3297         }
3298 }
3299
3300
3301 /* add a client connection to the sockets list */
3302 void AddClient(int socket, char* host, int port, bool iscached)
3303 {
3304         int i;
3305         int blocking = 1;
3306         char resolved[MAXBUF];
3307         string tempnick;
3308         char tn2[MAXBUF];
3309         user_hash::iterator iter;
3310
3311         tempnick = ConvToStr(socket) + "-unknown";
3312         sprintf(tn2,"%d-unknown",socket);
3313
3314         iter = clientlist.find(tempnick);
3315
3316         if (iter != clientlist.end()) return;
3317
3318         /*
3319          * It is OK to access the value here this way since we know
3320          * it exists, we just created it above.
3321          *
3322          * At NO other time should you access a value in a map or a
3323          * hash_map this way.
3324          */
3325         clientlist[tempnick] = new userrec();
3326
3327         NonBlocking(socket);
3328         log(DEBUG,"AddClient: %d %s %d",socket,host,port);
3329
3330
3331         clientlist[tempnick]->fd = socket;
3332         strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
3333         strncpy(clientlist[tempnick]->host, host,160);
3334         strncpy(clientlist[tempnick]->dhost, host,160);
3335         strncpy(clientlist[tempnick]->server, ServerName,256);
3336         clientlist[tempnick]->registered = 0;
3337         clientlist[tempnick]->signon = time(NULL);
3338         clientlist[tempnick]->nping = time(NULL)+240;
3339         clientlist[tempnick]->lastping = 1;
3340         clientlist[tempnick]->port = port;
3341
3342         if (iscached)
3343         {
3344                 WriteServ(socket,"NOTICE Auth :Found your hostname (cached)...");
3345         }
3346         else
3347         {
3348                 WriteServ(socket,"NOTICE Auth :Looking up your hostname...");
3349         }
3350
3351         if (clientlist.size() == MAXCLIENTS)
3352                 kill_link(clientlist[tempnick],"No more connections allowed in this class");
3353 }
3354
3355 void handle_names(char **parameters, int pcnt, userrec *user)
3356 {
3357         chanrec* c;
3358
3359         if (loop_call(handle_names,parameters,pcnt,user,0,pcnt-1,0))
3360                 return;
3361         c = FindChan(parameters[0]);
3362         if (c)
3363         {
3364                 /*WriteServ(user->fd,"353 %s = %s :%s", user->nick, c->name,*/
3365                 userlist(user,c);
3366                 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, c->name);
3367         }
3368         else
3369         {
3370                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3371         }
3372 }
3373
3374
3375 void handle_privmsg(char **parameters, int pcnt, userrec *user)
3376 {
3377         userrec *dest;
3378         chanrec *chan;
3379         
3380         if (loop_call(handle_privmsg,parameters,pcnt,user,0,pcnt-2,0))
3381                 return;
3382         if (parameters[0][0] == '#')
3383         {
3384                 chan = FindChan(parameters[0]);
3385                 if (chan)
3386                 {
3387                         if ((chan->noexternal) && (!has_channel(user,chan)))
3388                         {
3389                                 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
3390                                 return;
3391                         }
3392                         if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
3393                         {
3394                                 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
3395                                 return;
3396                         }
3397                         ChanExceptSender(chan, user, "PRIVMSG %s :%s", chan->name, parameters[1]);
3398                 }
3399                 else
3400                 {
3401                         /* no such nick/channel */
3402                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3403                 }
3404                 return;
3405         }
3406         
3407         dest = Find(parameters[0]);
3408         if (dest)
3409         {
3410                 if (strcmp(dest->awaymsg,""))
3411                 {
3412                         /* auto respond with aweh msg */
3413                         WriteServ(user->fd,"301 %s %s :%s",user->nick,dest->nick,dest->awaymsg);
3414                 }
3415                 WriteTo(user, dest, "PRIVMSG %s :%s", dest->nick, parameters[1]);
3416         }
3417         else
3418         {
3419                 /* no such nick/channel */
3420                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3421         }
3422 }
3423
3424 void handle_notice(char **parameters, int pcnt, userrec *user)
3425 {
3426         userrec *dest;
3427         chanrec *chan;
3428
3429         if (loop_call(handle_notice,parameters,pcnt,user,0,pcnt-2,0))
3430                 return;
3431         if (parameters[0][0] == '#')
3432         {
3433                 chan = FindChan(parameters[0]);
3434                 if (chan)
3435                 {
3436                         if ((chan->noexternal) && (!has_channel(user,chan)))
3437                         {
3438                                 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
3439                                 return;
3440                         }
3441                         if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
3442                         {
3443                                 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
3444                                 return;
3445                         }
3446                         WriteChannel(chan, user, "NOTICE %s :%s", chan->name, parameters[1]);
3447                 }
3448                 else
3449                 {
3450                         /* no such nick/channel */
3451                         WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3452                 }
3453                 return;
3454         }
3455         
3456         dest = Find(parameters[0]);
3457         if (dest)
3458         {
3459                 WriteTo(user, dest, "NOTICE %s :%s", dest->nick, parameters[1]);
3460         }
3461         else
3462         {
3463                 /* no such nick/channel */
3464                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3465         }
3466 }
3467
3468 char lst[MAXBUF];
3469
3470 char* chlist(userrec *user)
3471 {
3472         int i = 0;
3473         char cmp[MAXBUF];
3474
3475         log(DEBUG,"chlist: %s",user->nick);
3476         strcpy(lst,"");
3477         if (!user)
3478         {
3479                 return lst;
3480         }
3481         for (i = 0; i != MAXCHANS; i++)
3482         {
3483                 if (user->chans[i].channel != NULL)
3484                 {
3485                         if (user->chans[i].channel->name)
3486                         {
3487                                 strcpy(cmp,user->chans[i].channel->name);
3488                                 strcat(cmp," ");
3489                                 if (!strstr(lst,cmp))
3490                                 {
3491                                         if ((!user->chans[i].channel->c_private) && (!user->chans[i].channel->secret))
3492                                         {
3493                                                 strcat(lst,cmode(user,user->chans[i].channel));
3494                                                 strcat(lst,user->chans[i].channel->name);
3495                                                 strcat(lst," ");
3496                                         }
3497                                 }
3498                         }
3499                 }
3500         }
3501         return lst;
3502 }
3503
3504 void handle_info(char **parameters, int pcnt, userrec *user)
3505 {
3506         WriteServ(user->fd,"371 %s :The Inspire IRCd Project Has been brought to you by the following people..",user->nick);
3507         WriteServ(user->fd,"371 %s :Craig Edwards, Craig McLure, and Others..",user->nick);
3508         WriteServ(user->fd,"371 %s :Will finish this later when i can be arsed :p",user->nick);
3509         WriteServ(user->fd,"374 %s :End of /INFO list",user->nick);
3510 }
3511
3512 void handle_time(char **parameters, int pcnt, userrec *user)
3513 {
3514         time_t rawtime;
3515         struct tm * timeinfo;
3516
3517         time ( &rawtime );
3518         timeinfo = localtime ( &rawtime );
3519         WriteServ(user->fd,"391 %s %s :%s",user->nick,ServerName, asctime (timeinfo) );
3520   
3521 }
3522
3523 void handle_whois(char **parameters, int pcnt, userrec *user)
3524 {
3525         userrec *dest;
3526         char *t;
3527
3528         if (loop_call(handle_whois,parameters,pcnt,user,0,pcnt-1,0))
3529                 return;
3530         dest = Find(parameters[0]);
3531         if (dest)
3532         {
3533                 WriteServ(user->fd,"311 %s %s %s %s * :%s",user->nick, dest->nick, dest->ident, dest->dhost, dest->fullname);
3534                 if ((user == dest) || (strchr(user->modes,'o')))
3535                 {
3536                         WriteServ(user->fd,"378 %s %s :is connecting from *@%s",user->nick, dest->nick, dest->host);
3537                 }
3538                 if (strcmp(chlist(dest),""))
3539                 {
3540                         WriteServ(user->fd,"319 %s %s :%s",user->nick, dest->nick, chlist(dest));
3541                 }
3542                 WriteServ(user->fd,"312 %s %s %s :%s",user->nick, dest->nick, dest->server, ServerDesc);
3543                 if (strcmp(dest->awaymsg,""))
3544                 {
3545                         WriteServ(user->fd,"301 %s %s :%s",user->nick, dest->nick, dest->awaymsg);
3546                 }
3547                 if (strchr(dest->modes,'o'))
3548                 {
3549                         WriteServ(user->fd,"313 %s %s :is an IRC operator",user->nick, dest->nick);
3550                 }
3551                 //WriteServ(user->fd,"310 %s %s :is available for help.",user->nick, dest->nick);
3552                 WriteServ(user->fd,"317 %s %s %d %d :seconds idle, signon time",user->nick, dest->nick, abs((dest->idle_lastmsg)-time(NULL)), dest->signon);
3553                 
3554                 WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, dest->nick);
3555         }
3556         else
3557         {
3558                 /* no such nick/channel */
3559                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3560         }
3561 }
3562
3563 void handle_quit(char **parameters, int pcnt, userrec *user)
3564 {
3565         user_hash::iterator iter = clientlist.find(user->nick);
3566         char* reason;
3567
3568         if (user->registered == 7)
3569         {
3570                 /* theres more to do here, but for now just close the socket */
3571                 if (pcnt == 1)
3572                 {
3573                         if (parameters[0][0] == ':')
3574                         {
3575                                 *parameters[0]++;
3576                         }
3577                         reason = parameters[0];
3578
3579                         if (strlen(reason)>MAXQUIT)
3580                         {
3581                                 reason[MAXQUIT-1] = '\0';
3582                         }
3583
3584                         Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,parameters[0]);
3585                         WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,parameters[0]);
3586                         WriteCommonExcept(user,"QUIT :%s%s",PrefixQuit,parameters[0]);
3587                 }
3588                 else
3589                 {
3590                         Write(user->fd,"ERROR :Closing link (%s@%s) [QUIT]",user->ident,user->host);
3591                         WriteOpers("*** Client exiting: %s!%s@%s [Client exited]",user->nick,user->ident,user->host);
3592                         WriteCommonExcept(user,"QUIT :Client exited");
3593                 }
3594                 FOREACH_MOD OnUserQuit(user);
3595                 AddWhoWas(user);
3596         }
3597
3598         /* push the socket on a stack of sockets due to be closed at the next opportunity */
3599         fd_reap.push_back(user->fd);
3600         
3601         if (iter != clientlist.end())
3602         {
3603                 log(DEBUG,"deleting user hash value %d",iter->second);
3604                 if ((iter->second) && (user->registered == 7)) {
3605                         delete iter->second;
3606                 }
3607                 clientlist.erase(iter);
3608         }
3609
3610         if (user->registered == 7) {
3611                 purge_empty_chans();
3612         }
3613 }
3614
3615 void handle_who(char **parameters, int pcnt, userrec *user)
3616 {
3617         chanrec* Ptr = NULL;
3618         
3619         /* theres more to do here, but for now just close the socket */
3620         if (pcnt == 1)
3621         {
3622                 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")))
3623                 {
3624                         if (user->chans[0].channel)
3625                         {
3626                                 Ptr = user->chans[0].channel;
3627                                 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3628                                 {
3629                                         if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
3630                                         {
3631                                                 WriteServ(user->fd,"352 %s %s %s %s %s %s Hr@ :0 %s",user->nick, Ptr->name, i->second->ident, i->second->dhost, ServerName, i->second->nick, i->second->fullname);
3632                                         }
3633                                 }
3634                         }
3635                         if (Ptr)
3636                         {
3637                                 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
3638                         }
3639                         else
3640                         {
3641                                 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, user->nick);
3642                         }
3643                         return;
3644                 }
3645                 if (parameters[0][0] = '#')
3646                 {
3647                         Ptr = FindChan(parameters[0]);
3648                         if (Ptr)
3649                         {
3650                                 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3651                                 {
3652                                         if ((has_channel(i->second,Ptr)) && (isnick(i->second->nick)))
3653                                         {
3654                                                 WriteServ(user->fd,"352 %s %s %s %s %s %s Hr@ :0 %s",user->nick, Ptr->name, i->second->ident, i->second->dhost, ServerName, i->second->nick, i->second->fullname);
3655                                         }
3656                                 }
3657                                 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
3658                         }
3659                         else
3660                         {
3661                                 WriteServ(user->fd,"401 %s %s :No suck nick/channel",user->nick, parameters[0]);
3662                         }
3663                 }
3664         }
3665         if (pcnt == 2)
3666         {
3667                 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")) && (!strcmp(parameters[1],"o")))
3668                 {
3669                         Ptr = user->chans[0].channel;
3670                         printf(user->chans[0].channel->name);
3671                         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3672                         {
3673                                 if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
3674                                 {
3675                                         if (strchr(i->second->modes,'o'))
3676                                         {
3677                                                 WriteServ(user->fd,"352 %s %s %s %s %s %s Hr@ :0 %s",user->nick, Ptr->name, i->second->ident, i->second->dhost, ServerName, i->second->nick, i->second->fullname);
3678                                         }
3679                                 }
3680                         }
3681                         WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, Ptr->name);
3682                         return;
3683                 }
3684         }
3685 }
3686
3687 void handle_wallops(char **parameters, int pcnt, userrec *user)
3688 {
3689         WriteWallOps(user,"%s",parameters[0]);
3690 }
3691
3692 void handle_list(char **parameters, int pcnt, userrec *user)
3693 {
3694         chanrec* Ptr;
3695         
3696         WriteServ(user->fd,"321 %s Channel :Users Name",user->nick);
3697         for (chan_hash::const_iterator i = chanlist.begin(); i != chanlist.end(); i++)
3698         {
3699                 if ((!i->second->c_private) && (!i->second->secret))
3700                 {
3701                         WriteServ(user->fd,"322 %s %s %d :[+%s] %s",user->nick,i->second->name,usercount_i(i->second),chanmodes(i->second),i->second->topic);
3702                 }
3703         }
3704         WriteServ(user->fd,"323 %s :End of channel list.",user->nick);
3705 }
3706
3707
3708 void handle_rehash(char **parameters, int pcnt, userrec *user)
3709 {
3710         WriteServ(user->fd,"382 %s %s :Rehashing",user->nick,CONFIG_FILE);
3711         ReadConfig();
3712         FOREACH_MOD OnRehash();
3713         WriteOpers("%s is rehashing config file %s",user->nick,CONFIG_FILE);
3714 }
3715
3716
3717 int usercnt(void)
3718 {
3719         return clientlist.size();
3720 }
3721
3722 int usercount_invisible(void)
3723 {
3724         int c = 0;
3725
3726         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3727         {
3728                 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'i'))) c++;
3729         }
3730         return c;
3731 }
3732
3733 int usercount_opers(void)
3734 {
3735         int c = 0;
3736
3737         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3738         {
3739                 if ((i->second->fd) && (isnick(i->second->nick)) && (strchr(i->second->modes,'o'))) c++;
3740         }
3741         return c;
3742 }
3743
3744 int usercount_unknown(void)
3745 {
3746         int c = 0;
3747
3748         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
3749         {
3750                 if ((i->second->fd) && (i->second->registered != 7))
3751                         c++;
3752         }
3753         return c;
3754 }
3755
3756 int chancount(void)
3757 {
3758         return chanlist.size();
3759 }
3760
3761 int servercount(void)
3762 {
3763         return 1;
3764 }
3765
3766 void handle_lusers(char **parameters, int pcnt, userrec *user)
3767 {
3768         WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),servercount());
3769         WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
3770         WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
3771         WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
3772         WriteServ(user->fd,"254 %s :I have %d clients and 0 servers",user->nick,usercnt());
3773 }
3774
3775 void handle_admin(char **parameters, int pcnt, userrec *user)
3776 {
3777         WriteServ(user->fd,"256 %s :Administrative info for %s",user->nick,ServerName);
3778         WriteServ(user->fd,"257 %s :Name     - %s",user->nick,AdminName);
3779         WriteServ(user->fd,"258 %s :Nickname - %s",user->nick,AdminNick);
3780         WriteServ(user->fd,"258 %s :E-Mail   - %s",user->nick,AdminEmail);
3781 }
3782
3783 void ShowMOTD(userrec *user)
3784 {
3785         if (!MOTD.size())
3786         {
3787                 WriteServ(user->fd,"422 %s :Message of the day file is missing.",user->nick);
3788                 return;
3789         }
3790         WriteServ(user->fd,"375 %s :- %s message of the day",user->nick,ServerName);
3791         for (int i = 0; i != MOTD.size(); i++)
3792         {
3793                                 WriteServ(user->fd,"372 %s :- %s",user->nick,MOTD[i].c_str());
3794         }
3795         WriteServ(user->fd,"376 %s :End of %s message of the day.",user->nick,ServerName);
3796 }
3797
3798 void ShowRULES(userrec *user)
3799 {
3800         if (!RULES.size())
3801         {
3802                 WriteServ(user->fd,"NOTICE %s :Rules file is missing.",user->nick);
3803                 return;
3804         }
3805         WriteServ(user->fd,"NOTICE %s :%s rules",user->nick,ServerName);
3806         for (int i = 0; i != RULES.size(); i++)
3807         {
3808                                 WriteServ(user->fd,"NOTICE %s :%s",user->nick,RULES[i].c_str());
3809         }
3810         WriteServ(user->fd,"NOTICE %s :End of %s rules.",user->nick,ServerName);
3811 }
3812
3813 /* shows the message of the day, and any other on-logon stuff */
3814 void ConnectUser(userrec *user)
3815 {
3816         user->registered = 7;
3817         user->idle_lastmsg = time(NULL);
3818         log(DEBUG,"ConnectUser: %s",user->nick);
3819
3820         if (strcmp(Passwd(user),"") && (!user->haspassed))
3821         {
3822                 Write(user->fd,"ERROR :Closing link: Invalid password");
3823                 kill_link(user,"Invalid password");
3824                 return;
3825         }
3826         if (IsDenied(user))
3827         {
3828                 Write(user->fd,"ERROR :Closing link: Unauthorized connection");
3829                 kill_link(user,"Unauthorised connection");
3830         }
3831
3832         WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
3833         WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
3834         WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
3835         WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
3836         WriteServ(user->fd,"004 %s :%s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
3837         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);
3838         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);
3839         ShowMOTD(user);
3840         FOREACH_MOD OnUserConnect(user);
3841         WriteOpers("*** Client connecting on port %d: %s!%s@%s",user->port,user->nick,user->ident,user->host);
3842 }
3843
3844 void handle_version(char **parameters, int pcnt, userrec *user)
3845 {
3846         WriteServ(user->fd,"351 %s :%s %s %s :%s",user->nick,VERSION,"$Id$",ServerName,SYSTEM);
3847 }
3848
3849 void handle_ping(char **parameters, int pcnt, userrec *user)
3850 {
3851         WriteServ(user->fd,"PONG %s :%s",ServerName,parameters[0]);
3852 }
3853
3854 void handle_pong(char **parameters, int pcnt, userrec *user)
3855 {
3856         // set the user as alive so they survive to next ping
3857         user->lastping = 1;
3858 }
3859
3860 void handle_motd(char **parameters, int pcnt, userrec *user)
3861 {
3862         ShowMOTD(user);
3863 }
3864
3865 void handle_rules(char **parameters, int pcnt, userrec *user)
3866 {
3867         ShowRULES(user);
3868 }
3869
3870 void handle_user(char **parameters, int pcnt, userrec *user)
3871 {
3872         if (user->registered < 3)
3873         {
3874                 if (isident(parameters[0]) == 0) {
3875                         // This kinda Sucks, According to the RFC thou, its either this,
3876                         // or "You have already registered" :p -- Craig
3877                         WriteServ(user->fd,"461 %s USER :Not enough parameters",user->nick);
3878                 }
3879                 else {
3880                         WriteServ(user->fd,"NOTICE Auth :No ident response, ident prefixed with ~");
3881                         strcpy(user->ident,"~"); /* we arent checking ident... but these days why bother anyway? */
3882                         strncat(user->ident,parameters[0],IDENTMAX);
3883                         strncpy(user->fullname,parameters[3],128);
3884                         user->registered = (user->registered | 1);
3885                 }
3886         }
3887         else
3888         {
3889                 WriteServ(user->fd,"462 %s :You may not reregister",user->nick);
3890                 return;
3891         }
3892         /* parameters 2 and 3 are local and remote hosts, ignored when sent by client connection */
3893         if (user->registered == 3)
3894         {
3895                 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
3896                 ConnectUser(user);
3897         }
3898 }
3899
3900 void handle_userhost(char **parameters, int pcnt, userrec *user)
3901 {
3902         char Return[MAXBUF],junk[MAXBUF];
3903         sprintf(Return,"302 %s :",user->nick);
3904         for (int i = 0; i < pcnt; i++)
3905         {
3906                 userrec *u = Find(parameters[i]);
3907                 if (u)
3908                 {
3909                         if (strchr(u->modes,'o'))
3910                         {
3911                                 sprintf(junk,"%s*=+%s@%s ",u->nick,u->ident,u->host);
3912                                 strcat(Return,junk);
3913                         }
3914                         else
3915                         {
3916                                 sprintf(junk,"%s=+%s@%s ",u->nick,u->ident,u->host);
3917                                 strcat(Return,junk);
3918                         }
3919                 }
3920         }
3921         WriteServ(user->fd,Return);
3922 }
3923
3924
3925 void handle_ison(char **parameters, int pcnt, userrec *user)
3926 {
3927         char Return[MAXBUF];
3928         sprintf(Return,"303 %s :",user->nick);
3929         for (int i = 0; i < pcnt; i++)
3930         {
3931                 userrec *u = Find(parameters[i]);
3932                 if (u)
3933                 {
3934                         strcat(Return,u->nick);
3935                         strcat(Return," ");
3936                 }
3937         }
3938         WriteServ(user->fd,Return);
3939 }
3940
3941
3942 void handle_away(char **parameters, int pcnt, userrec *user)
3943 {
3944         if (pcnt)
3945         {
3946                 strcpy(user->awaymsg,parameters[0]);
3947                 WriteServ(user->fd,"306 %s :You have been marked as being away",user->nick);
3948         }
3949         else
3950         {
3951                 strcpy(user->awaymsg,"");
3952                 WriteServ(user->fd,"305 %s :You are no longer marked as being away",user->nick);
3953         }
3954 }
3955
3956 void handle_whowas(char **parameters, int pcnt, userrec* user)
3957 {
3958         user_hash::iterator i = whowas.find(parameters[0]);
3959
3960         if (i == whowas.end())
3961         {
3962                 WriteServ(user->fd,"406 %s %s :There was no such nickname",user->nick,parameters[0]);
3963                 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
3964         }
3965         else
3966         {
3967                 time_t rawtime = i->second->signon;
3968                 tm *timeinfo;
3969                 char b[MAXBUF];
3970                 
3971                 timeinfo = localtime(&rawtime);
3972                 strcpy(b,asctime(timeinfo));
3973                 b[strlen(b)-1] = '\0';
3974                 
3975                 WriteServ(user->fd,"314 %s %s %s %s * :%s",user->nick,i->second->nick,i->second->ident,i->second->dhost,i->second->fullname);
3976                 WriteServ(user->fd,"312 %s %s %s :%s",user->nick,i->second->nick,i->second->server,b);
3977                 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
3978         }
3979
3980 }
3981
3982 void handle_trace(char **parameters, int pcnt, userrec *user)
3983 {
3984         for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
3985         {
3986                 if (i->second)
3987                 {
3988                         if (isnick(i->second->nick))
3989                         {
3990                                 if (strchr(i->second->modes,'o'))
3991                                 {
3992                                         WriteServ(user->fd,"205 %s :Oper 0 %s",user->nick,i->second->nick);
3993                                 }
3994                                 else
3995                                 {
3996                                         WriteServ(user->fd,"204 %s :User 0 %s",user->nick,i->second->nick);
3997                                 }
3998                         }
3999                         else
4000                         {
4001                                 WriteServ(user->fd,"203 %s :???? 0 [%s]",user->nick,i->second->host);
4002                         }
4003                 }
4004         }
4005 }
4006
4007 void handle_modules(char **parameters, int pcnt, userrec *user)
4008 {
4009         for (int i = 0; i < module_names.size(); i++)
4010         {
4011                         Version V = modules[i]->GetVersion();
4012                         WriteServ(user->fd,"900 0x%08lx %d.%d.%d.%d :%s",modules[i],V.Major,V.Minor,V.Revision,V.Build,module_names[i].c_str());
4013         }
4014 }
4015
4016 void handle_stats(char **parameters, int pcnt, userrec *user)
4017 {
4018         if (pcnt != 1)
4019         {
4020                 return;
4021         }
4022         if (strlen(parameters[0])>1)
4023         {
4024                 /* make the stats query 1 character long */
4025                 parameters[0][1] = '\0';
4026         }
4027
4028         /* stats m (list number of times each command has been used, plus bytecount) */
4029         if (!strcasecmp(parameters[0],"m"))
4030         {
4031                 for (int i = 0; i < cmdlist.size(); i++)
4032                 {
4033                         if (cmdlist[i].handler_function)
4034                         {
4035                                 if (cmdlist[i].use_count)
4036                                 {
4037                                         /* RPL_STATSCOMMANDS */
4038                                         WriteServ(user->fd,"212 %s %s %d %d",user->nick,cmdlist[i].command,cmdlist[i].use_count,cmdlist[i].total_bytes);
4039                                 }
4040                         }
4041                 }
4042                         
4043         }
4044
4045         /* stats z (debug and memory info) */
4046         if (!strcasecmp(parameters[0],"z"))
4047         {
4048                 WriteServ(user->fd,"249 %s :Users(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,clientlist.size(),clientlist.size()*sizeof(userrec),clientlist.bucket_count());
4049                 WriteServ(user->fd,"249 %s :Channels(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,chanlist.size(),chanlist.size()*sizeof(chanrec),chanlist.bucket_count());
4050                 WriteServ(user->fd,"249 %s :Commands(VECTOR) %d (%d bytes)",user->nick,cmdlist.size(),cmdlist.size()*sizeof(command_t));
4051                 WriteServ(user->fd,"249 %s :MOTD(VECTOR) %d, RULES(VECTOR) %d",user->nick,MOTD.size(),RULES.size());
4052                 WriteServ(user->fd,"249 %s :address_cache(HASH_MAP) %d (%d buckets)",user->nick,IP.size(),IP.bucket_count());
4053                 WriteServ(user->fd,"249 %s :Modules(VECTOR) %d (%d)",user->nick,modules.size(),modules.size()*sizeof(Module));
4054                 WriteServ(user->fd,"249 %s :ClassFactories(VECTOR) %d (%d)",user->nick,factory.size(),factory.size()*sizeof(ircd_module));
4055                 WriteServ(user->fd,"249 %s :Ports(STATIC_ARRAY) %d",user->nick,boundPortCount);
4056         }
4057         
4058         /* stats o */
4059         if (!strcasecmp(parameters[0],"o"))
4060         {
4061                 for (int i = 0; i < ConfValueEnum("oper"); i++)
4062                 {
4063                         char LoginName[MAXBUF];
4064                         char HostName[MAXBUF];
4065                         char OperType[MAXBUF];
4066                         ConfValue("oper","name",i,LoginName);
4067                         ConfValue("oper","host",i,HostName);
4068                         ConfValue("oper","type",i,OperType);
4069                         WriteServ(user->fd,"243 %s O %s * %s %s 0",user->nick,HostName,LoginName,OperType);
4070                 }
4071         }
4072         
4073         /* stats l (show user I/O stats) */
4074         if (!strcasecmp(parameters[0],"l"))
4075         {
4076                 WriteServ(user->fd,"211 %s :server:port nick bytes_in cmds_in bytes_out cmds_out",user->nick);
4077                 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
4078                 {
4079                         if (isnick(i->second->nick))
4080                         {
4081                                 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);
4082                         }
4083                         else
4084                         {
4085                                 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);
4086                         }
4087                         
4088                 }
4089         }
4090         
4091         /* stats u (show server uptime) */
4092         if (!strcasecmp(parameters[0],"u"))
4093         {
4094                 time_t current_time = 0;
4095                 current_time = time(NULL);
4096                 time_t server_uptime = current_time - startup_time;
4097                 struct tm* stime;
4098                 stime = gmtime(&server_uptime);
4099                 /* i dont know who the hell would have an ircd running for over a year nonstop, but
4100                  * Craig suggested this, and it seemed a good idea so in it went */
4101                 if (stime->tm_year > 70)
4102                 {
4103                         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);
4104                 }
4105                 else
4106                 {
4107                         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);
4108                 }
4109         }
4110
4111         WriteServ(user->fd,"219 %s %s :End of /STATS report",user->nick,parameters[0]);
4112         WriteOpers("*** Notice: Stats '%s' requested by %s (%s@%s)",parameters[0],user->nick,user->ident,user->host);
4113         
4114 }
4115
4116 void handle_connect(char **parameters, int pcnt, userrec *user)
4117 {
4118         char Link_ServerName[1024];
4119         char Link_IPAddr[1024];
4120         char Link_Port[1024];
4121         char Link_Pass[1024];
4122         int LinkPort;
4123         bool found = false;
4124         
4125         for (int i = 0; i < ConfValueEnum("link"); i++)
4126         {
4127                 ConfValue("link","name",i,Link_ServerName);
4128                 ConfValue("link","ipaddr",i,Link_IPAddr);
4129                 ConfValue("link","port",i,Link_Port);
4130                 ConfValue("link","sendpass",i,Link_Pass);
4131                 log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
4132                 LinkPort = atoi(Link_Port);
4133                 if (match(Link_ServerName,parameters[0])) {
4134                         found = true;
4135                 }
4136         }
4137         
4138         if (!found) {
4139                 WriteServ(user->fd,"NOTICE %s :*** Failed to connect to %s: No servers matching this pattern are configured for linking.",user->nick,parameters[0]);
4140                 return;
4141         }
4142         
4143         // TODO: Perform a check here to stop a server being linked twice!
4144
4145         WriteServ(user->fd,"NOTICE %s :*** Connecting to %s (%s) port %s...",user->nick,Link_ServerName,Link_IPAddr,Link_Port);
4146
4147         if (me[defaultRoute])
4148         {
4149
4150                 // at this point parameters[0] is an ip in a string.
4151                 // TODO: Look this up from the <link> blocks instead!
4152                 for (int j = 0; j < 255; j++) {
4153                         if (servers[j] == NULL) {
4154                                 servers[j] = new serverrec;
4155                                 strcpy(servers[j]->internal_addr,Link_IPAddr);
4156                                 strcpy(servers[j]->name,Link_ServerName);
4157                                 log(DEBUG,"Allocated new serverrec");
4158                                 if (!me[defaultRoute]->BeginLink(Link_IPAddr,LinkPort,Link_Pass))
4159                                 {
4160                                         WriteServ(user->fd,"NOTICE %s :*** Failed to send auth packet to %s!",user->nick,Link_IPAddr);
4161                                 }
4162                                 return;
4163                         }
4164                 }
4165                 WriteServ(user->fd,"NOTICE %s :*** Failed to create server record for address %s!",user->nick,Link_IPAddr);
4166         }
4167         else
4168         {
4169                 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);
4170         }
4171 }
4172
4173 void handle_squit(char **parameters, int pcnt, userrec *user)
4174 {
4175         // send out an squit across the mesh and then clear the server list (for local squit)
4176 }
4177
4178 void handle_oper(char **parameters, int pcnt, userrec *user)
4179 {
4180         char LoginName[MAXBUF];
4181         char Password[MAXBUF];
4182         char OperType[MAXBUF];
4183         char TypeName[MAXBUF];
4184         char Hostname[MAXBUF];
4185         int i,j;
4186
4187         for (i = 0; i < ConfValueEnum("oper"); i++)
4188         {
4189                 ConfValue("oper","name",i,LoginName);
4190                 ConfValue("oper","password",i,Password);
4191                 if ((!strcmp(LoginName,parameters[0])) && (!strcmp(Password,parameters[1])))
4192                 {
4193                         /* correct oper credentials */
4194                         ConfValue("oper","type",i,OperType);
4195                         WriteOpers("*** %s (%s@%s) is now an IRC operator of type %s",user->nick,user->ident,user->host,OperType);
4196                         WriteServ(user->fd,"381 %s :You are now an IRC operator of type %s",user->nick,OperType);
4197                         WriteServ(user->fd,"MODE %s :+o",user->nick);
4198                         for (j =0; j < ConfValueEnum("type"); j++)
4199                         {
4200                                 ConfValue("type","name",j,TypeName);
4201                                 if (!strcmp(TypeName,OperType))
4202                                 {
4203                                         /* found this oper's opertype */
4204                                         ConfValue("type","host",j,Hostname);
4205                                         strncpy(user->dhost,Hostname,256);
4206                                 }
4207                         }
4208                         if (!strchr(user->modes,'o'))
4209                         {
4210                                 strcat(user->modes,"o");
4211                         }
4212                         return;
4213                 }
4214         }
4215         /* no such oper */
4216         WriteServ(user->fd,"491 %s :Invalid oper credentials",user->nick);
4217         WriteOpers("*** WARNING! Failed oper attempt by %s!%s@%s!",user->nick,user->ident,user->host);
4218 }
4219                                 
4220 void handle_nick(char **parameters, int pcnt, userrec *user)
4221 {
4222         if (pcnt < 1) 
4223         {
4224                 log(DEBUG,"not enough params for handle_nick");
4225                 return;
4226         }
4227         if (!parameters[0])
4228         {
4229                 log(DEBUG,"invalid parameter passed to handle_nick");
4230                 return;
4231         }
4232         if (!strlen(parameters[0]))
4233         {
4234                 log(DEBUG,"zero length new nick passed to handle_nick");
4235                 return;
4236         }
4237         if (!user)
4238         {
4239                 log(DEBUG,"invalid user passed to handle_nick");
4240                 return;
4241         }
4242         if (!user->nick)
4243         {
4244                 log(DEBUG,"invalid old nick passed to handle_nick");
4245                 return;
4246         }
4247         if (!strcasecmp(user->nick,parameters[0]))
4248         {
4249                 log(DEBUG,"old nick is new nick, skipping");
4250                 return;
4251         }
4252         else
4253         {
4254                 if (strlen(parameters[0]) > 1)
4255                 {
4256                         if (parameters[0][0] == ':')
4257                         {
4258                                 *parameters[0]++;
4259                         }
4260                 }
4261                 if ((Find(parameters[0])) && (Find(parameters[0]) != user))
4262                 {
4263                         WriteServ(user->fd,"433 %s %s :Nickname is already in use.",user->nick,parameters[0]);
4264                         return;
4265                 }
4266         }
4267         if (isnick(parameters[0]) == 0)
4268         {
4269                 WriteServ(user->fd,"432 %s %s :Erroneous Nickname",user->nick,parameters[0]);
4270                 return;
4271         }
4272
4273         if (user->registered == 7)
4274         {
4275                 WriteCommon(user,"NICK %s",parameters[0]);
4276         }
4277         
4278         /* change the nick of the user in the users_hash */
4279         user = ReHashNick(user->nick, parameters[0]);
4280         /* actually change the nick within the record */
4281         if (!user) return;
4282         if (!user->nick) return;
4283
4284         strncpy(user->nick, parameters[0],NICKMAX);
4285
4286         log(DEBUG,"new nick set: %s",user->nick);
4287         
4288         if (user->registered < 3)
4289                 user->registered = (user->registered | 2);
4290         if (user->registered == 3)
4291         {
4292                 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
4293                 ConnectUser(user);
4294         }
4295         log(DEBUG,"exit nickchange: %s",user->nick);
4296 }
4297
4298 int process_parameters(char **command_p,char *parameters)
4299 {
4300         int i = 0;
4301         int j = 0;
4302         int q = 0;
4303         q = strlen(parameters);
4304         if (!q)
4305         {
4306                 /* no parameters, command_p invalid! */
4307                 return 0;
4308         }
4309         if (parameters[0] == ':')
4310         {
4311                 command_p[0] = parameters+1;
4312                 return 1;
4313         }
4314         if (q)
4315         {
4316                 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
4317                 {
4318                         /* only one parameter */
4319                         command_p[0] = parameters;
4320                         if (parameters[0] == ':')
4321                         {
4322                                 if (strchr(parameters,' ') != NULL)
4323                                 {
4324                                         command_p[0]++;
4325                                 }
4326                         }
4327                         return 1;
4328                 }
4329         }
4330         command_p[j++] = parameters;
4331         for (i = 0; i <= q; i++)
4332         {
4333                 if (parameters[i] == ' ')
4334                 {
4335                         command_p[j++] = parameters+i+1;
4336                         parameters[i] = '\0';
4337                         if (command_p[j-1][0] == ':')
4338                         {
4339                                 *command_p[j-1]++; /* remove dodgy ":" */
4340                                 break;
4341                                 /* parameter like this marks end of the sequence */
4342                         }
4343                 }
4344         }
4345         return j; /* returns total number of items in the list */
4346 }
4347
4348 void process_command(userrec *user, char* cmd)
4349 {
4350         char *parameters;
4351         char *command;
4352         char *command_p[127];
4353         char p[MAXBUF], temp[MAXBUF];
4354         int i, j, items, cmd_found;
4355
4356         for (int i = 0; i < 127; i++)
4357                 command_p[i] = NULL;
4358
4359         if (!user)
4360         {
4361                 return;
4362         }
4363         if (!cmd)
4364         {
4365                 return;
4366         }
4367         if (!strcmp(cmd,""))
4368         {
4369                 return;
4370         }
4371         strcpy(temp,cmd);
4372
4373         string tmp = cmd;
4374         FOREACH_MOD OnServerRaw(tmp,true);
4375         const char* cmd2 = tmp.c_str();
4376         snprintf(cmd,512,"%s",cmd2);
4377
4378         if (!strchr(cmd,' '))
4379         {
4380                 /* no parameters, lets skip the formalities and not chop up
4381                  * the string */
4382                 items = 0;
4383                 command_p[0] = NULL;
4384                 parameters = NULL;
4385                 for (int i = 0; i <= strlen(cmd); i++)
4386                 {
4387                         cmd[i] = toupper(cmd[i]);
4388                 }
4389         }
4390         else
4391         {
4392                 strcpy(cmd,"");
4393                 j = 0;
4394                 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
4395                 for (i = 0; i < strlen(temp); i++)
4396                 {
4397                         if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
4398                         {
4399                                 cmd[j++] = temp[i];
4400                                 cmd[j] = 0;
4401                         }
4402                 }
4403                 /* split the full string into a command plus parameters */
4404                 parameters = p;
4405                 strcpy(p," ");
4406                 command = cmd;
4407                 if (strchr(cmd,' '))
4408                 {
4409                         for (i = 0; i <= strlen(cmd); i++)
4410                         {
4411                                 /* capitalise the command ONLY, leave params intact */
4412                                 cmd[i] = toupper(cmd[i]);
4413                                 /* are we nearly there yet?! :P */
4414                                 if (cmd[i] == ' ')
4415                                 {
4416                                         command = cmd;
4417                                         parameters = cmd+i+1;
4418                                         cmd[i] = '\0';
4419                                         break;
4420                                 }
4421                         }
4422                 }
4423                 else
4424                 {
4425                         for (i = 0; i <= strlen(cmd); i++)
4426                         {
4427                                 cmd[i] = toupper(cmd[i]);
4428                         }
4429                 }
4430
4431         }
4432         
4433         cmd_found = 0;
4434
4435         if (strlen(command)>MAXCOMMAND)
4436         {
4437                 command[MAXCOMMAND-1] = '\0';
4438                 WriteOpers("Possible command-flood from %s, sending excessively long commands.",user->nick);
4439         }
4440
4441         for (i = 0; i != cmdlist.size(); i++)
4442         {
4443                 if (strcmp(cmdlist[i].command,""))
4444                 {
4445                         if (!strcmp(command, cmdlist[i].command))
4446                         {
4447                                 if (parameters)
4448                                 {
4449                                         if (strcmp(parameters,""))
4450                                         {
4451                                                 items = process_parameters(command_p,parameters);
4452                                         }
4453                                         else
4454                                         {
4455                                                 items = 0;
4456                                                 command_p[0] = NULL;
4457                                         }
4458                                 }
4459                                 else
4460                                 {
4461                                         items = 0;
4462                                         command_p[0] = NULL;
4463                                 }
4464                                 
4465                                 if (user)
4466                                 {
4467                                         user->idle_lastmsg = time(NULL);
4468                                         /* activity resets the ping pending timer */
4469                                         user->nping = time(NULL) + 120;
4470                                         if ((items) < cmdlist[i].min_params)
4471                                         {
4472                                                 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
4473                                                 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
4474                                                 return;
4475                                         }
4476                                         if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
4477                                         {
4478                                                 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
4479                                                 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
4480                                                 cmd_found = 1;
4481                                                 return;
4482                                         }
4483                 /* if the command isnt USER, PASS, or NICK, and nick is empty,
4484                  * deny command! */
4485                                         if ((strcmp(command,"USER")) && (strcmp(command,"NICK")) && (strcmp(command,"PASS")))
4486                                         {
4487                                                 if ((!isnick(user->nick)) || (user->registered != 7))
4488                                                 {
4489                                                         log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
4490                                                         WriteServ(user->fd,"451 %s :You have not registered",command);
4491                                                         return;
4492                                                 }
4493                                         }
4494                                         if ((user->registered == 7) || (!strcmp(command,"USER")) || (!strcmp(command,"NICK")) || (!strcmp(command,"PASS")))
4495                                         {
4496                                                 log(DEBUG,"process_command: handler: %s %s %d",user->nick,command,items);
4497                                                 if (cmdlist[i].handler_function)
4498                                                 {
4499                                                         /* ikky /stats counters */
4500                                                         if (temp)
4501                                                         {
4502                                                                 if (user)
4503                                                                 {
4504                                                                         user->bytes_in += strlen(temp);
4505                                                                         user->cmds_in++;
4506                                                                 }
4507                                                                 cmdlist[i].use_count++;
4508                                                                 cmdlist[i].total_bytes+=strlen(temp);
4509                                                         }
4510
4511                                                         /* WARNING: nothing may come after the
4512                                                          * command handler call, as the handler
4513                                                          * may free the user structure! */
4514
4515                                                         cmdlist[i].handler_function(command_p,items,user);
4516                                                 }
4517                                                 return;
4518                                         }
4519                                         else
4520                                         {
4521                                                 log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
4522                                                 WriteServ(user->fd,"451 %s :You have not registered",command);
4523                                                 return;
4524                                         }
4525                                 }
4526                                 cmd_found = 1;
4527                         }
4528                 }
4529         }
4530         if ((!cmd_found) && (user))
4531         {
4532                 log(DEBUG,"process_command: not in table: %s %s",user->nick,command);
4533                 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
4534         }
4535 }
4536
4537
4538 void createcommand(char* cmd, handlerfunc f, char flags, int minparams)
4539 {
4540         command_t comm;
4541         /* create the command and push it onto the table */     
4542         strcpy(comm.command,cmd);
4543         comm.handler_function = f;
4544         comm.flags_needed = flags;
4545         comm.min_params = minparams;
4546         comm.use_count = 0;
4547         comm.total_bytes = 0;
4548         cmdlist.push_back(comm);
4549         log(DEBUG,"Added command %s (%d parameters)",cmd,minparams);
4550 }
4551
4552 void SetupCommandTable(void)
4553 {
4554   createcommand("USER",handle_user,0,4);
4555   createcommand("NICK",handle_nick,0,1);
4556   createcommand("QUIT",handle_quit,0,0);
4557   createcommand("VERSION",handle_version,0,0);
4558   createcommand("PING",handle_ping,0,1);
4559   createcommand("PONG",handle_pong,0,1);
4560   createcommand("ADMIN",handle_admin,0,0);
4561   createcommand("PRIVMSG",handle_privmsg,0,2);
4562   createcommand("INFO",handle_info,0,0);
4563   createcommand("TIME",handle_time,0,0);
4564   createcommand("WHOIS",handle_whois,0,1);
4565   createcommand("WALLOPS",handle_wallops,'o',1);
4566   createcommand("NOTICE",handle_notice,0,2);
4567   createcommand("JOIN",handle_join,0,1);
4568   createcommand("NAMES",handle_names,0,1);
4569   createcommand("PART",handle_part,0,1);
4570   createcommand("KICK",handle_kick,0,2);
4571   createcommand("MODE",handle_mode,0,1);
4572   createcommand("TOPIC",handle_topic,0,1);
4573   createcommand("WHO",handle_who,0,1);
4574   createcommand("MOTD",handle_motd,0,0);
4575   createcommand("RULES",handle_join,0,0);
4576   createcommand("OPER",handle_oper,0,2);
4577   createcommand("LIST",handle_list,0,0);
4578   createcommand("DIE",handle_die,'o',1);
4579   createcommand("RESTART",handle_restart,'o',1);
4580   createcommand("KILL",handle_kill,'o',2);
4581   createcommand("REHASH",handle_rehash,'o',0);
4582   createcommand("LUSERS",handle_lusers,0,0);
4583   createcommand("STATS",handle_stats,0,1);
4584   createcommand("USERHOST",handle_userhost,0,1);
4585   createcommand("AWAY",handle_away,0,0);
4586   createcommand("ISON",handle_ison,0,0);
4587   createcommand("SUMMON",handle_summon,0,0);
4588   createcommand("USERS",handle_users,0,0);
4589   createcommand("INVITE",handle_invite,0,2);
4590   createcommand("PASS",handle_pass,0,1);
4591   createcommand("TRACE",handle_trace,'o',0);
4592   createcommand("WHOWAS",handle_whowas,0,1);
4593   createcommand("CONNECT",handle_connect,'o',1);
4594   createcommand("SQUIT",handle_squit,'o',1);
4595   createcommand("MODULES",handle_modules,'o',0);
4596 }
4597
4598 void process_buffer(userrec *user)
4599 {
4600         if (!user)
4601         {
4602                 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
4603                 return;
4604         }
4605         char cmd[MAXBUF];
4606         int i;
4607         if (!user->inbuf)
4608         {
4609                 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
4610                 return;
4611         }
4612         if (!strcmp(user->inbuf,""))
4613         {
4614                 return;
4615         }
4616         strncpy(cmd,user->inbuf,MAXBUF);
4617         if (!strcmp(cmd,""))
4618         {
4619                 return;
4620         }
4621         if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
4622         {
4623                 cmd[strlen(cmd)-1] = '\0';
4624         }
4625         if ((cmd[strlen(cmd)-1] == 13) || (cmd[strlen(cmd)-1] == 10))
4626         {
4627                 cmd[strlen(cmd)-1] = '\0';
4628         }
4629         strcpy(user->inbuf,"");
4630         if (!strcmp(cmd,""))
4631         {
4632                 return;
4633         }
4634         log(DEBUG,"InspIRCd: processing: %s %s",user->nick,cmd);
4635         tidystring(cmd);
4636         if (user)
4637         {
4638                 process_command(user,cmd);
4639         }
4640 }
4641
4642 void process_restricted_commands(char token,char* params,serverrec* source,serverrec* reply, char* udp_host,int udp_port)
4643 {
4644         WriteOpers("Secure-UDP-Channel: Token='%c', Params='%s'",token,params);
4645 }
4646
4647
4648 void handle_link_packet(long theirkey, char* udp_msg, char* udp_host, int udp_port, serverrec *serv)
4649 {
4650         char response[10240];
4651         char token = udp_msg[0];
4652         char* params = udp_msg + 2;
4653         char finalparam[1024];
4654         strcpy(finalparam," :xxxx");
4655         if (strstr(params," :")) {
4656                 strncpy(finalparam,strstr(params," :"),1024);
4657         }
4658         if (token == 'S') {
4659                 // S test.chatspike.net password :ChatSpike InspIRCd test server
4660                 char* servername = strtok(params," ");
4661                 char* password = strtok(NULL," ");
4662                 char* serverdesc = finalparam+2;
4663                 WriteOpers("CONNECT from %s (%s)",servername,udp_host,password,serverdesc);
4664                 
4665                 
4666                 char Link_ServerName[1024];
4667                 char Link_IPAddr[1024];
4668                 char Link_Port[1024];
4669                 char Link_Pass[1024];
4670                 char Link_SendPass[1024];
4671                 int LinkPort = 0;
4672                 
4673                 // search for a corresponding <link> block in the config files
4674                 for (int i = 0; i < ConfValueEnum("link"); i++)
4675                 {
4676                         ConfValue("link","name",i,Link_ServerName);
4677                         ConfValue("link","ipaddr",i,Link_IPAddr);
4678                         ConfValue("link","port",i,Link_Port);
4679                         ConfValue("link","recvpass",i,Link_Pass);
4680                         ConfValue("link","sendpass",i,Link_SendPass);
4681                         log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
4682                         LinkPort = atoi(Link_Port);
4683                         if (!strcasecmp(Link_ServerName,servername)) {
4684                                 if (!strcasecmp(Link_IPAddr,udp_host)) {
4685                                         if (LinkPort == udp_port) {
4686                                                 // we have a matching link line -
4687                                                 // send a 'diminutive' server message back...
4688                                                 snprintf(response,10240,"s %s %s :%s",ServerName,Link_SendPass,ServerDesc);
4689                                                 serv->SendPacket(response,udp_host,udp_port,0);
4690                                                 WriteOpers("CONNECT from %s accepted, authenticating",servername);
4691                                                 for (int j = 0; j < 255; j++) {
4692                                                         if (servers[j] == NULL) {
4693                                                                 servers[j] = new serverrec;
4694                                                                 strcpy(servers[j]->internal_addr,udp_host);
4695                                                                 strcpy(servers[j]->name,servername);
4696                                                                 // create a server record for this server
4697                                                                 snprintf(response,10240,"O %d",MyKey);
4698                                                                 serv->SendPacket(response,udp_host,udp_port,0);
4699                                                                 return;
4700                                                         }
4701                                                 }
4702                                                 WriteOpers("Internal error connecting to %s, failed to create server record!",servername);
4703                                                 return;
4704                                         }
4705                                         else {
4706                                                 log(DEBUG,"Port numbers '%d' and '%d' don't match",LinkPort,udp_port);
4707                                         }
4708                                 }
4709                                 else {
4710                                         log(DEBUG,"IP Addresses '%s' and '%s' don't match",Link_IPAddr,udp_host);
4711                                 }
4712                         }
4713                         else {
4714                                 log(DEBUG,"Server names '%s' and '%s' don't match",Link_ServerName,servername);
4715                         }
4716                 }
4717                 serv->SendPacket("E :Access is denied (no matching link block)",udp_host,udp_port,0);
4718                 WriteOpers("CONNECT from %s denied, no matching link block",servername);
4719                 return;
4720         }
4721         else
4722         if (token == 'O') {
4723                 // if this is received, this means the server-ip that sent it said "OK" to credentials.
4724                 // only when a server says this do we exchange keys. The server MUST have an entry in the servers
4725                 // array, which is only added by an 'S' packet or BeginLink().
4726                 for (int i = 0; i < 255; i++) {
4727                         if (servers[i] != NULL) {
4728                                 if (!strcasecmp(servers[i]->internal_addr,udp_host)) {
4729                                         servers[i]->key = atoi(params);
4730                                         log(DEBUG,"Key for this server is now %d",servers[i]->key);
4731                                         serv->SendPacket("Z blah blah",udp_host,udp_port,MyKey);
4732                                         return;
4733                                 }
4734                         }
4735                 }
4736                 WriteOpers("\2WARNING!\2 Server ip %s attempted a key exchange, but is not in the authentication state! Possible intrusion attempt!",udp_host);
4737         }
4738         else
4739         if (token == 's') {
4740                 // S test.chatspike.net password :ChatSpike InspIRCd test server
4741                 char* servername = strtok(params," ");
4742                 char* password = strtok(NULL," ");
4743                 char* serverdesc = finalparam+2;
4744                 
4745                 // TODO: we should do a check here to ensure that this server is one we recently initiated a
4746                 // link with, and didnt hear an 's' or 'E' back from yet (these are the only two valid responses
4747                 // to an 'S' command. If we didn't recently send an 'S' to this server, theyre trying to spoof
4748                 // a connect, so put out an oper alert!
4749                 
4750                 
4751                 
4752                 
4753                 // for now, just accept all, we'll fix that later.
4754                 WriteOpers("%s accepted our link credentials ",servername);
4755                 
4756                 char Link_ServerName[1024];
4757                 char Link_IPAddr[1024];
4758                 char Link_Port[1024];
4759                 char Link_Pass[1024];
4760                 char Link_SendPass[1024];
4761                 int LinkPort = 0;
4762                 
4763                 // search for a corresponding <link> block in the config files
4764                 for (int i = 0; i < ConfValueEnum("link"); i++)
4765                 {
4766                         ConfValue("link","name",i,Link_ServerName);
4767                         ConfValue("link","ipaddr",i,Link_IPAddr);
4768                         ConfValue("link","port",i,Link_Port);
4769                         ConfValue("link","recvpass",i,Link_Pass);
4770                         ConfValue("link","sendpass",i,Link_SendPass);
4771                         log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
4772                         LinkPort = atoi(Link_Port);
4773                         if (!strcasecmp(Link_ServerName,servername)) {
4774                                 if (!strcasecmp(Link_IPAddr,udp_host)) {
4775                                         if (LinkPort == udp_port) {
4776                                                 // matching link at this end too, we're all done!
4777                                                 // at this point we must begin key exchange and insert this
4778                                                 // server into our 'active' table.
4779                                                 for (int j = 0; j < 255; j++) {
4780                                                         if (servers[j] != NULL) {
4781                                                                 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
4782                                                                         WriteOpers("Server %s authenticated, exchanging server keys...",servername);
4783                                                                         snprintf(response,10240,"O %d",MyKey);
4784                                                                         serv->SendPacket(response,udp_host,udp_port,0);
4785                                                                         return;
4786                                                                 }
4787                                                         }
4788                                                 }
4789                                                 WriteOpers("\2WARNING!\2 %s sent us an authentication packet but we are not authenticating with this server right noe! Possible intrusion attempt!",udp_host);
4790                                                 return;
4791
4792                                         }
4793                                         else {
4794                                                 log(DEBUG,"Port numbers '%d' and '%d' don't match",LinkPort,udp_port);
4795                                         }
4796                                 }
4797                                 else {
4798                                         log(DEBUG,"IP Addresses '%s' and '%s' don't match",Link_IPAddr,udp_host);
4799                                 }
4800                         }
4801                         else {
4802                                 log(DEBUG,"Server names '%s' and '%s' don't match",Link_ServerName,servername);
4803                         }
4804                 }
4805                 serv->SendPacket("E :Access is denied (no matching link block)",udp_host,udp_port,0);
4806                 WriteOpers("CONNECT from %s denied, no matching link block",servername);
4807                 return;
4808         }
4809         else
4810         if (token == 'E') {
4811                 char* error_message = finalparam+2;
4812                 WriteOpers("ERROR from %s: %s",udp_host,error_message);
4813                 // remove this server from any lists
4814                 for (int j = 0; j < 255; j++) {
4815                         if (servers[j] != NULL) {
4816                                 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
4817                                         delete servers[j];
4818                                         return;
4819                                 }
4820                         }
4821                 }
4822                 return;
4823         }
4824         else {
4825
4826                 serverrec* source_server = NULL;
4827
4828                 for (int j = 0; j < 255; j++) {
4829                         if (servers[j] != NULL) {
4830                                 if (!strcasecmp(servers[j]->internal_addr,udp_host)) {
4831                                         if (servers[j]->key == theirkey) {
4832                                                 // found a valid key for this server, can process restricted stuff here
4833                                                 process_restricted_commands(token,params,servers[j],serv,udp_host,udp_port);
4834                                                 
4835                                                 return;
4836                                         }
4837                                 }
4838                         }
4839                 }
4840
4841                 log(DEBUG,"Unrecognised token or unauthenticated host in datagram from %s:%d: %c",udp_host,udp_port,token);
4842         }
4843 }
4844
4845 int reap_counter = 0;
4846
4847 int InspIRCd(void)
4848 {
4849   struct sockaddr_in client, server;
4850   char addrs[MAXBUF][255];
4851   int openSockfd[MAXSOCKS], incomingSockfd, result = TRUE;
4852   socklen_t length;
4853   int count = 0, scanDetectTrigger = TRUE, showBanner = FALSE;
4854   int selectResult = 0;
4855   char *temp, configToken[MAXBUF], stuff[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
4856   char resolvedHost[MAXBUF];
4857   fd_set selectFds;
4858   struct timeval tv;
4859
4860   log_file = fopen("ircd.log","a+");
4861   if (!log_file)
4862   {
4863         printf("ERROR: Could not write to logfile ircd.log, bailing!\n\n");
4864         Exit(ERROR);
4865   }
4866
4867   log(DEBUG,"InspIRCd: startup: begin");
4868   log(DEBUG,"$Id$");
4869   if (geteuid() == 0)
4870   {
4871         printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
4872         Exit(ERROR);
4873         log(DEBUG,"InspIRCd: startup: not starting with UID 0!");
4874   }
4875   SetupCommandTable();
4876   log(DEBUG,"InspIRCd: startup: default command table set up");
4877
4878   ReadConfig();
4879   if (strcmp(DieValue,"")) 
4880   { 
4881         printf("WARNING: %s\n\n",DieValue);
4882         exit(0); 
4883   }  
4884   log(DEBUG,"InspIRCd: startup: read config");
4885   
4886   int count2 = 0, count3 = 0;
4887   for (count = 0; count < ConfValueEnum("bind"); count++)
4888   {
4889         ConfValue("bind","port",count,configToken);
4890         ConfValue("bind","address",count,Addr);
4891         ConfValue("bind","type",count,Type);
4892         if (!strcmp(Type,"servers"))
4893         {
4894                 char Default[MAXBUF];
4895                 strcpy(Default,"no");
4896                 ConfValue("bind","default",count,Default);
4897                 if (strchr(Default,'y'))
4898                 {
4899                                 defaultRoute = count3;
4900                                 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
4901                 }
4902                 me[count3] = new serverrec(ServerName,100L,false);
4903                 me[count3]->CreateListener(Addr,atoi(configToken));
4904                 count3++;
4905         }
4906         else
4907         {
4908                 ports[count2] = atoi(configToken);
4909                 strcpy(addrs[count2],Addr);
4910                 count2++;
4911         }
4912         log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
4913   }
4914   portCount = count2;
4915   UDPportCount = count3;
4916   
4917   log(DEBUG,"InspIRCd: startup: read %d total client ports and %d total server ports",portCount,UDPportCount);
4918
4919   log(DEBUG,"InspIRCd: startup: InspIRCd is now running!");
4920
4921   printf("\n");
4922
4923   /* BugFix By Craig! :p */
4924   count2 = 0;
4925   for (count = 0; count2 < ConfValueEnum("module"); count2++)
4926   {
4927         char modfile[MAXBUF];
4928         ConfValue("module","name",count,configToken);
4929         sprintf(modfile,"%s/%s",MOD_PATH,configToken);
4930         printf("Loading module... \033[1;37m%s\033[0;37m\n",modfile);
4931         log(DEBUG,"InspIRCd: startup: Loading module: %s",modfile);
4932         /* If The File Doesnt exist, Trying to load it
4933          * Will Segfault the IRCd.. So, check to see if
4934          * it Exists, Before Proceeding. */
4935         if (FileExists(modfile))
4936         {
4937                 factory[count] = new ircd_module(modfile);
4938                 if (factory[count]->LastError())
4939                 {
4940                         log(DEBUG,"Unable to load %s: %s",modfile,factory[count]->LastError());
4941                         sprintf("Unable to load %s: %s\nExiting...\n",modfile,factory[count]->LastError());
4942                         Exit(ERROR);
4943                 }
4944                 if (factory[count]->factory)
4945                 {
4946                         modules[count] = factory[count]->factory->CreateModule();
4947                         /* save the module and the module's classfactory, if
4948                          * this isnt done, random crashes can occur :/ */
4949                         module_names.push_back(modfile);        
4950                 }
4951                 else
4952                 {
4953                         log(DEBUG,"Unable to load %s",modfile);
4954                         sprintf("Unable to load %s\nExiting...\n",modfile);
4955                         Exit(ERROR);
4956                 }
4957                 /* Increase the Count */
4958                 count++;
4959         }
4960         else
4961         {
4962                 log(DEBUG,"InspIRCd: startup: Module Not Found %s",modfile);
4963                 printf("Module Not Found: \033[1;37m%s\033[0;37m, Skipping\n",modfile);
4964         }
4965   }
4966   MODCOUNT = count - 1;
4967   log(DEBUG,"Total loaded modules: %d",MODCOUNT+1);
4968
4969   printf("\nInspIRCd is now running!\n");
4970
4971   startup_time = time(NULL);
4972   
4973   if (nofork)
4974   {
4975         log(VERBOSE,"Not forking as -nofork was specified");
4976   }
4977   else
4978   {
4979         if (DaemonSeed() == ERROR)
4980         {
4981                 log(DEBUG,"InspIRCd: startup: can't daemonise");
4982                 printf("ERROR: could not go into daemon mode. Shutting down.\n");
4983                 Exit(ERROR);
4984         }
4985   }
4986   
4987   
4988   /* setup select call */
4989   FD_ZERO(&selectFds);
4990   log(DEBUG,"InspIRCd: startup: zero selects");
4991   log(VERBOSE,"InspIRCd: startup: portCount = %d", portCount);
4992
4993   for (count = 0; count < portCount; count++)
4994   {
4995           if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
4996       {
4997                 log(DEBUG,"InspIRCd: startup: bad fd %d",openSockfd[boundPortCount]);
4998                 return(ERROR);
4999       }
5000       if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
5001       {
5002                 log(DEBUG,"InspIRCd: startup: failed to bind port %d",ports[count]);
5003       }
5004       else                      /* well we at least bound to one socket so we'll continue */
5005       {
5006                 boundPortCount++;
5007       }
5008   }
5009
5010   log(DEBUG,"InspIRCd: startup: total bound ports %d",boundPortCount);
5011   
5012   /* if we didn't bind to anything then abort */
5013   if (boundPortCount == 0)
5014   {
5015      log(DEBUG,"InspIRCd: startup: no ports bound, bailing!");
5016      return (ERROR);
5017   }
5018
5019   length = sizeof (client);
5020   int flip_flop = 0, udp_port = 0;
5021   char udp_msg[MAXBUF], udp_host[MAXBUF];
5022   
5023   /* main loop for multiplexing/resetting */
5024   for (;;)
5025   {
5026       /* set up select call */
5027       for (count = 0; count < boundPortCount; count++)
5028       {
5029                 FD_SET (openSockfd[count], &selectFds);
5030       }
5031         
5032       /* added timeout! select was waiting forever... wank... :/ */
5033       tv.tv_usec = 0;
5034
5035       flip_flop++;
5036       reap_counter++;
5037       if (flip_flop > 20)
5038       {
5039               tv.tv_usec = 1;
5040               flip_flop = 0;
5041       }
5042       
5043         vector<int>::iterator niterator;
5044                 
5045
5046         // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
5047         // them in a list, then reap the list every second or so.
5048         if (reap_counter>5000) {
5049                 if (fd_reap.size() > 0) {
5050                         for( int n = 0; n < fd_reap.size(); n++)
5051                         {
5052                                 Blocking(fd_reap[n]);
5053                                 close(fd_reap[n]);
5054                                 NonBlocking(fd_reap[n]);
5055                         }
5056                 }
5057                 fd_reap.clear();
5058                 reap_counter=0;
5059         }
5060
5061       
5062       tv.tv_sec = 0;
5063       selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
5064
5065       for (int x = 0; x != UDPportCount; x++)
5066       {
5067            long theirkey = 0;
5068            if (me[x]->RecvPacket(udp_msg, udp_host, udp_port, theirkey))
5069            {
5070                         if (strlen(udp_msg)<1) {
5071                                 log(DEBUG,"Invalid datagram from %s:%d:%d [route%d]",udp_host,udp_port,me[x]->port,x);
5072                         }
5073                         else {
5074                                 FOREACH_MOD OnPacketReceive(udp_msg);
5075                                 // Packets must go back via the route they arrived on :)
5076                                 handle_link_packet(theirkey, udp_msg, udp_host, udp_port, me[x]);
5077                         }
5078            }
5079       }
5080
5081         for (user_hash::iterator count2 = clientlist.begin(); count2 != clientlist.end(); count2++)
5082         {
5083                 char data[MAXBUF];
5084
5085                 if (!count2->second) break;
5086                 
5087                 if (count2->second)
5088                 if (count2->second->fd)
5089                 {
5090                         if (((time(NULL)) > count2->second->nping) && (isnick(count2->second->nick)) && (count2->second->registered == 7))
5091                         {
5092                                 if (!count2->second->lastping) 
5093                                 {
5094                                         log(DEBUG,"InspIRCd: ping timeout: %s",count2->second->nick);
5095                                         kill_link(count2->second,"Ping timeout");
5096                                         break;
5097                                 }
5098                                 Write(count2->second->fd,"PING :%s",ServerName);
5099                                 log(DEBUG,"InspIRCd: pinging: %s",count2->second->nick);
5100                                 count2->second->lastping = 0;
5101                                 count2->second->nping = time(NULL)+120;
5102                         }
5103                         
5104                         result = read(count2->second->fd, data, 1);
5105                         // result EAGAIN means nothing read
5106                         if (result == EAGAIN)
5107                         {
5108                         }
5109                         else
5110                         if (result == 0)
5111                         {
5112                                 if (count2->second)
5113                                 {
5114                                         log(DEBUG,"InspIRCd: Exited: %s",count2->second->nick);
5115                                         kill_link(count2->second,"Client exited");
5116                                         // must bail here? kill_link removes the hash, corrupting the iterator
5117                                         log(DEBUG,"Bailing from client exit");
5118                                         break;
5119                                 }
5120                         }
5121                         else if (result > 0)
5122                         {
5123                                 if (count2->second)
5124                                 {
5125                                         strncat(count2->second->inbuf, data, result);
5126
5127                                         if (strlen(count2->second->inbuf) > 509) {
5128                                                 count2->second->inbuf[509] = '\r';
5129                                                 count2->second->inbuf[510] = '\n';
5130                                                 count2->second->inbuf[511] = '\0';
5131                                         }
5132
5133                                         if (strchr(count2->second->inbuf, '\n') || strchr(count2->second->inbuf, '\r') || (strlen(count2->second->inbuf) > 509))
5134                                         {
5135                                                 /* at least one complete line is waiting to be processed */
5136                                                 if (!count2->second->fd)
5137                                                         break;
5138                                                 else
5139                                                 {
5140                                                         process_buffer(count2->second);
5141                                                         break;
5142                                                 }
5143                                         }
5144                                 }
5145                         }
5146                 }
5147         }
5148
5149       /* select is reporting a waiting socket. Poll them all to find out which */
5150       if (selectResult > 0)
5151       {
5152         char target[MAXBUF], resolved[MAXBUF];
5153         for (count = 0; count < boundPortCount; count++)                
5154         {
5155             if (FD_ISSET (openSockfd[count], &selectFds))
5156             {
5157               incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
5158               
5159               address_cache::iterator iter = IP.find(client.sin_addr);
5160               bool iscached = false;
5161               if (iter == IP.end())
5162               {
5163                         /* ip isn't in cache, add it */
5164                         strncpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
5165                         if(CleanAndResolve(resolved, target) != TRUE)
5166                         {
5167                                 strncpy(resolved,target,MAXBUF);
5168                         }
5169                         /* hostname now in 'target' */
5170                         IP[client.sin_addr] = new string(resolved);
5171               /* hostname in cache */
5172               }
5173               else
5174               {
5175               /* found ip (cached) */
5176               strncpy(resolved, iter->second->c_str(), MAXBUF);
5177               iscached = true;
5178            }
5179
5180               if (incomingSockfd < 0)
5181               {
5182                         WriteOpers("*** WARNING: Accept failed on port %d (%s)", ports[count],target);
5183                         log(DEBUG,"InspIRCd: accept failed: %d",ports[count]);
5184                         break;
5185               }
5186
5187               AddClient(incomingSockfd, resolved, ports[count], iscached);
5188               log(DEBUG,"InspIRCd: adding client on port %d fd=%d",ports[count],incomingSockfd);
5189               break;
5190             }
5191
5192            }
5193       }
5194   }
5195
5196   /* not reached */
5197   close (incomingSockfd);
5198 }
5199