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