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