]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/commands.cpp
d62ad4bcc47515df52424e7e5f57b08b079f925c
[user/henk/code/inspircd.git] / src / commands.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  Inspire is copyright (C) 2002-2004 ChatSpike-Dev.
6  *                       E-mail:
7  *                <brain@chatspike.net>
8  *                <Craig@chatspike.net>
9  *     
10  * Written by Craig Edwards, Craig McLure, and others.
11  * This program is free but copyrighted software; see
12  *            the file COPYING for details.
13  *
14  * ---------------------------------------------------
15  */
16
17 #include "inspircd.h"
18 #include "inspircd_io.h"
19 #include "inspircd_util.h"
20 #include "inspircd_config.h"
21 #include <unistd.h>
22 #include <fcntl.h>
23 #include <sys/errno.h>
24 #include <sys/ioctl.h>
25 #include <sys/utsname.h>
26 #include <cstdio>
27 #include <time.h>
28 #include <string>
29 #ifdef GCC3
30 #include <ext/hash_map>
31 #else
32 #include <hash_map>
33 #endif
34 #include <map>
35 #include <sstream>
36 #include <vector>
37 #include <errno.h>
38 #include <deque>
39 #include <errno.h>
40 #include <unistd.h>
41 #include <sched.h>
42 #include "connection.h"
43 #include "users.h"
44 #include "servers.h"
45 #include "ctables.h"
46 #include "globals.h"
47 #include "modules.h"
48 #include "dynamic.h"
49 #include "wildcard.h"
50 #include "message.h"
51 #include "mode.h"
52 #include "xline.h"
53 #include "inspstring.h"
54 #include "dnsqueue.h"
55
56 #ifdef GCC3
57 #define nspace __gnu_cxx
58 #else
59 #define nspace std
60 #endif
61
62 using namespace std;
63
64 extern int MODCOUNT;
65 extern std::vector<Module*> modules;
66 extern std::vector<ircd_module*> factory;
67
68 extern int LogLevel;
69 extern char ServerName[MAXBUF];
70 extern char Network[MAXBUF];
71 extern char ServerDesc[MAXBUF];
72 extern char AdminName[MAXBUF];
73 extern char AdminEmail[MAXBUF];
74 extern char AdminNick[MAXBUF];
75 extern char diepass[MAXBUF];
76 extern char restartpass[MAXBUF];
77 extern char motd[MAXBUF];
78 extern char rules[MAXBUF];
79 extern char list[MAXBUF];
80 extern char PrefixQuit[MAXBUF];
81 extern char DieValue[MAXBUF];
82
83 extern int debugging;
84 extern int WHOWAS_STALE;
85 extern int WHOWAS_MAX;
86 extern int DieDelay;
87 extern time_t startup_time;
88 extern int NetBufferSize;
89 extern int MaxWhoResults;
90 extern time_t nb_start;
91
92 extern bool nofork;
93
94 extern time_t TIME;
95
96 extern std::vector<std::string> module_names;
97
98 extern char MyExecutable[1024];
99 extern int boundPortCount;
100 extern int portCount;
101 extern int UDPportCount;
102 extern int ports[MAXSOCKS];
103 extern int defaultRoute;
104
105 extern std::vector<long> auth_cookies;
106 extern std::stringstream config_f;
107
108 extern serverrec* me[32];
109
110 extern FILE *log_file;
111
112 extern ClassVector Classes;
113
114 const long duration_m = 60;
115 const long duration_h = duration_m * 60;
116 const long duration_d = duration_h * 24;
117 const long duration_w = duration_d * 7;
118 const long duration_y = duration_w * 52;
119
120 namespace nspace
121 {
122 #ifdef GCC34
123         template<> struct hash<in_addr>
124 #else
125         template<> struct nspace::hash<in_addr>
126 #endif
127         {
128                 size_t operator()(const struct in_addr &a) const
129                 {
130                         size_t q;
131                         memcpy(&q,&a,sizeof(size_t));
132                         return q;
133                 }
134         };
135 #ifdef GCC34
136         template<> struct hash<string>
137 #else
138         template<> struct nspace::hash<string>
139 #endif
140         {
141                 size_t operator()(const string &s) const
142                 {
143                         char a[MAXBUF];
144                         static struct hash<const char *> strhash;
145                         strlcpy(a,s.c_str(),MAXBUF);
146                         strlower(a);
147                         return strhash(a);
148                 }
149         };
150 }
151
152
153 struct StrHashComp
154 {
155
156         bool operator()(const string& s1, const string& s2) const
157         {
158                 char a[MAXBUF],b[MAXBUF];
159                 strlcpy(a,s1.c_str(),MAXBUF);
160                 strlcpy(b,s2.c_str(),MAXBUF);
161                 strlower(a);
162                 strlower(b);
163                 return (strcasecmp(a,b) == 0);
164         }
165
166 };
167
168 struct InAddr_HashComp
169 {
170
171         bool operator()(const in_addr &s1, const in_addr &s2) const
172         {
173                 size_t q;
174                 size_t p;
175                 
176                 memcpy(&q,&s1,sizeof(size_t));
177                 memcpy(&p,&s2,sizeof(size_t));
178                 
179                 return (q == p);
180         }
181
182 };
183
184
185 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, StrHashComp> user_hash;
186 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, StrHashComp> chan_hash;
187 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, InAddr_HashComp> address_cache;
188 typedef std::deque<command_t> command_table;
189
190
191 extern user_hash clientlist;
192 extern chan_hash chanlist;
193 extern user_hash whowas;
194 extern command_table cmdlist;
195 extern file_cache MOTD;
196 extern file_cache RULES;
197 extern address_cache IP;
198
199
200 void handle_join(char **parameters, int pcnt, userrec *user)
201 {
202         chanrec* Ptr;
203         
204         if (loop_call(handle_join,parameters,pcnt,user,0,0,1))
205                 return;
206         if (parameters[0][0] == '#')
207         {
208                 Ptr = add_channel(user,parameters[0],parameters[1],false);
209         }
210 }
211
212
213 void handle_part(char **parameters, int pcnt, userrec *user)
214 {
215         if (pcnt > 1)
216         {
217                 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-2,0))
218                         return;
219                 del_channel(user,parameters[0],parameters[1],false);
220         }
221         else
222         {
223                 if (loop_call(handle_part,parameters,pcnt,user,0,pcnt-1,0))
224                         return;
225                 del_channel(user,parameters[0],NULL,false);
226         }
227 }
228
229 void handle_kick(char **parameters, int pcnt, userrec *user)
230 {
231         chanrec* Ptr = FindChan(parameters[0]);
232         userrec* u   = Find(parameters[1]);
233
234         if ((!u) || (!Ptr))
235         {
236                 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[0]);
237                 return;
238         }
239         
240         if (!has_channel(user,Ptr))
241         {
242                 WriteServ(user->fd,"442 %s %s :You're not on that channel!",user->nick, parameters[0]);
243                 return;
244         }
245         
246         char reason[MAXBUF];
247         
248         if (pcnt > 2)
249         {
250                 strlcpy(reason,parameters[2],MAXBUF);
251                 if (strlen(reason)>MAXKICK)
252                 {
253                         reason[MAXKICK-1] = '\0';
254                 }
255
256                 kick_channel(user,u,Ptr,reason);
257         }
258         else
259         {
260                 strlcpy(reason,user->nick,MAXBUF);
261                 kick_channel(user,u,Ptr,reason);
262         }
263         
264         // this must be propogated so that channel membership is kept in step network-wide
265         char buffer[MAXBUF];
266         snprintf(buffer,MAXBUF,"k %s %s %s :%s",user->nick,u->nick,Ptr->name,reason);
267         NetSendToAll(buffer);
268 }
269
270 void handle_loadmodule(char **parameters, int pcnt, userrec *user)
271 {
272         if (LoadModule(parameters[0]))
273         {
274                 WriteOpers("*** NEW MODULE: %s",parameters[0]);
275                 WriteServ(user->fd,"975 %s %s :Module successfully loaded.",user->nick, parameters[0]);
276         }
277         else
278         {
279                 WriteServ(user->fd,"974 %s %s :Failed to load module: %s",user->nick, parameters[0],ModuleError());
280         }
281 }
282
283 void handle_unloadmodule(char **parameters, int pcnt, userrec *user)
284 {
285         if (UnloadModule(parameters[0]))
286         {
287                 WriteOpers("*** MODULE UNLOADED: %s",parameters[0]);
288                 WriteServ(user->fd,"973 %s %s :Module successfully unloaded.",user->nick, parameters[0]);
289         }
290         else
291         {
292                 WriteServ(user->fd,"972 %s %s :Failed to unload module: %s",user->nick, parameters[0],ModuleError());
293         }
294 }
295
296 void handle_die(char **parameters, int pcnt, userrec *user)
297 {
298         log(DEBUG,"die: %s",user->nick);
299         if (!strcmp(parameters[0],diepass))
300         {
301                 WriteOpers("*** DIE command from %s!%s@%s, terminating...",user->nick,user->ident,user->host);
302                 sleep(DieDelay);
303                 Exit(ERROR);
304         }
305         else
306         {
307                 WriteOpers("*** Failed DIE Command from %s!%s@%s.",user->nick,user->ident,user->host);
308         }
309 }
310
311 void handle_restart(char **parameters, int pcnt, userrec *user)
312 {
313         char *argv[32];
314         log(DEFAULT,"Restart: %s",user->nick);
315         if (!strcmp(parameters[0],restartpass))
316         {
317                 WriteOpers("*** RESTART command from %s!%s@%s, restarting server.",user->nick,user->ident,user->host);
318
319                 argv[0] = MyExecutable;
320                 argv[1] = "-wait";
321                 if (nofork)
322                 {
323                         argv[2] = "-nofork";
324                 }
325                 else
326                 {
327                         argv[2] = NULL;
328                 }
329                 argv[3] = NULL;
330                 
331                 // close ALL file descriptors
332                 send_error("Server restarting.");
333                 sleep(1);
334                 for (int i = 0; i < 65536; i++)
335                 {
336                         int on = 1;
337                         struct linger linger = { 0 };
338                         setsockopt(i, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
339                         linger.l_onoff = 1;
340                         linger.l_linger = 1;
341                         setsockopt(i, SOL_SOCKET, SO_LINGER, (const char*)&linger,sizeof(linger));
342                         Blocking(i);
343                         close(i);
344                 }
345                 sleep(2);
346                 
347                 execv(MyExecutable,argv);
348
349                 exit(0);
350         }
351         else
352         {
353                 WriteOpers("*** Failed RESTART Command from %s!%s@%s.",user->nick,user->ident,user->host);
354         }
355 }
356
357 void handle_kill(char **parameters, int pcnt, userrec *user)
358 {
359         userrec *u = Find(parameters[0]);
360         char killreason[MAXBUF];
361
362         log(DEBUG,"kill: %s %s",parameters[0],parameters[1]);
363         if (u)
364         {
365                 log(DEBUG,"into kill mechanism");
366                 int MOD_RESULT = 0;
367                 FOREACH_RESULT(OnKill(user,u,parameters[1]));
368                 if (MOD_RESULT) {
369                         log(DEBUG,"A module prevented the kill with result %d",MOD_RESULT);
370                         return;
371                 }
372
373                 if (strcmp(ServerName,u->server))
374                 {
375                         // remote kill
376                         WriteOpers("*** Remote kill by %s: %s!%s@%s (%s)",user->nick,u->nick,u->ident,u->host,parameters[1]);
377                         snprintf(killreason,MAXBUF,"[%s] Killed (%s (%s))",ServerName,user->nick,parameters[1]);
378                         WriteCommonExcept(u,"QUIT :%s",killreason);
379                         // K token must go to ALL servers!!!
380                         char buffer[MAXBUF];
381                         snprintf(buffer,MAXBUF,"K %s %s :%s",user->nick,u->nick,killreason);
382                         NetSendToAll(buffer);
383                         
384                         user_hash::iterator iter = clientlist.find(u->nick);
385                         if (iter != clientlist.end())
386                         {
387                                 log(DEBUG,"deleting user hash value %d",iter->second);
388                                 clientlist.erase(iter);
389                         }
390                         if (u->registered == 7)
391                         {
392                                 purge_empty_chans(u);
393                         }
394                         delete u;
395                 }
396                 else
397                 {
398                         // local kill
399                         log(DEFAULT,"LOCAL KILL: %s :%s!%s!%s (%s)", u->nick, ServerName,user->dhost,user->nick,parameters[1]);
400                         WriteTo(user, u, "KILL %s :%s!%s!%s (%s)", u->nick, ServerName,user->dhost,user->nick,parameters[1]);
401                         WriteOpers("*** Local Kill by %s: %s!%s@%s (%s)",user->nick,u->nick,u->ident,u->host,parameters[1]);
402                         snprintf(killreason,MAXBUF,"Killed (%s (%s))",user->nick,parameters[1]);
403                         kill_link(u,killreason);
404                 }
405         }
406         else
407         {
408                 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[0]);
409         }
410 }
411
412 void handle_summon(char **parameters, int pcnt, userrec *user)
413 {
414         WriteServ(user->fd,"445 %s :SUMMON has been disabled (depreciated command)",user->nick);
415 }
416
417 void handle_users(char **parameters, int pcnt, userrec *user)
418 {
419         WriteServ(user->fd,"445 %s :USERS has been disabled (depreciated command)",user->nick);
420 }
421
422 void handle_pass(char **parameters, int pcnt, userrec *user)
423 {
424         // Check to make sure they havnt registered -- Fix by FCS
425         if (user->registered == 7)
426         {
427                 WriteServ(user->fd,"462 %s :You may not reregister",user->nick);
428                 return;
429         }
430         strlcpy(user->password,parameters[0],MAXBUF);
431         if (!strcasecmp(parameters[0],Passwd(user)))
432         {
433                 user->haspassed = true;
434         }
435 }
436
437 void handle_invite(char **parameters, int pcnt, userrec *user)
438 {
439         userrec* u = Find(parameters[0]);
440         chanrec* c = FindChan(parameters[1]);
441
442         if ((!c) || (!u))
443         {
444                 if (!c)
445                 {
446                         WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[1]);
447                 }
448                 else
449                 {
450                         if (c->inviteonly)
451                         {
452                                 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[0]);
453                         }
454                 }
455
456                 return;
457         }
458
459         if (c->inviteonly)
460         {
461                 if (cstatus(user,c) < STATUS_HOP)
462                 {
463                         WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",user->nick, c->name);
464                         return;
465                 }
466         }
467         if (has_channel(u,c))
468         {
469                 WriteServ(user->fd,"443 %s %s %s :Is already on channel %s",user->nick,u->nick,c->name,c->name);
470                 return;
471         }
472         if (!has_channel(user,c))
473         {
474                 WriteServ(user->fd,"442 %s %s :You're not on that channel!",user->nick, c->name);
475                 return;
476         }
477
478         int MOD_RESULT = 0;
479         FOREACH_RESULT(OnUserPreInvite(user,u,c));
480         if (MOD_RESULT == 1) {
481                 return;
482         }
483
484         u->InviteTo(c->name);
485         WriteFrom(u->fd,user,"INVITE %s :%s",u->nick,c->name);
486         WriteServ(user->fd,"341 %s %s %s",user->nick,u->nick,c->name);
487         
488         // i token must go to ALL servers!!!
489         char buffer[MAXBUF];
490         snprintf(buffer,MAXBUF,"i %s %s %s",u->nick,user->nick,c->name);
491         NetSendToAll(buffer);
492 }
493
494 void handle_topic(char **parameters, int pcnt, userrec *user)
495 {
496         chanrec* Ptr;
497
498         if (pcnt == 1)
499         {
500                 if (strlen(parameters[0]) <= CHANMAX)
501                 {
502                         Ptr = FindChan(parameters[0]);
503                         if (Ptr)
504                         {
505                                 if (((Ptr) && (!has_channel(user,Ptr))) && (Ptr->secret))
506                                 {
507                                         WriteServ(user->fd,"442 %s %s :You're not on that channel!",user->nick, Ptr->name);
508                                         return;
509                                 }
510                                 if (Ptr->topicset)
511                                 {
512                                         WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
513                                         WriteServ(user->fd,"333 %s %s %s %d", user->nick, Ptr->name, Ptr->setby, Ptr->topicset);
514                                 }
515                                 else
516                                 {
517                                         WriteServ(user->fd,"331 %s %s :No topic is set.", user->nick, Ptr->name);
518                                 }
519                         }
520                         else
521                         {
522                                 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[0]);
523                         }
524                 }
525                 return;
526         }
527         else if (pcnt>1)
528         {
529                 if (strlen(parameters[0]) <= CHANMAX)
530                 {
531                         Ptr = FindChan(parameters[0]);
532                         if (Ptr)
533                         {
534                                 if ((Ptr) && (!has_channel(user,Ptr)))
535                                 {
536                                         WriteServ(user->fd,"442 %s %s :You're not on that channel!",user->nick, Ptr->name);
537                                         return;
538                                 }
539                                 if ((Ptr->topiclock) && (cstatus(user,Ptr)<STATUS_HOP))
540                                 {
541                                         WriteServ(user->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel", user->nick, Ptr->name);
542                                         return;
543                                 }
544
545                                 char topic[MAXBUF];
546                                 strlcpy(topic,parameters[1],MAXBUF);
547                                 if (strlen(topic)>MAXTOPIC)
548                                 {
549                                         topic[MAXTOPIC-1] = '\0';
550                                 }
551
552                                 if (!strcasecmp(user->server,ServerName))
553                                 {
554                                         int MOD_RESULT = 0;
555                                         FOREACH_RESULT(OnLocalTopicChange(user,Ptr,topic));
556                                         if (MOD_RESULT)
557                                                 return;
558                                 }
559
560                                 strlcpy(Ptr->topic,topic,MAXBUF);
561                                 strlcpy(Ptr->setby,user->nick,NICKMAX);
562                                 Ptr->topicset = TIME;
563                                 WriteChannel(Ptr,user,"TOPIC %s :%s",Ptr->name, Ptr->topic);
564
565                                 // t token must go to ALL servers!!!
566                                 char buffer[MAXBUF];
567                                 snprintf(buffer,MAXBUF,"t %s %s :%s",user->nick,Ptr->name,topic);
568                                 NetSendToAll(buffer);
569                         }
570                         else
571                         {
572                                 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[0]);
573                         }
574                 }
575         }
576 }
577
578 void handle_names(char **parameters, int pcnt, userrec *user)
579 {
580         chanrec* c;
581
582         if (!pcnt)
583         {
584                 WriteServ(user->fd,"366 %s * :End of /NAMES list.",user->nick);
585                 return;
586         }
587
588         if (loop_call(handle_names,parameters,pcnt,user,0,pcnt-1,0))
589                 return;
590         c = FindChan(parameters[0]);
591         if (c)
592         {
593                 if (((c) && (!has_channel(user,c))) && (c->secret))
594                 {
595                       WriteServ(user->fd,"442 %s %s :You're not on that channel!",user->nick, c->name);
596                       return;
597                 }
598                 userlist(user,c);
599                 WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, c->name);
600         }
601         else
602         {
603                 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[0]);
604         }
605 }
606
607 void handle_privmsg(char **parameters, int pcnt, userrec *user)
608 {
609         userrec *dest;
610         chanrec *chan;
611
612         user->idle_lastmsg = TIME;
613         
614         if (loop_call(handle_privmsg,parameters,pcnt,user,0,pcnt-2,0))
615                 return;
616         if (parameters[0][0] == '#')
617         {
618                 chan = FindChan(parameters[0]);
619                 if (chan)
620                 {
621                         if ((chan->noexternal) && (!has_channel(user,chan)))
622                         {
623                                 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
624                                 return;
625                         }
626                         if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
627                         {
628                                 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
629                                 return;
630                         }
631                         
632                         int MOD_RESULT = 0;
633
634                         std::string temp = parameters[1];
635                         FOREACH_RESULT(OnUserPreMessage(user,chan,TYPE_CHANNEL,temp));
636                         if (MOD_RESULT) {
637                                 return;
638                         }
639                         parameters[1] = (char*)temp.c_str();
640                         
641                         ChanExceptSender(chan, user, "PRIVMSG %s :%s", chan->name, parameters[1]);
642                         
643                         // if any users of this channel are on remote servers, broadcast the packet
644                         char buffer[MAXBUF];
645                         snprintf(buffer,MAXBUF,"P %s %s :%s",user->nick,chan->name,parameters[1]);
646                         NetSendToCommon(user,buffer);
647                 }
648                 else
649                 {
650                         /* no such nick/channel */
651                         WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[0]);
652                 }
653                 return;
654         }
655         
656         dest = Find(parameters[0]);
657         if (dest)
658         {
659                 if (strcmp(dest->awaymsg,""))
660                 {
661                         /* auto respond with aweh msg */
662                         WriteServ(user->fd,"301 %s %s :%s",user->nick,dest->nick,dest->awaymsg);
663                 }
664
665                 int MOD_RESULT = 0;
666                 
667                 std::string temp = parameters[1];
668                 FOREACH_RESULT(OnUserPreMessage(user,dest,TYPE_USER,temp));
669                 if (MOD_RESULT) {
670                         return;
671                 }
672                 parameters[1] = (char*)temp.c_str();
673
674
675
676                 if (!strcmp(dest->server,user->server))
677                 {
678                         // direct write, same server
679                         WriteTo(user, dest, "PRIVMSG %s :%s", dest->nick, parameters[1]);
680                 }
681                 else
682                 {
683                         char buffer[MAXBUF];
684                         snprintf(buffer,MAXBUF,"P %s %s :%s",user->nick,dest->nick,parameters[1]);
685                         NetSendToOne(dest->server,buffer);
686                 }
687         }
688         else
689         {
690                 /* no such nick/channel */
691                 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[0]);
692         }
693 }
694
695 void handle_notice(char **parameters, int pcnt, userrec *user)
696 {
697         userrec *dest;
698         chanrec *chan;
699
700         user->idle_lastmsg = TIME;
701         
702         if (loop_call(handle_notice,parameters,pcnt,user,0,pcnt-2,0))
703                 return;
704         if (parameters[0][0] == '#')
705         {
706                 chan = FindChan(parameters[0]);
707                 if (chan)
708                 {
709                         if ((chan->noexternal) && (!has_channel(user,chan)))
710                         {
711                                 WriteServ(user->fd,"404 %s %s :Cannot send to channel (no external messages)", user->nick, chan->name);
712                                 return;
713                         }
714                         if ((chan->moderated) && (cstatus(user,chan)<STATUS_VOICE))
715                         {
716                                 WriteServ(user->fd,"404 %s %s :Cannot send to channel (+m)", user->nick, chan->name);
717                                 return;
718                         }
719
720                         int MOD_RESULT = 0;
721
722                         std::string temp = parameters[1];
723                         FOREACH_RESULT(OnUserPreNotice(user,chan,TYPE_CHANNEL,temp));
724                         if (MOD_RESULT) {
725                                 return;
726                         }
727                         parameters[1] = (char*)temp.c_str();
728
729                         ChanExceptSender(chan, user, "NOTICE %s :%s", chan->name, parameters[1]);
730
731                         // if any users of this channel are on remote servers, broadcast the packet
732                         char buffer[MAXBUF];
733                         snprintf(buffer,MAXBUF,"V %s %s :%s",user->nick,chan->name,parameters[1]);
734                         NetSendToCommon(user,buffer);
735                 }
736                 else
737                 {
738                         /* no such nick/channel */
739                         WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[0]);
740                 }
741                 return;
742         }
743         
744         dest = Find(parameters[0]);
745         if (dest)
746         {
747                 int MOD_RESULT = 0;
748                 
749                 std::string temp = parameters[1];
750                 FOREACH_RESULT(OnUserPreNotice(user,dest,TYPE_USER,temp));
751                 if (MOD_RESULT) {
752                         return;
753                 }
754                 parameters[1] = (char*)temp.c_str();
755
756                 if (!strcmp(dest->server,user->server))
757                 {
758                         // direct write, same server
759                         WriteTo(user, dest, "NOTICE %s :%s", dest->nick, parameters[1]);
760                 }
761                 else
762                 {
763                         char buffer[MAXBUF];
764                         snprintf(buffer,MAXBUF,"V %s %s :%s",user->nick,dest->nick,parameters[1]);
765                         NetSendToOne(dest->server,buffer);
766                 }
767         }
768         else
769         {
770                 /* no such nick/channel */
771                 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[0]);
772         }
773 }
774
775 void handle_server(char **parameters, int pcnt, userrec *user)
776 {
777         WriteServ(user->fd,"666 %s :You cannot identify as a server, you are a USER. IRC Operators informed.",user->nick);
778         WriteOpers("*** WARNING: %s attempted to issue a SERVER command and is registered as a user!",user->nick);
779 }
780
781 void handle_info(char **parameters, int pcnt, userrec *user)
782 {
783         WriteServ(user->fd,"371 %s :. o O (The Inspire Internet Relay Chat Server) O o .",user->nick);
784         WriteServ(user->fd,"371 %s : ",user->nick);
785         WriteServ(user->fd,"371 %s :Core developers: Craig Edwards (Brain)",user->nick);
786         WriteServ(user->fd,"371 %s :                 Craig McLure",user->nick);
787         WriteServ(user->fd,"371 %s : ",user->nick);
788         WriteServ(user->fd,"371 %s :Contributors:    typobox43",user->nick);
789         WriteServ(user->fd,"371 %s :                 w00t",user->nick);
790         WriteServ(user->fd,"371 %s :                 Om",user->nick);
791         WriteServ(user->fd,"371 %s :                 Jazza",user->nick);
792         WriteServ(user->fd,"371 %s : ",user->nick);
793         WriteServ(user->fd,"371 %s :Testers:         CC",user->nick);
794         WriteServ(user->fd,"371 %s :                 Piggles",user->nick);
795         WriteServ(user->fd,"371 %s :                 Foamy",user->nick);
796         WriteServ(user->fd,"371 %s :                 Hart",user->nick);
797         WriteServ(user->fd,"371 %s :                 RageD",user->nick);
798         WriteServ(user->fd,"371 %s :                 [ed]",user->nick);
799         WriteServ(user->fd,"371 %s :                 Azhrarn",user->nick);
800         WriteServ(user->fd,"371 %s :                 nenolod",user->nick);
801         WriteServ(user->fd,"371 %s :                 luigiman",user->nick);
802         WriteServ(user->fd,"371 %s :                 Chu",user->nick);
803         WriteServ(user->fd,"371 %s :                 aquanight",user->nick);
804         WriteServ(user->fd,"371 %s :                 xptek",user->nick);
805         WriteServ(user->fd,"371 %s :                 Grantlinks",user->nick);
806         WriteServ(user->fd,"371 %s :                 Rob",user->nick);
807         WriteServ(user->fd,"371 %s :                 angelic",user->nick);
808         WriteServ(user->fd,"371 %s :                 Jason",user->nick);
809         WriteServ(user->fd,"371 %s : ",user->nick);
810         WriteServ(user->fd,"371 %s :Thanks to irc-junkie and searchirc",user->nick);
811         WriteServ(user->fd,"371 %s :for the nice comments and the help",user->nick);
812         WriteServ(user->fd,"371 %s :you gave us in attracting users to",user->nick);
813         WriteServ(user->fd,"371 %s :this software.",user->nick);
814         WriteServ(user->fd,"371 %s : ",user->nick);
815         WriteServ(user->fd,"371 %s :Best experienced with: An IRC client.",user->nick);
816         FOREACH_MOD OnInfo(user);
817         WriteServ(user->fd,"374 %s :End of /INFO list",user->nick);
818 }
819
820 void handle_time(char **parameters, int pcnt, userrec *user)
821 {
822         time_t rawtime;
823         struct tm * timeinfo;
824
825         time ( &rawtime );
826         timeinfo = localtime ( &rawtime );
827         WriteServ(user->fd,"391 %s %s :%s",user->nick,ServerName, asctime (timeinfo) );
828   
829 }
830
831 void handle_whois(char **parameters, int pcnt, userrec *user)
832 {
833         userrec *dest;
834
835         if (loop_call(handle_whois,parameters,pcnt,user,0,pcnt-1,0))
836                 return;
837         dest = Find(parameters[0]);
838         if (dest)
839         {
840                 // bug found by phidjit - were able to whois an incomplete connection if it had sent a NICK or USER
841                 if (dest->registered == 7)
842                 {
843                         WriteServ(user->fd,"311 %s %s %s %s * :%s",user->nick, dest->nick, dest->ident, dest->dhost, dest->fullname);
844                         if ((user == dest) || (strchr(user->modes,'o')))
845                         {
846                                 WriteServ(user->fd,"378 %s %s :is connecting from *@%s",user->nick, dest->nick, dest->host);
847                         }
848                         if (strcmp(chlist(dest),""))
849                         {
850                                 WriteServ(user->fd,"319 %s %s :%s",user->nick, dest->nick, chlist(dest));
851                         }
852                         WriteServ(user->fd,"312 %s %s %s :%s",user->nick, dest->nick, dest->server, GetServerDescription(dest->server).c_str());
853                         if (strcmp(dest->awaymsg,""))
854                         {
855                                 WriteServ(user->fd,"301 %s %s :%s",user->nick, dest->nick, dest->awaymsg);
856                         }
857                         if ((strchr(dest->modes,'o')) && (strcmp(dest->oper,"")))
858                         {
859                                 WriteServ(user->fd,"313 %s %s :is %s %s on %s",user->nick, dest->nick,
860                                 (strchr("aeiou",dest->oper[0]) ? "an" : "a"),dest->oper, Network);
861                         }
862                         FOREACH_MOD OnWhois(user,dest);
863                         if (!strcasecmp(user->server,dest->server))
864                         {
865                                 // idle time and signon line can only be sent if youre on the same server (according to RFC)
866                                 WriteServ(user->fd,"317 %s %s %d %d :seconds idle, signon time",user->nick, dest->nick, abs((dest->idle_lastmsg)-TIME), dest->signon);
867                         }
868                         
869                         WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, dest->nick);
870                 }
871                 else
872                 {
873                         WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[0]);
874                 }
875         }
876         else
877         {
878                 /* no such nick/channel */
879                 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[0]);
880         }
881 }
882
883 void handle_quit(char **parameters, int pcnt, userrec *user)
884 {
885         user_hash::iterator iter = clientlist.find(user->nick);
886         char* reason;
887
888         if (user->registered == 7)
889         {
890                 /* theres more to do here, but for now just close the socket */
891                 if (pcnt == 1)
892                 {
893                         if (parameters[0][0] == ':')
894                         {
895                                 *parameters[0]++;
896                         }
897                         reason = parameters[0];
898
899                         if (strlen(reason)>MAXQUIT)
900                         {
901                                 reason[MAXQUIT-1] = '\0';
902                         }
903
904                         Write(user->fd,"ERROR :Closing link (%s@%s) [%s%s]",user->ident,user->host,PrefixQuit,parameters[0]);
905                         WriteOpers("*** Client exiting: %s!%s@%s [%s%s]",user->nick,user->ident,user->host,PrefixQuit,parameters[0]);
906                         WriteCommonExcept(user,"QUIT :%s%s",PrefixQuit,parameters[0]);
907
908                         char buffer[MAXBUF];
909                         snprintf(buffer,MAXBUF,"Q %s :%s%s",user->nick,PrefixQuit,parameters[0]);
910                         NetSendToAll(buffer);
911                 }
912                 else
913                 {
914                         Write(user->fd,"ERROR :Closing link (%s@%s) [QUIT]",user->ident,user->host);
915                         WriteOpers("*** Client exiting: %s!%s@%s [Client exited]",user->nick,user->ident,user->host);
916                         WriteCommonExcept(user,"QUIT :Client exited");
917
918                         char buffer[MAXBUF];
919                         snprintf(buffer,MAXBUF,"Q %s :Client exited",user->nick);
920                         NetSendToAll(buffer);
921                 }
922                 FOREACH_MOD OnUserQuit(user);
923                 AddWhoWas(user);
924         }
925
926         FOREACH_MOD OnUserDisconnect(user);
927
928         /* push the socket on a stack of sockets due to be closed at the next opportunity */
929         if (user->fd > -1)
930         {
931                 shutdown(user->fd,2);
932                 close(user->fd);
933         }
934         
935         if (iter != clientlist.end())
936         {
937                 clientlist.erase(iter);
938         }
939
940         if (user->registered == 7) {
941                 purge_empty_chans(user);
942         }
943         delete user;
944 }
945
946 void handle_who(char **parameters, int pcnt, userrec *user)
947 {
948         chanrec* Ptr = NULL;
949         char tmp[10];
950         
951         /* theres more to do here, but for now just close the socket */
952         if (pcnt == 1)
953         {
954                 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")))
955                 {
956                         if (user->chans[0].channel)
957                         {
958                                 int n_list = 0;
959                                 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
960                                 {
961                                         Ptr = i->second->chans[0].channel;
962                                         // suggested by phidjit and FCS
963                                         if ((!common_channels(user,i->second)) && (isnick(i->second->nick)))
964                                         {
965                                                 // Bug Fix #29
966                                                 strcpy(tmp, "");
967                                                 if (strcmp(i->second->awaymsg, "")) {
968                                                         strncat(tmp, "G", 9);
969                                                 } else {
970                                                         strncat(tmp, "H", 9);
971                                                 }
972                                                 if (strchr(i->second->modes,'o')) { strncat(tmp, "*", 9); }
973                                                 WriteServ(user->fd,"352 %s %s %s %s %s %s %s :0 %s",user->nick, Ptr ? Ptr->name : "*", i->second->ident, i->second->dhost, i->second->server, i->second->nick, tmp, i->second->fullname);
974                                                 n_list++;
975                                                 if (n_list > MaxWhoResults)
976                                                         break;
977                                         }
978                                 }
979                         }
980                         if (Ptr)
981                         {
982                                 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick , parameters[0]);
983                         }
984                         else
985                         {
986                                 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, parameters[0]);
987                         }
988                         return;
989                 }
990                 if (parameters[0][0] == '#')
991                 {
992                         Ptr = FindChan(parameters[0]);
993                         if (Ptr)
994                         {
995                                 for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
996                                 {
997                                         if ((has_channel(i->second,Ptr)) && (isnick(i->second->nick)))
998                                         {
999                                                 // Fix Bug #29 - Part 2..
1000                                                 strcpy(tmp, "");
1001                                                 if (strcmp(i->second->awaymsg, "")) {
1002                                                         strncat(tmp, "G", 9);
1003                                                 } else {
1004                                                         strncat(tmp, "H", 9);
1005                                                 }
1006                                                 if (strchr(i->second->modes,'o')) { strncat(tmp, "*", 9); }
1007                                                 strcat(tmp, cmode(i->second, Ptr));
1008                                                 WriteServ(user->fd,"352 %s %s %s %s %s %s %s :0 %s",user->nick, Ptr->name, i->second->ident, i->second->dhost, i->second->server, i->second->nick, tmp, i->second->fullname);
1009                                         }
1010                                 }
1011                                 WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, parameters[0]);
1012                         }
1013                         else
1014                         {
1015                                 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[0]);
1016                         }
1017                 }
1018                 else
1019                 {
1020                         userrec* u = Find(parameters[0]);
1021                         if (u)
1022                         {
1023                                 // Bug Fix #29 -- Part 29..
1024                                 strcpy(tmp, "");
1025                                 if (strcmp(u->awaymsg, "")) {
1026                                         strncat(tmp, "G" ,9);
1027                                 } else {
1028                                         strncat(tmp, "H" ,9);
1029                                 }
1030                                 if (strchr(u->modes,'o')) { strncat(tmp, "*" ,9); }
1031                                 WriteServ(user->fd,"352 %s %s %s %s %s %s %s :0 %s",user->nick, u->nick, u->ident, u->dhost, u->server, u->nick, tmp, u->fullname);
1032                         }
1033                         WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, parameters[0]);
1034                 }
1035         }
1036         if (pcnt == 2)
1037         {
1038                 if ((!strcmp(parameters[0],"0")) || (!strcmp(parameters[0],"*")) && (!strcmp(parameters[1],"o")))
1039                 {
1040                         for (user_hash::const_iterator i = clientlist.begin(); i != clientlist.end(); i++)
1041                         {
1042                                 if ((common_channels(user,i->second)) && (isnick(i->second->nick)))
1043                                 {
1044                                         if (strchr(i->second->modes,'o'))
1045                                         {
1046                                                 // If i were a rich man.. I wouldn't need to me making these bugfixes..
1047                                                 // But i'm a poor bastard with nothing better to do.
1048                                                 strcpy(tmp, "");
1049                                                 if (strcmp(i->second->awaymsg, "")) {
1050                                                         strncat(tmp, "G" ,9);
1051                                                 } else {
1052                                                         strncat(tmp, "H" ,9);
1053                                                 }
1054
1055                                                 WriteServ(user->fd,"352 %s %s %s %s %s %s %s* :0 %s",user->nick, user->nick, i->second->ident, i->second->dhost, i->second->server, i->second->nick, tmp, i->second->fullname);
1056                                         }
1057                                 }
1058                         }
1059                         WriteServ(user->fd,"315 %s %s :End of /WHO list.",user->nick, parameters[0]);
1060                         return;
1061                 }
1062         }
1063 }
1064
1065 void handle_wallops(char **parameters, int pcnt, userrec *user)
1066 {
1067         WriteWallOps(user,false,"%s",parameters[0]);
1068 }
1069
1070 void handle_list(char **parameters, int pcnt, userrec *user)
1071 {
1072         WriteServ(user->fd,"321 %s Channel :Users Name",user->nick);
1073         for (chan_hash::const_iterator i = chanlist.begin(); i != chanlist.end(); i++)
1074         {
1075                 if ((!i->second->c_private) && (!i->second->secret))
1076                 {
1077                         WriteServ(user->fd,"322 %s %s %d :[+%s] %s",user->nick,i->second->name,usercount_i(i->second),chanmodes(i->second),i->second->topic);
1078                 }
1079         }
1080         WriteServ(user->fd,"323 %s :End of channel list.",user->nick);
1081 }
1082
1083
1084 void handle_rehash(char **parameters, int pcnt, userrec *user)
1085 {
1086         WriteServ(user->fd,"382 %s %s :Rehashing",user->nick,CleanFilename(CONFIG_FILE));
1087         ReadConfig(false,user);
1088         FOREACH_MOD OnRehash();
1089         WriteOpers("%s is rehashing config file %s",user->nick,CleanFilename(CONFIG_FILE));
1090 }
1091
1092 void handle_lusers(char **parameters, int pcnt, userrec *user)
1093 {
1094         WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),servercount());
1095         WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
1096         WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
1097         WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
1098         WriteServ(user->fd,"254 %s :I have %d clients and %d servers",user->nick,local_count(),count_servs());
1099 }
1100
1101 void handle_admin(char **parameters, int pcnt, userrec *user)
1102 {
1103         WriteServ(user->fd,"256 %s :Administrative info for %s",user->nick,ServerName);
1104         WriteServ(user->fd,"257 %s :Name     - %s",user->nick,AdminName);
1105         WriteServ(user->fd,"258 %s :Nickname - %s",user->nick,AdminNick);
1106         WriteServ(user->fd,"258 %s :E-Mail   - %s",user->nick,AdminEmail);
1107 }
1108
1109 void handle_ping(char **parameters, int pcnt, userrec *user)
1110 {
1111         WriteServ(user->fd,"PONG %s :%s",ServerName,parameters[0]);
1112 }
1113
1114 void handle_pong(char **parameters, int pcnt, userrec *user)
1115 {
1116         // set the user as alive so they survive to next ping
1117         user->lastping = 1;
1118 }
1119
1120 void handle_motd(char **parameters, int pcnt, userrec *user)
1121 {
1122         ShowMOTD(user);
1123 }
1124
1125 void handle_rules(char **parameters, int pcnt, userrec *user)
1126 {
1127         ShowRULES(user);
1128 }
1129
1130 void handle_user(char **parameters, int pcnt, userrec *user)
1131 {
1132         if (user->registered < 3)
1133         {
1134                 if (isident(parameters[0]) == 0) {
1135                         // This kinda Sucks, According to the RFC thou, its either this,
1136                         // or "You have already registered" :p -- Craig
1137                         WriteServ(user->fd,"461 %s USER :Not enough parameters",user->nick);
1138                 }
1139                 else {
1140                         strcpy(user->ident,"~"); /* we arent checking ident... but these days why bother anyway? */
1141                         strlcat(user->ident,parameters[0],IDENTMAX);
1142                         strlcpy(user->fullname,parameters[3],128);
1143                         user->registered = (user->registered | 1);
1144                 }
1145         }
1146         else
1147         {
1148                 WriteServ(user->fd,"462 %s :You may not reregister",user->nick);
1149                 return;
1150         }
1151         /* parameters 2 and 3 are local and remote hosts, ignored when sent by client connection */
1152         if (user->registered == 3)
1153         {
1154                 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
1155                 FOREACH_MOD OnUserRegister(user);
1156                 ConnectUser(user);
1157         }
1158 }
1159
1160 void handle_userhost(char **parameters, int pcnt, userrec *user)
1161 {
1162         char Return[MAXBUF],junk[MAXBUF];
1163         snprintf(Return,MAXBUF,"302 %s :",user->nick);
1164         for (int i = 0; i < pcnt; i++)
1165         {
1166                 userrec *u = Find(parameters[i]);
1167                 if (u)
1168                 {
1169                         if (strchr(u->modes,'o'))
1170                         {
1171                                 snprintf(junk,MAXBUF,"%s*=+%s@%s ",u->nick,u->ident,u->host);
1172                                 strlcat(Return,junk,MAXBUF);
1173                         }
1174                         else
1175                         {
1176                                 snprintf(junk,MAXBUF,"%s=+%s@%s ",u->nick,u->ident,u->host);
1177                                 strlcat(Return,junk,MAXBUF);
1178                         }
1179                 }
1180         }
1181         WriteServ(user->fd,Return);
1182 }
1183
1184
1185 void handle_ison(char **parameters, int pcnt, userrec *user)
1186 {
1187         char Return[MAXBUF];
1188         snprintf(Return,MAXBUF,"303 %s :",user->nick);
1189         for (int i = 0; i < pcnt; i++)
1190         {
1191                 userrec *u = Find(parameters[i]);
1192                 if (u)
1193                 {
1194                         strlcat(Return,u->nick,MAXBUF);
1195                         strlcat(Return," ",MAXBUF);
1196                 }
1197         }
1198         WriteServ(user->fd,Return);
1199 }
1200
1201
1202 void handle_away(char **parameters, int pcnt, userrec *user)
1203 {
1204         if (pcnt)
1205         {
1206                 strlcpy(user->awaymsg,parameters[0],512);
1207                 WriteServ(user->fd,"306 %s :You have been marked as being away",user->nick);
1208         }
1209         else
1210         {
1211                 strlcpy(user->awaymsg,"",512);
1212                 WriteServ(user->fd,"305 %s :You are no longer marked as being away",user->nick);
1213         }
1214 }
1215
1216 void handle_whowas(char **parameters, int pcnt, userrec* user)
1217 {
1218         user_hash::iterator i = whowas.find(parameters[0]);
1219
1220         if (i == whowas.end())
1221         {
1222                 WriteServ(user->fd,"406 %s %s :There was no such nickname",user->nick,parameters[0]);
1223                 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
1224         }
1225         else
1226         {
1227                 time_t rawtime = i->second->signon;
1228                 tm *timeinfo;
1229                 char b[MAXBUF];
1230                 
1231                 timeinfo = localtime(&rawtime);
1232                 strlcpy(b,asctime(timeinfo),MAXBUF);
1233                 b[strlen(b)-1] = '\0';
1234                 
1235                 WriteServ(user->fd,"314 %s %s %s %s * :%s",user->nick,i->second->nick,i->second->ident,i->second->dhost,i->second->fullname);
1236                 WriteServ(user->fd,"312 %s %s %s :%s",user->nick,i->second->nick,i->second->server,b);
1237                 WriteServ(user->fd,"369 %s %s :End of WHOWAS",user->nick,parameters[0]);
1238         }
1239
1240 }
1241
1242 void handle_trace(char **parameters, int pcnt, userrec *user)
1243 {
1244         for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
1245         {
1246                 if (i->second)
1247                 {
1248                         if (isnick(i->second->nick))
1249                         {
1250                                 if (strchr(i->second->modes,'o'))
1251                                 {
1252                                         WriteServ(user->fd,"205 %s :Oper 0 %s",user->nick,i->second->nick);
1253                                 }
1254                                 else
1255                                 {
1256                                         WriteServ(user->fd,"204 %s :User 0 %s",user->nick,i->second->nick);
1257                                 }
1258                         }
1259                         else
1260                         {
1261                                 WriteServ(user->fd,"203 %s :???? 0 [%s]",user->nick,i->second->host);
1262                         }
1263                 }
1264         }
1265 }
1266
1267 void handle_modules(char **parameters, int pcnt, userrec *user)
1268 {
1269         for (int i = 0; i < module_names.size(); i++)
1270         {
1271                 Version V = modules[i]->GetVersion();
1272                 char modulename[MAXBUF];
1273                 char flagstate[MAXBUF];
1274                 strcpy(flagstate,"");
1275                 if (V.Flags & VF_STATIC)
1276                         strlcat(flagstate,", static",MAXBUF);
1277                 if (V.Flags & VF_VENDOR)
1278                         strlcat(flagstate,", vendor",MAXBUF);
1279                 if (V.Flags & VF_COMMON)
1280                         strlcat(flagstate,", common",MAXBUF);
1281                 if (V.Flags & VF_SERVICEPROVIDER)
1282                         strlcat(flagstate,", service provider",MAXBUF);
1283                 if (!flagstate[0])
1284                         strcpy(flagstate,"  <no flags>");
1285                 strlcpy(modulename,module_names[i].c_str(),256);
1286                 if (strchr(user->modes,'o'))
1287                 {
1288                         WriteServ(user->fd,"900 %s :0x%08lx %d.%d.%d.%d %s (%s)",user->nick,modules[i],V.Major,V.Minor,V.Revision,V.Build,CleanFilename(modulename),flagstate+2);
1289                 }
1290                 else
1291                 {
1292                         WriteServ(user->fd,"900 %s :%s",user->nick,CleanFilename(modulename));
1293                 }
1294         }
1295         WriteServ(user->fd,"901 %s :End of MODULES list",user->nick);
1296 }
1297
1298 void handle_stats(char **parameters, int pcnt, userrec *user)
1299 {
1300         char Link_ServerName[MAXBUF],Link_IPAddr[MAXBUF],Link_Port[MAXBUF];
1301         if (pcnt != 1)
1302         {
1303                 return;
1304         }
1305         if (strlen(parameters[0])>1)
1306         {
1307                 /* make the stats query 1 character long */
1308                 parameters[0][1] = '\0';
1309         }
1310
1311
1312         FOREACH_MOD OnStats(*parameters[0]);
1313
1314         if (*parameters[0] == 'c')
1315         {
1316                 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
1317                 {
1318                         ConfValue("link","name",i,Link_ServerName,&config_f);
1319                         ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
1320                         ConfValue("link","port",i,Link_Port,&config_f);
1321                         WriteServ(user->fd,"213 %s C *@%s * %s %s 0 M",user->nick,Link_IPAddr,Link_ServerName,Link_Port);
1322                         WriteServ(user->fd,"244 %s H * * %s",user->nick,Link_ServerName);
1323                 }
1324         }
1325         
1326         if (*parameters[0] == 'i')
1327         {
1328                 int idx = 0;
1329                 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1330                 {
1331                         WriteServ(user->fd,"215 %s I * * * %d %d %s *",user->nick,MAXCLIENTS,idx,ServerName);
1332                         idx++;
1333                 }
1334         }
1335         
1336         if (*parameters[0] == 'y')
1337         {
1338                 int idx = 0;
1339                 for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1340                 {
1341                         WriteServ(user->fd,"218 %s Y %d %d 0 %d %d",user->nick,idx,120,i->flood,i->registration_timeout);
1342                         idx++;
1343                 }
1344         }
1345
1346         if (*parameters[0] == 'U')
1347         {
1348                 for (int i = 0; i < ConfValueEnum("uline",&config_f); i++)
1349                 {
1350                         ConfValue("uline","server",i,Link_ServerName,&config_f);
1351                         WriteServ(user->fd,"248 %s U %s",user->nick,Link_ServerName);
1352                 }
1353         }
1354         
1355         if (*parameters[0] == 'P')
1356         {
1357                 int idx = 0;
1358                 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
1359                 {
1360                         if (strchr(i->second->modes,'o'))
1361                         {
1362                                 WriteServ(user->fd,"249 %s :%s (%s@%s) Idle: %d",user->nick,i->second->nick,i->second->ident,i->second->dhost,(TIME - i->second->idle_lastmsg));
1363                                 idx++;
1364                         }
1365                 }
1366                 WriteServ(user->fd,"249 %s :%d OPER(s)",user->nick,idx);
1367         //249 [Brain] :bwoadway-monitor (~wgmon@204.152.186.58) Idle: 18
1368         }
1369         
1370         if (*parameters[0] == 'k')
1371         {
1372                 stats_k(user);
1373         }
1374
1375         if (*parameters[0] == 'g')
1376         {
1377                 stats_g(user);
1378         }
1379
1380         if (*parameters[0] == 'q')
1381         {
1382                 stats_q(user);
1383         }
1384
1385         if (*parameters[0] == 'Z')
1386         {
1387                 stats_z(user);
1388         }
1389
1390         if (*parameters[0] == 'e')
1391         {
1392                 stats_e(user);
1393         }
1394
1395         /* stats m (list number of times each command has been used, plus bytecount) */
1396         if (*parameters[0] == 'm')
1397         {
1398                 for (int i = 0; i < cmdlist.size(); i++)
1399                 {
1400                         if (cmdlist[i].handler_function)
1401                         {
1402                                 if (cmdlist[i].use_count)
1403                                 {
1404                                         /* RPL_STATSCOMMANDS */
1405                                         WriteServ(user->fd,"212 %s %s %d %d",user->nick,cmdlist[i].command,cmdlist[i].use_count,cmdlist[i].total_bytes);
1406                                 }
1407                         }
1408                 }
1409                         
1410         }
1411
1412         /* stats z (debug and memory info) */
1413         if (*parameters[0] == 'z')
1414         {
1415                 WriteServ(user->fd,"249 %s :Users(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,clientlist.size(),clientlist.size()*sizeof(userrec),clientlist.bucket_count());
1416                 WriteServ(user->fd,"249 %s :Channels(HASH_MAP) %d (%d bytes, %d buckets)",user->nick,chanlist.size(),chanlist.size()*sizeof(chanrec),chanlist.bucket_count());
1417                 WriteServ(user->fd,"249 %s :Commands(VECTOR) %d (%d bytes)",user->nick,cmdlist.size(),cmdlist.size()*sizeof(command_t));
1418                 WriteServ(user->fd,"249 %s :MOTD(VECTOR) %d, RULES(VECTOR) %d",user->nick,MOTD.size(),RULES.size());
1419                 WriteServ(user->fd,"249 %s :address_cache(HASH_MAP) %d (%d buckets)",user->nick,IP.size(),IP.bucket_count());
1420                 WriteServ(user->fd,"249 %s :Modules(VECTOR) %d (%d)",user->nick,modules.size(),modules.size()*sizeof(Module));
1421                 WriteServ(user->fd,"249 %s :ClassFactories(VECTOR) %d (%d)",user->nick,factory.size(),factory.size()*sizeof(ircd_module));
1422                 WriteServ(user->fd,"249 %s :Ports(STATIC_ARRAY) %d",user->nick,boundPortCount);
1423         }
1424         
1425         /* stats o */
1426         if (*parameters[0] == 'o')
1427         {
1428                 for (int i = 0; i < ConfValueEnum("oper",&config_f); i++)
1429                 {
1430                         char LoginName[MAXBUF];
1431                         char HostName[MAXBUF];
1432                         char OperType[MAXBUF];
1433                         ConfValue("oper","name",i,LoginName,&config_f);
1434                         ConfValue("oper","host",i,HostName,&config_f);
1435                         ConfValue("oper","type",i,OperType,&config_f);
1436                         WriteServ(user->fd,"243 %s O %s * %s %s 0",user->nick,HostName,LoginName,OperType);
1437                 }
1438         }
1439         
1440         /* stats l (show user I/O stats) */
1441         if (*parameters[0] == 'l')
1442         {
1443                 WriteServ(user->fd,"211 %s :server:port nick bytes_in cmds_in bytes_out cmds_out",user->nick);
1444                 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); i++)
1445                 {
1446                         if (isnick(i->second->nick))
1447                         {
1448                                 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);
1449                         }
1450                         else
1451                         {
1452                                 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);
1453                         }
1454                         
1455                 }
1456         }
1457         
1458         /* stats u (show server uptime) */
1459         if (*parameters[0] == 'u')
1460         {
1461                 time_t current_time = 0;
1462                 current_time = TIME;
1463                 time_t server_uptime = current_time - startup_time;
1464                 struct tm* stime;
1465                 stime = gmtime(&server_uptime);
1466                 /* i dont know who the hell would have an ircd running for over a year nonstop, but
1467                  * Craig suggested this, and it seemed a good idea so in it went */
1468                 if (stime->tm_year > 70)
1469                 {
1470                         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);
1471                 }
1472                 else
1473                 {
1474                         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);
1475                 }
1476         }
1477
1478         WriteServ(user->fd,"219 %s %s :End of /STATS report",user->nick,parameters[0]);
1479         WriteOpers("*** Notice: Stats '%s' requested by %s (%s@%s)",parameters[0],user->nick,user->ident,user->host);
1480         
1481 }
1482
1483 void handle_connect(char **parameters, int pcnt, userrec *user)
1484 {
1485         char Link_ServerName[1024];
1486         char Link_IPAddr[1024];
1487         char Link_Port[1024];
1488         char Link_Pass[1024];
1489         int LinkPort;
1490         bool found = false;
1491
1492         for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
1493         {
1494                 if (!found)
1495                 {
1496                         ConfValue("link","name",i,Link_ServerName,&config_f);
1497                         ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
1498                         ConfValue("link","port",i,Link_Port,&config_f);
1499                         ConfValue("link","sendpass",i,Link_Pass,&config_f);
1500                         log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
1501                         LinkPort = atoi(Link_Port);
1502                         if (match(Link_ServerName,parameters[0])) {
1503                                 found = true;
1504                                 break;
1505                         }
1506                 }
1507         }
1508         
1509         if (!found) {
1510                 WriteServ(user->fd,"NOTICE %s :*** Failed to connect to %s: No servers matching this pattern are configured for linking.",user->nick,parameters[0]);
1511                 return;
1512         }
1513         
1514         // TODO: Perform a check here to stop a server being linked twice!
1515
1516         WriteServ(user->fd,"NOTICE %s :*** Connecting to %s (%s) port %s...",user->nick,Link_ServerName,Link_IPAddr,Link_Port);
1517
1518         if (me[defaultRoute])
1519         {
1520                 me[defaultRoute]->BeginLink(Link_IPAddr,LinkPort,Link_Pass,Link_ServerName,me[defaultRoute]->port);
1521                 return;
1522         }
1523         else
1524         {
1525                 WriteServ(user->fd,"NOTICE %s :No default route is defined for server connections on this server. You must define a server connection to be default route so that sockets can be bound to it.",user->nick);
1526         }
1527 }
1528
1529 void handle_squit(char **parameters, int pcnt, userrec *user)
1530 {
1531         // send out an squit across the mesh and then clear the server list (for local squit)
1532         if (!pcnt)
1533         {
1534                 WriteOpers("SQUIT command issued by %s",user->nick);
1535                 char buffer[MAXBUF];
1536                 snprintf(buffer,MAXBUF,"& %s",ServerName);
1537                 NetSendToAll(buffer);
1538                 DoSplitEveryone();
1539         }
1540         else
1541         {
1542                 if (!strcasecmp("*",parameters[0]))
1543                 {
1544                         WriteServ(user->fd,"NOTICE %s :*** You cannot issue an SQUIT this wide! If this is REALLY what you want, use a less wide mask.",user->nick);
1545                         WriteOpers("*** WARNING! %s tried to SQUIT all servers at once!",user->nick);
1546                         return;
1547                 }
1548                 if (!strcasecmp(ServerName,parameters[0]))
1549                 {
1550                         WriteServ(user->fd,"NOTICE %s :*** To take the local server out of the mesh, just use /SQUIT with no parameters instead.",user->nick);
1551                         return;
1552                 }
1553                 bool have_this_server = true;
1554                 int n_count = 0;
1555                 std::string server_to_squit = "";
1556                 while (have_this_server)
1557                 {
1558                         have_this_server = false;
1559                         for (int j = 0; j < 32; j++)
1560                         {
1561                                 if (me[j] != NULL)
1562                                 {
1563                                         for (int x = 0; x < me[j]->connectors.size(); x++)
1564                                         {
1565                                                 if (match(me[j]->connectors[x].GetServerName().c_str(),parameters[0]))
1566                                                 {
1567                                                         // found a valid ircd_connector.
1568                                                         have_this_server = true;
1569                                                         server_to_squit = me[j]->connectors[x].GetServerName().c_str();
1570                                                         break;
1571                                                 }
1572                                         }
1573                                 }
1574                         }
1575                         if (have_this_server)
1576                         {
1577                                 WriteOpers("SQUIT command issued by %s to remove %s from the mesh",user->nick,server_to_squit.c_str());
1578                                 WriteServ(user->fd,"NOTICE %s :*** Removing remote server %s.",user->nick,server_to_squit.c_str());
1579                                 char buffer[MAXBUF];
1580                                 snprintf(buffer,MAXBUF,"& %s",server_to_squit.c_str());
1581                                 NetSendToAll(buffer);
1582                                 DoSplit(server_to_squit.c_str());
1583                                 n_count++;
1584                         }
1585                 }
1586                 if (!n_count)
1587                 {
1588                         WriteServ(user->fd,"402 %s %s :Your pattern did not match any servers.",user->nick,parameters[0]);
1589                 }
1590         }
1591 }
1592
1593 void handle_links(char **parameters, int pcnt, userrec *user)
1594 {
1595         WriteServ(user->fd,"364 %s %s %s :0 %s",user->nick,ServerName,ServerName,ServerDesc);
1596         for (int j = 0; j < 32; j++)
1597         {
1598                 if (me[j] != NULL)
1599                 {
1600                         for (int k = 0; k < me[j]->connectors.size(); k++)
1601                         {
1602                                 WriteServ(user->fd,"364 %s %s %s :1 %s",user->nick,me[j]->connectors[k].GetServerName().c_str(),ServerName,me[j]->connectors[k].GetDescription().c_str());
1603                         }
1604                 }
1605         }
1606         WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
1607 }
1608
1609 void handle_map(char **parameters, int pcnt, userrec *user)
1610 {
1611         char line[MAXBUF];
1612         snprintf(line,MAXBUF,"006 %s :%s",user->nick,ServerName);
1613         while (strlen(line) < 50)
1614                 strcat(line," ");
1615         WriteServ(user->fd,"%s%d (%.2f%%)",line,local_count(),(float)(((float)local_count()/(float)registered_usercount())*100));
1616         for (int j = 0; j < 32; j++)
1617         {
1618                 if (me[j] != NULL)
1619                 {
1620                         for (int k = 0; k < me[j]->connectors.size(); k++)
1621                         {
1622                                 snprintf(line,MAXBUF,"006 %s :%c-%s",user->nick,islast(me[j]->connectors[k].GetServerName().c_str()),me[j]->connectors[k].GetServerName().c_str());
1623                                 while (strlen(line) < 50)
1624                                         strcat(line," ");
1625                                 WriteServ(user->fd,"%s%d (%.2f%%)",line,map_count(me[j]->connectors[k].GetServerName().c_str()),(float)(((float)map_count(me[j]->connectors[k].GetServerName().c_str())/(float)registered_usercount())*100));
1626                         }
1627                 }
1628         }
1629         WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
1630 }
1631
1632 bool is_uline(const char* server)
1633 {
1634         char ServName[MAXBUF];
1635         for (int i = 0; i < ConfValueEnum("uline",&config_f); i++)
1636         {
1637                 ConfValue("uline","server",i,ServName,&config_f);
1638                 if (!strcasecmp(server,ServName))
1639                 {
1640                         return true;
1641                 }
1642         }
1643         return false;
1644 }
1645 int operstrcmp(char* data,char* input)
1646 {
1647         int MOD_RESULT = 0;
1648         FOREACH_RESULT(OnOperCompare(data,input))
1649         log(DEBUG,"operstrcmp: %d",MOD_RESULT);
1650         if (MOD_RESULT == 1)
1651                 return 0;
1652         if (MOD_RESULT == -1)
1653                 return 1;
1654         log(DEBUG,"strcmp fallback: '%s' '%s' %d",data,input,strcmp(data,input));
1655         return strcmp(data,input);
1656 }
1657
1658 void handle_oper(char **parameters, int pcnt, userrec *user)
1659 {
1660         char LoginName[MAXBUF];
1661         char Password[MAXBUF];
1662         char OperType[MAXBUF];
1663         char TypeName[MAXBUF];
1664         char HostName[MAXBUF];
1665         char TheHost[MAXBUF];
1666         int j;
1667         bool found = false;
1668         bool fail2 = false;
1669         char global[MAXBUF];
1670
1671         snprintf(TheHost,MAXBUF,"%s@%s",user->ident,user->host);
1672
1673         for (int i = 0; i < ConfValueEnum("oper",&config_f); i++)
1674         {
1675                 ConfValue("oper","name",i,LoginName,&config_f);
1676                 ConfValue("oper","password",i,Password,&config_f);
1677                 ConfValue("oper","type",i,OperType,&config_f);
1678                 ConfValue("oper","host",i,HostName,&config_f);
1679                 if ((!strcmp(LoginName,parameters[0])) && (!operstrcmp(Password,parameters[1])) && (match(TheHost,HostName)))
1680                 {
1681                         fail2 = true;
1682                         for (j =0; j < ConfValueEnum("type",&config_f); j++)
1683                         {
1684                                 ConfValue("type","name",j,TypeName,&config_f);
1685
1686                                 if (!strcmp(TypeName,OperType))
1687                                 {
1688                                         /* found this oper's opertype */
1689                                         snprintf(global,MAXBUF,"| %s %s",user->nick,TypeName);
1690                                         NetSendToAll(global);
1691                                         ConfValue("type","host",j,HostName,&config_f);
1692                                         ChangeDisplayedHost(user,HostName);
1693                                         strlcpy(user->oper,TypeName,NICKMAX);
1694                                         found = true;
1695                                         fail2 = false;
1696                                         break;
1697                                 }
1698                         }
1699                 }
1700                 if (found)
1701                         break;
1702         }
1703         if (found)
1704         {
1705                 /* correct oper credentials */
1706                 WriteOpers("*** %s (%s@%s) is now an IRC operator of type %s",user->nick,user->ident,user->host,OperType);
1707                 WriteServ(user->fd,"381 %s :You are now an IRC operator of type %s",user->nick,OperType);
1708                 if (!strchr(user->modes,'o'))
1709                 {
1710                         strcat(user->modes,"o");
1711                         WriteServ(user->fd,"MODE %s :+o",user->nick);
1712                         snprintf(global,MAXBUF,"M %s +o",user->nick);
1713                         NetSendToAll(global);
1714                         FOREACH_MOD OnOper(user);
1715                         log(DEFAULT,"OPER: %s!%s@%s opered as type: %s",user->nick,user->ident,user->host,OperType);
1716                         AddOper(user);
1717                 }
1718         }
1719         else
1720         {
1721                 if (!fail2)
1722                 {
1723                         WriteServ(user->fd,"491 %s :Invalid oper credentials",user->nick);
1724                         WriteOpers("*** WARNING! Failed oper attempt by %s!%s@%s!",user->nick,user->ident,user->host);
1725                         log(DEFAULT,"OPER: Failed oper attempt by %s!%s@%s: user, host or password did not match.",user->nick,user->ident,user->host);
1726                 }
1727                 else
1728                 {
1729                         WriteServ(user->fd,"491 %s :Your oper block does not have a valid opertype associated with it",user->nick);
1730                         WriteOpers("*** CONFIGURATION ERROR! Oper block mismatch for OperType %s",OperType);
1731                         log(DEFAULT,"OPER: Failed oper attempt by %s!%s@%s: credentials valid, but oper type nonexistent.",user->nick,user->ident,user->host);
1732                 }
1733         }
1734         return;
1735 }
1736
1737 void handle_nick(char **parameters, int pcnt, userrec *user)
1738 {
1739         if (pcnt < 1) 
1740         {
1741                 log(DEBUG,"not enough params for handle_nick");
1742                 return;
1743         }
1744         if (!parameters[0])
1745         {
1746                 log(DEBUG,"invalid parameter passed to handle_nick");
1747                 return;
1748         }
1749         if (!parameters[0][0])
1750         {
1751                 log(DEBUG,"zero length new nick passed to handle_nick");
1752                 return;
1753         }
1754         if (!user)
1755         {
1756                 log(DEBUG,"invalid user passed to handle_nick");
1757                 return;
1758         }
1759         if (!user->nick)
1760         {
1761                 log(DEBUG,"invalid old nick passed to handle_nick");
1762                 return;
1763         }
1764         if (!strcasecmp(user->nick,parameters[0]))
1765         {
1766                 log(DEBUG,"old nick is new nick, skipping");
1767                 return;
1768         }
1769         else
1770         {
1771                 if (strlen(parameters[0]) > 1)
1772                 {
1773                         if (parameters[0][0] == ':')
1774                         {
1775                                 *parameters[0]++;
1776                         }
1777                 }
1778                 if (matches_qline(parameters[0]))
1779                 {
1780                         WriteOpers("*** Q-Lined nickname %s from %s!%s@%s: %s",parameters[0],user->nick,user->ident,user->host,matches_qline(parameters[0]));
1781                         WriteServ(user->fd,"432 %s %s :Invalid nickname: %s",user->nick,parameters[0],matches_qline(parameters[0]));
1782                         return;
1783                 }
1784                 if ((Find(parameters[0])) && (Find(parameters[0]) != user))
1785                 {
1786                         WriteServ(user->fd,"433 %s %s :Nickname is already in use.",user->nick,parameters[0]);
1787                         return;
1788                 }
1789         }
1790         if (isnick(parameters[0]) == 0)
1791         {
1792                 WriteServ(user->fd,"432 %s %s :Erroneous Nickname",user->nick,parameters[0]);
1793                 return;
1794         }
1795
1796         if (user->registered == 7)
1797         {
1798                 int MOD_RESULT = 0;
1799                 FOREACH_RESULT(OnUserPreNick(user,parameters[0]));
1800                 if (MOD_RESULT) {
1801                         // if a module returns true, the nick change is silently forbidden.
1802                         return;
1803                 }
1804
1805                 WriteCommon(user,"NICK %s",parameters[0]);
1806                 
1807                 // N token must go to ALL servers!!!
1808                 char buffer[MAXBUF];
1809                 snprintf(buffer,MAXBUF,"n %s %s",user->nick,parameters[0]);
1810                 NetSendToAll(buffer);
1811         }
1812         
1813         char oldnick[NICKMAX];
1814         strlcpy(oldnick,user->nick,NICKMAX);
1815
1816         /* change the nick of the user in the users_hash */
1817         user = ReHashNick(user->nick, parameters[0]);
1818         /* actually change the nick within the record */
1819         if (!user) return;
1820         if (!user->nick) return;
1821
1822         strlcpy(user->nick, parameters[0],NICKMAX);
1823
1824         log(DEBUG,"new nick set: %s",user->nick);
1825         
1826         if (user->registered < 3)
1827         {
1828                 user->registered = (user->registered | 2);
1829                 // dont attempt to look up the dns until they pick a nick... because otherwise their pointer WILL change
1830                 // and unless we're lucky we'll get a duff one later on.
1831                 user->dns_done = (!lookup_dns(user->nick));
1832                 if (user->dns_done)
1833                         log(DEBUG,"Aborting dns lookup of %s because dns server experienced a failure.",user->nick);
1834         }
1835         if (user->registered == 3)
1836         {
1837                 /* user is registered now, bit 0 = USER command, bit 1 = sent a NICK command */
1838                 FOREACH_MOD OnUserRegister(user);
1839                 ConnectUser(user);
1840         }
1841         if (user->registered == 7)
1842         {
1843                 FOREACH_MOD OnUserPostNick(user,oldnick);
1844         }
1845 }
1846
1847
1848 void handle_v(char token,char* params,serverrec* source,serverrec* reply, char* tcp_host)
1849 {
1850         char* servername = strtok(params," ");
1851         char* versionstr = strtok(NULL,"\r\n");
1852         ircd_connector* cn = reply->FindHost(servername);
1853         cn->SetVersionString(versionstr);
1854 }
1855
1856 void handle_V(char token,char* params,serverrec* source,serverrec* reply, char* tcp_host)
1857 {
1858         char* src = strtok(params," ");
1859         char* dest = strtok(NULL," :");
1860         char* text = strtok(NULL,"\r\n");
1861         text++;
1862         
1863         userrec* user = Find(src);
1864         if (user)
1865         {
1866                 // notice all - only issuable by a server
1867                 if (!strcmp(dest,"*"))
1868                 {
1869                         NoticeAll(user,true,"%s",text);
1870                 }
1871                 else
1872                 {
1873                         userrec* dst = Find(dest);      
1874                         if (dst)
1875                         {
1876                                 WriteTo(user, dst, "NOTICE %s :%s", dst->nick, text);
1877                         }
1878                         else
1879                         {
1880                                 chanrec* d = FindChan(dest);
1881                                 if (d)
1882                                 {
1883                                         ChanExceptSender(d, user, "NOTICE %s :%s", d->name, text);
1884                                 }
1885                         }
1886                 }
1887         }
1888         
1889 }
1890
1891
1892 void handle_P(char token,char* params,serverrec* source,serverrec* reply, char* tcp_host)
1893 {
1894         char* src = strtok(params," ");
1895         char* dest = strtok(NULL," :");
1896         char* text = strtok(NULL,"\r\n");
1897         text++;
1898         
1899         userrec* user = Find(src);
1900         if (user)
1901         {
1902                 userrec* dst = Find(dest);
1903                 
1904                 if (dst)
1905                 {
1906                         WriteTo(user, dst, "PRIVMSG %s :%s", dst->nick, text);
1907                 }
1908                 else
1909                 {
1910                         chanrec* d = FindChan(dest);
1911                         if (d)
1912                         {
1913                                 ChanExceptSender(d, user, "PRIVMSG %s :%s", d->name, text);
1914                         }
1915                 }
1916         }
1917         
1918 }
1919
1920 void handle_i(char token,char* params,serverrec* source,serverrec* reply, char* tcp_host)
1921 {
1922         char* nick = strtok(params," ");
1923         char* from = strtok(NULL," ");
1924         char* channel = strtok(NULL," ");
1925         userrec* u = Find(nick);
1926         userrec* user = Find(from);
1927         chanrec* c = FindChan(channel);
1928         if ((c) && (u) && (user))
1929         {
1930                 u->InviteTo(c->name);
1931                 WriteFrom(u->fd,user,"INVITE %s :%s",u->nick,c->name);
1932         }
1933 }
1934
1935 void handle_t(char token,char* params,serverrec* source,serverrec* reply, char* tcp_host)
1936 {
1937         char* setby = strtok(params," ");
1938         char* channel = strtok(NULL," :");
1939         char* topic = strtok(NULL,"\r\n");
1940         topic++;
1941         userrec* u = Find(setby);
1942         chanrec* c = FindChan(channel);
1943         if ((c) && (u))
1944         {
1945                 WriteChannelLocal(c,u,"TOPIC %s :%s",c->name,topic);
1946                 strlcpy(c->topic,topic,MAXTOPIC);
1947                 strlcpy(c->setby,u->nick,NICKMAX);
1948                 c->topicset = TIME;
1949         }       
1950 }
1951         
1952
1953 void handle_T(char token,char* params,serverrec* source,serverrec* reply, char* tcp_host)
1954 {
1955         char* tm = strtok(params," ");
1956         char* setby = strtok(NULL," ");
1957         char* channel = strtok(NULL," :");
1958         char* topic = strtok(NULL,"\r\n");
1959         topic++;
1960         time_t TS = atoi(tm);
1961         chanrec* c = FindChan(channel);
1962         if (c)
1963         {
1964                 // in the case of topics and TS, the *NEWER* 
1965                 if (TS <= c->topicset)
1966                 {
1967                         WriteChannelLocal(c,NULL,"TOPIC %s :%s",c->name,topic);
1968                         strlcpy(c->topic,topic,MAXTOPIC);
1969                         strlcpy(c->setby,setby,NICKMAX);
1970                 }
1971         }       
1972 }
1973         
1974 void handle_M(char token,char* params,serverrec* source,serverrec* reply, char* tcp_host)
1975 {
1976         char* pars[128];
1977         char original[MAXBUF],target[MAXBUF];
1978         strlcpy(original,params,MAXBUF);
1979         int index = 0;
1980         char* parameter = strtok(params," ");
1981         strlcpy(target,parameter,MAXBUF);
1982         while (parameter)
1983         {
1984                 if (parameter[0] == ':')
1985                         parameter++;
1986                 pars[index++] = parameter;
1987                 parameter = strtok(NULL," ");
1988         }
1989         log(DEBUG,"*** MODE: %s %s",pars[0],pars[1]);
1990         merge_mode(pars,index);
1991         if (FindChan(target))
1992         {
1993                 WriteChannelLocal(FindChan(target), NULL, "MODE %s",original);
1994         }
1995         if (Find(target))
1996         {
1997                 Write(Find(target)->fd,":%s MODE %s",ServerName,original);
1998         }
1999 }
2000
2001 // m is modes set by users only (not servers) valid targets are channels or users.
2002
2003 void handle_m(char token,char* params,serverrec* source,serverrec* reply, char* tcp_host)
2004 {
2005         // m blah #chatspike +b *!test@*4
2006         char* pars[128];
2007         char original[MAXBUF];
2008         strlcpy(original,params,MAXBUF);
2009         
2010         if (!strchr(params,' '))
2011         {
2012                 WriteOpers("WARNING! 'm' token in data stream without any parameters! Something fishy is going on!");
2013                 return;
2014         }
2015         
2016         int index = 0;
2017         
2018         char* src = strtok(params," ");
2019         userrec* user = Find(src);
2020         
2021         if (user)
2022         {
2023                 log(DEBUG,"Found user: %s",user->nick);
2024                 char* parameter = strtok(NULL," ");
2025                 while (parameter)
2026                 {
2027                         pars[index++] = parameter;
2028                         parameter = strtok(NULL," ");
2029                 }
2030                 
2031                 log(DEBUG,"Calling merge_mode2");
2032                 merge_mode2(pars,index,user);
2033         }
2034 }
2035
2036
2037 void handle_L(char token,char* params,serverrec* source,serverrec* reply, char* tcp_host)
2038 {
2039         char* nick = NULL;
2040         char* channel = NULL;
2041         char* reason = NULL;
2042         log(DEBUG,"L TOKEN PARS: '%s'",params);
2043         if (strstr(params,":#"))
2044         {
2045                 nick = strtok(params," ");
2046                 channel = strtok(NULL,"\r\n");
2047                 channel++;
2048                 reason = "";
2049         }
2050         else
2051         {
2052                 nick = strtok(params," ");
2053                 channel = strtok(NULL," :");
2054                 reason = strtok(NULL,"\r\n");
2055                 reason++;
2056         }
2057         userrec* user = Find(nick);
2058         if ((user) && (channel) && (reason))
2059         {
2060                 if ((!reason) && (*reason != '\0'))
2061                 {
2062                         del_channel(user,channel,reason,true);
2063                 }
2064                 else
2065                 {
2066                         del_channel(user,channel,NULL,true);
2067                 }
2068         }
2069 }
2070
2071 void handle_K(char token,char* params,serverrec* source,serverrec* reply, char* tcp_host)
2072 {
2073         char* src = strtok(params," ");
2074         char* nick = strtok(NULL," :");
2075         char* reason = strtok(NULL,"\r\n");
2076         char kreason[MAXBUF];
2077         reason++;
2078
2079         userrec* u = Find(nick);
2080         userrec* user = Find(src);
2081         
2082         if ((user) && (u))
2083         {
2084                 WriteTo(user, u, "KILL %s :%s!%s!%s!%s (%s)", u->nick, source->name, ServerName, user->dhost,user->nick,reason);
2085                 WriteOpers("*** Remote kill from %s by %s: %s!%s@%s (%s)",source->name,user->nick,u->nick,u->ident,u->host,reason);
2086                 snprintf(kreason,MAXBUF,"[%s] Killed (From: '%s' (%s))",source->name,user->nick,reason);
2087                 kill_link(u,kreason);
2088         }
2089 }
2090
2091 void handle_Q(char token,char* params,serverrec* source,serverrec* reply, char* tcp_host)
2092 {
2093         char* nick = strtok(params," :");
2094         char* reason = strtok(NULL,"\r\n");
2095         reason++;
2096
2097         userrec* user = Find(nick);
2098         
2099         if (user)
2100         {
2101                 if (strlen(reason)>MAXQUIT)
2102                 {
2103                         reason[MAXQUIT-1] = '\0';
2104                 }
2105
2106
2107                 WriteCommonExcept(user,"QUIT :%s",reason);
2108
2109                 user_hash::iterator iter = clientlist.find(user->nick);
2110         
2111                 if (iter != clientlist.end())
2112                 {
2113                         log(DEBUG,"deleting user hash value %d",iter->second);
2114                         clientlist.erase(iter);
2115                 }
2116
2117                 if (user->registered == 7)
2118                 {
2119                         purge_empty_chans(user);
2120                 }
2121                 delete user;
2122         }
2123 }
2124
2125 void handle_n(char token,char* params,serverrec* source,serverrec* reply, char* tcp_host)
2126 {
2127         char* oldnick = strtok(params," ");
2128         char* newnick = strtok(NULL," ");
2129         
2130         userrec* user = Find(oldnick);
2131
2132         if (user)
2133         {
2134                 if (is_uline(tcp_host))
2135                 {
2136                         int MOD_RESULT = 0;
2137                         FOREACH_RESULT(OnUserPreNick(user,newnick));
2138                         if (MOD_RESULT) {
2139                                 // if a module returns true, the nick change couldnt be allowed
2140                                 kill_link(user,"Nickname collision");
2141                                 return;
2142                         }
2143                         if (matches_qline(newnick))
2144                         {
2145                                 kill_link(user,"Nickname collision");
2146                                 return;
2147                         }
2148         
2149                         // broadcast this because its a services thingy
2150                         char buffer[MAXBUF];
2151                         snprintf(buffer,MAXBUF,"n %s %s",user->nick,newnick);
2152                         NetSendToAllExcept(tcp_host,buffer);
2153                 }
2154                 WriteCommon(user,"NICK %s",newnick);
2155                 user = ReHashNick(user->nick, newnick);
2156                 if (!user) return;
2157                 if (!user->nick) return;
2158                 strlcpy(user->nick, newnick,NICKMAX);
2159                 log(DEBUG,"new nick set: %s",user->nick);
2160         }
2161 }
2162
2163 // k <SOURCE> <DEST> <CHANNEL> :<REASON>
2164 void handle_k(char token,char* params,serverrec* source,serverrec* reply, char* tcp_host)
2165 {
2166         char* src = strtok(params," ");
2167         char* dest = strtok(NULL," ");
2168         char* channel = strtok(NULL," :");
2169         char* reason = strtok(NULL,"\r\n");
2170         reason++;
2171         userrec* s = Find(src);
2172         userrec* d = Find(dest);
2173         chanrec* c = FindChan(channel);
2174         if ((s) && (d) && (c))
2175         {
2176                 kick_channel(s,d,c,reason);
2177                 return;
2178         }
2179         d = Find(channel);
2180         c = FindChan(dest);
2181         if ((s) && (d) && (c))
2182         {
2183                 kick_channel(s,d,c,reason);
2184                 return;
2185         }
2186 }
2187
2188 void handle_AT(char token,char* params,serverrec* source,serverrec* reply, char* tcp_host)
2189 {
2190         char* who = strtok(params," :");
2191         char* text = strtok(NULL,"\r\n");
2192         text++;
2193         userrec* s = Find(who);
2194         if (s)
2195         {
2196                 WriteWallOps(s,true,text);
2197         }
2198 }
2199
2200 void handle_H(char token,char* params,serverrec* source,serverrec* reply, char* tcp_host)
2201 {
2202         log(DEBUG,"Adding ULined server %s to my map",params);
2203         ircd_connector s;
2204         s.SetState(STATE_DISCONNECTED);
2205         s.SetServerName(params);
2206
2207         for (int j = 0; j < 32; j++)
2208         {
2209                 if (me[j] != NULL)
2210                 {
2211                         for (int k = 0; k < me[j]->connectors.size(); k++)
2212                         {
2213                                 if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),params))
2214                                 {
2215                                         // dont allow a server to be added twice
2216                                         log(DEBUG,"ULined server %s already in the map!",params);
2217                                         return;
2218                                 }
2219                         }
2220                 }
2221         }
2222
2223         source->connectors.push_back(s);
2224         WriteOpers("Non-Mesh server %s has joined the network",params);
2225 }
2226
2227 void handle_N(char token,char* params,serverrec* source,serverrec* reply, char* tcp_host)
2228 {
2229         char* tm = strtok(params," ");
2230         char* nick = strtok(NULL," ");
2231         char* host = strtok(NULL," ");
2232         char* dhost = strtok(NULL," ");
2233         char* ident = strtok(NULL," ");
2234         char* modes = strtok(NULL," ");
2235         char* ipaddr = strtok(NULL," ");
2236         char* server = strtok(NULL," :");
2237         char* gecos = strtok(NULL,"\r\n");
2238         gecos++;
2239         modes++;
2240         time_t TS = atoi(tm);
2241         user_hash::iterator iter = clientlist.find(nick);
2242         if (iter != clientlist.end())
2243         {
2244                 // nick collision
2245                 WriteOpers("Nickname collision: %s@%s != %s@%s",nick,server,iter->second->nick,iter->second->server);
2246                 char str[MAXBUF];
2247                 snprintf(str,MAXBUF,"Killed (Nick Collision (%s@%s < %s@%s))",nick,server,iter->second->nick,iter->second->server);
2248                 WriteServ(iter->second->fd, "KILL %s :%s",iter->second->nick,str);
2249                 kill_link(iter->second,str);
2250         }
2251         clientlist[nick] = new userrec();
2252         // remote users have an fd of -1. This is so that our Write abstraction
2253         // routines know to route any messages to this record away to whatever server
2254         // theyre on.
2255         clientlist[nick]->fd = -1;
2256         strlcpy(clientlist[nick]->nick, nick,NICKMAX);
2257         strlcpy(clientlist[nick]->host, host,160);
2258         strlcpy(clientlist[nick]->dhost, dhost,160);
2259         strlcpy(clientlist[nick]->server, server,256);
2260         strlcpy(clientlist[nick]->ident, ident,10); // +1 char to compensate for tilde
2261         strlcpy(clientlist[nick]->fullname, gecos,128);
2262         strlcpy(clientlist[nick]->ip,ipaddr,32);
2263         clientlist[nick]->signon = TS;
2264         clientlist[nick]->nping = 0; // this is ignored for a remote user anyway.
2265         clientlist[nick]->lastping = 1;
2266         clientlist[nick]->port = 0; // so is this...
2267         clientlist[nick]->registered = 7; // this however we need to set for them to receive messages and appear online
2268         clientlist[nick]->idle_lastmsg = TIME; // this is unrealiable and wont actually be used locally
2269         for (int i = 0; i < MAXCHANS; i++)
2270         {
2271                 clientlist[nick]->chans[i].channel = NULL;
2272                 clientlist[nick]->chans[i].uc_modes = 0;
2273         }
2274         FOREACH_MOD OnGlobalConnect(clientlist[nick]);
2275         if (strchr(clientlist[nick]->modes,'o'))
2276         {
2277                 FOREACH_MOD OnGlobalOper(clientlist[nick]);
2278         }
2279 }
2280
2281 void handle_F(char token,char* params,serverrec* source,serverrec* reply, char* tcp_host)
2282 {
2283         long tdiff = TIME - atoi(params);
2284         if (tdiff)
2285                 WriteOpers("TS split for %s -> %s: %d",source->name,reply->name,tdiff);
2286 }
2287
2288 void handle_a(char token,char* params,serverrec* source,serverrec* reply, char* tcp_host)
2289 {
2290         char* nick = strtok(params," :");
2291         char* gecos = strtok(NULL,"\r\n");
2292         
2293         userrec* user = Find(nick);
2294
2295         if (user)
2296                 strlcpy(user->fullname,gecos,MAXBUF);
2297 }
2298
2299 void handle_b(char token,char* params,serverrec* source,serverrec* reply, char* tcp_host)
2300 {
2301         char* nick = strtok(params," ");
2302         char* host = strtok(NULL," ");
2303         
2304         userrec* user = Find(nick);
2305
2306         if (user)
2307                 strlcpy(user->dhost,host,160);
2308 }
2309
2310 void handle_plus(char token,char* params,serverrec* source,serverrec* reply, char* tcp_host)
2311 {
2312         // %s %s %d %d
2313         // + test3.chatspike.net 7010 -2016508415
2314         char* servername = strtok(params," ");
2315         char* ipaddr = strtok(NULL," ");
2316         char* ipport = strtok(NULL," ");
2317         char* cookie = strtok(NULL," ");
2318         log(DEBUG,"*** Connecting back to %s:%d",ipaddr,atoi(ipport));
2319
2320
2321         bool conn_already = false;
2322         for (int i = 0; i < 32; i++)
2323         {
2324                 if (me[i] != NULL)
2325                 {
2326                         for (int j = 0; j < me[i]->connectors.size(); j++)
2327                         {
2328                                 if (!strcasecmp(me[i]->connectors[j].GetServerName().c_str(),servername))
2329                                 {
2330                                         if (me[i]->connectors[j].GetServerPort() == atoi(ipport))
2331                                         {
2332                                                 log(DEBUG,"Already got a connection to %s:%d, ignoring +",ipaddr,atoi(ipport));
2333                                                 conn_already = true;
2334                                         }
2335                                 }
2336                         }
2337                 }
2338         }
2339         if (!conn_already)
2340                 me[defaultRoute]->MeshCookie(ipaddr,atoi(ipport),atoi(cookie),servername);
2341 }
2342
2343 void handle_R(char token,char* params,serverrec* source,serverrec* reply, char* tcp_host)
2344 {
2345         char* server = strtok(params," ");
2346         char* data = strtok(NULL,"\r\n");
2347         if ((!data) || (!server))
2348         {
2349                 log(DEBUG,"Someones playing silly buggers, attempting to send to a null server or send a null message (BUG?)");
2350                 return;
2351         }
2352                 
2353         log(DEBUG,"Forwarded packet '%s' to '%s'",data,server);
2354         NetSendToOne(server,data);
2355 }
2356
2357 void handle_J(char token,char* params,serverrec* source,serverrec* reply, char* tcp_host)
2358 {
2359         // IMPORTANT NOTE
2360         // The J token currently has no timestamp - this needs looking at
2361         // because it will allow splitriding.
2362         char* nick = strtok(params," ");
2363         char* channel = strtok(NULL," ");
2364         userrec* user = Find(nick);
2365         while (channel)
2366         {
2367                 if ((user != NULL) && (strcmp(channel,"")))
2368                 {
2369                         char privilage = '\0';
2370                         if (channel[0] != '#')
2371                         {
2372                                 privilage = channel[0];
2373                                 channel++;
2374                         }
2375                         add_channel(user,channel,"",true);
2376
2377                         // now work out the privilages they should have on each channel
2378                         // and send the appropriate servermodes.
2379                         for (int i = 0; i != MAXCHANS; i++)
2380                         {
2381                                 if (user->chans[i].channel)
2382                                 {
2383                                         if (!strcasecmp(user->chans[i].channel->name,channel))
2384                                         {
2385                                                 if (privilage == '@')
2386                                                 {
2387                                                         user->chans[i].uc_modes = user->chans[i].uc_modes | UCMODE_OP;
2388                                                         WriteChannelLocal(user->chans[i].channel, NULL, "MODE %s +o %s",channel,user->nick);
2389                                                 }
2390                                                 if (privilage == '%')
2391                                                 {
2392                                                         user->chans[i].uc_modes = user->chans[i].uc_modes | UCMODE_HOP;
2393                                                         WriteChannelLocal(user->chans[i].channel, NULL, "MODE %s +h %s",channel,user->nick);
2394                                                 }
2395                                                 if (privilage == '+')
2396                                                 {
2397                                                         user->chans[i].uc_modes = user->chans[i].uc_modes | UCMODE_VOICE;
2398                                                         WriteChannelLocal(user->chans[i].channel, NULL, "MODE %s +v %s",channel,user->nick);
2399                                                 }
2400                                         }
2401                                 }
2402                         }
2403
2404                 }
2405                 channel = strtok(NULL," ");
2406         }
2407 }
2408
2409 void handle_dollar(char token,char* params,serverrec* source,serverrec* reply, char* tcp_host)
2410 {
2411         log(DEBUG,"Storing routing table...");
2412         char* sourceserver = strtok(params," ");
2413         char* server = strtok(NULL," ");
2414         for (int i = 0; i < 32; i++)
2415         {
2416                 if (me[i] != NULL)
2417                 {
2418                         for (int j = 0; j < me[i]->connectors.size(); j++)
2419                         {
2420                                 if (!strcasecmp(me[i]->connectors[j].GetServerName().c_str(),sourceserver))
2421                                 {
2422                                         me[i]->connectors[j].routes.clear();
2423                                         log(DEBUG,"Found entry for source server.");
2424                                         while (server)
2425                                         {
2426                                                 // store each route
2427                                                 me[i]->connectors[j].routes.push_back(server);
2428                                                 log(DEBUG,"*** Stored route: %s -> %s -> %s",ServerName,sourceserver,server);
2429                                                 server = strtok(NULL," ");
2430                                         }
2431                                         return;
2432                                 }
2433                         }
2434                 }
2435         }
2436         log(DEBUG,"Warning! routing table received from nonexistent server!");
2437 }
2438
2439 void handle_amp(char token,char* params,serverrec* source,serverrec* reply, char* tcp_host)
2440 {
2441         log(DEBUG,"Netsplit! %s split from mesh, removing!",params);
2442         WriteOpers("*** NOTICE - Controlled netsplit: %s split from %s",params,ServerName);
2443         bool go_again = true;
2444         while (go_again)
2445         {
2446                 go_again = false;
2447                 for (int i = 0; i < 32; i++)
2448                 {
2449                         if (me[i] != NULL)
2450                         {
2451                                 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2452                                 {
2453                                         if (!strcasecmp(j->GetServerName().c_str(),params))
2454                                         {
2455                                                 j->routes.clear();
2456                                                 j->CloseConnection();
2457                                                 me[i]->connectors.erase(j);
2458                                                 go_again = true;
2459                                                 break;
2460                                         }
2461                                 }
2462                         }
2463                 }
2464         }
2465         log(DEBUG,"Removed server. Will remove clients...");
2466         // iterate through the userlist and remove all users on this server.
2467         // because we're dealing with a mesh, we dont have to deal with anything
2468         // "down-route" from this server (nice huh)
2469         go_again = true;
2470         char reason[MAXBUF];
2471         snprintf(reason,MAXBUF,"%s %s",ServerName,params);
2472         while (go_again)
2473         {
2474                 go_again = false;
2475                 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
2476                 {
2477                         if (!strcasecmp(u->second->server,params))
2478                         {
2479                                 kill_link(u->second,reason);
2480                                 go_again = true;
2481                                 break;
2482                         }
2483                 }
2484         }
2485 }
2486
2487 unsigned long authcookie;
2488
2489 void handle_hash(char token,char* params,serverrec* source,serverrec* reply, char* tcp_host)
2490 {
2491         // # <mask> <who-set-it> <time-set> <duration> :<reason>
2492         log(DEBUG,"Adding G-line");
2493         char* mask = strtok(params," ");
2494         char* who = strtok(NULL," ");
2495         char* create_time = strtok(NULL," ");
2496         char* duration = strtok(NULL," :");
2497         char* reason = strtok(NULL,"\r\n");
2498         reason++;
2499         add_gline(atoi(duration),(const char*)who,(const char*)reason,(const char*)mask);
2500         // we must update the creation time on this gline
2501         // now that we've added it, or it wont expire at the right time.
2502         gline_set_creation_time(mask,atoi(create_time));
2503         if (!atoi(duration))
2504         {
2505                 WriteOpers("*** %s Added permenant G-Line on %s.",who,mask);
2506         }
2507         else
2508         {
2509                 WriteOpers("*** %s Added timed G-Line on %s to expire in %d seconds.",who,mask,atoi(duration));
2510         }
2511         apply_lines();
2512 }
2513
2514 void handle_dot(char token,char* params,serverrec* source,serverrec* reply, char* tcp_host)
2515 {
2516         log(DEBUG,"Removing G-line");
2517         char* mask = strtok(params," ");
2518         char* who = strtok(NULL," ");
2519         if (mask)
2520         {
2521                 if (del_gline((const char*)mask))
2522                 {
2523                         if (who)
2524                         {
2525                                 WriteOpers("*** %s Removed G-line on %s.",who,mask);
2526                         }
2527                 }
2528         }
2529 }
2530
2531 void handle_add_sqline(char token,char* params,serverrec* source,serverrec* reply, char* tcp_host)
2532 {
2533         // { <mask> <who-set-it> <time-set> <duration> :<reason>
2534         log(DEBUG,"Adding Q-line");
2535         char* mask = strtok(params," ");
2536         char* who = strtok(NULL," ");
2537         char* create_time = strtok(NULL," ");
2538         char* duration = strtok(NULL," :");
2539         char* reason = strtok(NULL,"\r\n");
2540         reason++;
2541         add_qline(atoi(duration),(const char*)who,(const char*)reason,(const char*)mask);
2542         // we must update the creation time on this gline
2543         // now that we've added it, or it wont expire at the right time.
2544         qline_set_creation_time(mask,atoi(create_time));
2545         qline_make_global(mask);
2546         if (!atoi(duration))
2547         {
2548                 WriteOpers("*** %s Added permenant Q-Line on %s.",who,mask);
2549         }
2550         else
2551         {
2552                 WriteOpers("*** %s Added timed Q-Line on %s to expire in %d seconds.",who,mask,atoi(duration));
2553         }
2554         apply_lines();
2555 }
2556
2557 void handle_del_sqline(char token,char* params,serverrec* source,serverrec* reply, char* tcp_host)
2558 {
2559         log(DEBUG,"Removing Q-line");
2560         char* mask = strtok(params," ");
2561         char* who = strtok(NULL," ");
2562         if (mask)
2563         {
2564                 if (del_qline((const char*)mask))
2565                 {
2566                         if (who)
2567                         {
2568                                 WriteOpers("*** %s Removed Q-line on %s.",who,mask);
2569                         }
2570                 }
2571         }
2572 }
2573
2574 void handle_add_szline(char token,char* params,serverrec* source,serverrec* reply, char* tcp_host)
2575 {
2576         // } <mask> <who-set-it> <time-set> <duration> :<reason>
2577         log(DEBUG,"Adding Z-line");
2578         char* mask = strtok(params," ");
2579         char* who = strtok(NULL," ");
2580         char* create_time = strtok(NULL," ");
2581         char* duration = strtok(NULL," :");
2582         char* reason = strtok(NULL,"\r\n");
2583         reason++;
2584         add_zline(atoi(duration),(const char*)who,(const char*)reason,(const char*)mask);
2585         // we must update the creation time on this gline
2586         // now that we've added it, or it wont expire at the right time.
2587         zline_set_creation_time(mask,atoi(create_time));
2588         zline_make_global(mask);
2589         if (!atoi(duration))
2590         {
2591                 WriteOpers("*** %s Added permenant Z-Line on %s.",who,mask);
2592         }
2593         else
2594         {
2595                 WriteOpers("*** %s Added timed Z-Line on %s to expire in %d seconds.",who,mask,atoi(duration));
2596         }
2597         apply_lines();
2598 }
2599
2600 void handle_del_szline(char token,char* params,serverrec* source,serverrec* reply, char* tcp_host)
2601 {
2602         log(DEBUG,"Removing Z-line");
2603         char* mask = strtok(params," ");
2604         char* who = strtok(NULL," ");
2605         if (mask)
2606         {
2607                 if (del_zline((const char*)mask))
2608                 {
2609                         if (who)
2610                         {
2611                                 WriteOpers("*** %s Removed Q-line on %s.",who,mask);
2612                         }
2613                 }
2614         }
2615 }
2616
2617 void handle_pipe(char token,char* params,serverrec* source,serverrec* reply, char* tcp_host)
2618 {
2619         char* nick = strtok(params," ");
2620         char* type = strtok(params," ");
2621         userrec* u = Find(nick);
2622         if (u)
2623         {
2624                 strlcpy(u->oper,type,NICKMAX);
2625         }
2626 }
2627
2628
2629 void process_restricted_commands(char token,char* params,serverrec* source,serverrec* reply, char* tcp_host,char* ipaddr,int port)
2630 {
2631         char buffer[MAXBUF];
2632         int MOD_RESULT = 0;
2633
2634         switch(token)
2635         {
2636                 // Y <TS>
2637                 // start netburst
2638                 case 'Y':
2639                         nb_start = TIME;
2640                         WriteOpers("Server %s is starting netburst.",tcp_host);
2641                         // now broadcast this new servers address out to all servers that are linked to us,
2642                         // except the newcomer. They'll all attempt to connect back to it.
2643                         authcookie = rand()*rand();
2644                         snprintf(buffer,MAXBUF,"~ %lu",(unsigned long)authcookie);
2645                         NetSendToAll(buffer);
2646                 break;
2647                 // ~
2648                 // Store authcookie
2649                 // once stored, this authcookie permits other servers to log in
2650                 // without user or password, using it.
2651                 case '~':
2652                         auth_cookies.push_back(atoi(params));
2653                         log(DEBUG,"*** Stored auth cookie, will permit servers with auth-cookie %d",atoi(params));
2654                 break;
2655                 // connect back to a server using an authcookie
2656                 case '+':
2657                         handle_plus(token,params,source,reply,tcp_host);
2658                 break;
2659                 // routing table
2660                 case '$':
2661                         handle_dollar(token,params,source,reply,tcp_host);
2662                 break;
2663                 // node unreachable - we cant route to a server, sooooo we slit it off.
2664                 // servers can generate these for themselves for an squit.
2665                 case '&':
2666                         handle_amp(token,params,source,reply,tcp_host);
2667                 break;
2668                 // R <server> <data>
2669                 // redirect token, send all of <data> along to the given 
2670                 // server as this server has been found to still have a route to it
2671                 case 'R':
2672                         handle_R(token,params,source,reply,tcp_host);
2673                 break;
2674                 // ?
2675                 // ping
2676                 case '?':
2677                         reply->SendPacket("!",tcp_host);
2678                 break;
2679                 // ?
2680                 // pong
2681                 case '!':
2682                 break;
2683                 // *
2684                 // no operation
2685                 case '*':
2686                 break;
2687                 // N <TS> <NICK> <HOST> <DHOST> <IDENT> <MODES> <SERVER> :<GECOS>
2688                 // introduce remote client
2689                 case 'N':
2690                         handle_N(token,params,source,reply,tcp_host);
2691                 break;
2692                 // a <NICK> :<GECOS>
2693                 // change GECOS (SETNAME)
2694                 case 'a':
2695                         handle_a(token,params,source,reply,tcp_host);
2696                 break;
2697                 // b <NICK> :<HOST>
2698                 // change displayed host (SETHOST)
2699                 case 'b':
2700                         handle_b(token,params,source,reply,tcp_host);
2701                 break;
2702                 // t <NICK> <CHANNEL> :<TOPIC>
2703                 // change a channel topic
2704                 case 't':
2705                         handle_t(token,params,source,reply,tcp_host);
2706                 break;
2707                 // i <NICK> <CHANNEL>
2708                 // invite a user to a channel
2709                 case 'i':
2710                         handle_i(token,params,source,reply,tcp_host);
2711                 break;
2712                 // k <SOURCE> <DEST> <CHANNEL> :<REASON>
2713                 // kick a user from a channel
2714                 case 'k':
2715                         handle_k(token,params,source,reply,tcp_host);
2716                 break;
2717                 // n <NICK> <NEWNICK>
2718                 // change nickname of client -- a server should only be able to
2719                 // change the nicknames of clients that reside on it unless
2720                 // they are ulined.
2721                 case 'n':
2722                         handle_n(token,params,source,reply,tcp_host);
2723                 break;
2724                 // J <NICK> <CHANLIST>
2725                 // Join user to channel list, merge channel permissions
2726                 case 'J':
2727                         handle_J(token,params,source,reply,tcp_host);
2728                 break;
2729                 // T <TS> <CHANNEL> <TOPICSETTER> :<TOPIC>
2730                 // change channel topic (netburst only)
2731                 case 'T':
2732                         handle_T(token,params,source,reply,tcp_host);
2733                 break;
2734                 // M <TARGET> <MODES> [MODE-PARAMETERS]
2735                 // Server setting modes on an object
2736                 case 'M':
2737                         handle_M(token,params,source,reply,tcp_host);
2738                 break;
2739                 // m <SOURCE> <TARGET> <MODES> [MODE-PARAMETERS]
2740                 // User setting modes on an object
2741                 case 'm':
2742                         handle_m(token,params,source,reply,tcp_host);
2743                 break;
2744                 // P <SOURCE> <TARGET> :<TEXT>
2745                 // Send a private/channel message
2746                 case 'P':
2747                         handle_P(token,params,source,reply,tcp_host);
2748                 break;
2749                 // V <SOURCE> <TARGET> :<TEXT>
2750                 // Send a private/channel notice
2751                 case 'V':
2752                         handle_V(token,params,source,reply,tcp_host);
2753                 break;
2754                 // v <servername> <arbitary version string>
2755                 case 'v':
2756                         handle_v(token,params,source,reply,tcp_host);
2757                 break;
2758                 // L <SOURCE> <CHANNEL> :<REASON>
2759                 // User parting a channel
2760                 case 'L':
2761                         handle_L(token,params,source,reply,tcp_host);
2762                 break;
2763                 // Q <SOURCE> :<REASON>
2764                 // user quitting
2765                 case 'Q':
2766                         handle_Q(token,params,source,reply,tcp_host);
2767                 break;
2768                 // H <SERVER>
2769                 // introduce non-meshable server (such as a services server)
2770                 case 'H':
2771                         handle_H(token,params,source,reply,tcp_host);
2772                 break;
2773                 // K <SOURCE> <DEST> :<REASON>
2774                 // remote kill
2775                 case 'K':
2776                         handle_K(token,params,source,reply,tcp_host);
2777                 break;
2778                 // @ <SOURCE> :<TEXT>
2779                 // wallops
2780                 case '@':
2781                         handle_AT(token,params,source,reply,tcp_host);
2782                 break;
2783                 // # <mask> <who-set-it> <time-set> <duration> :<reason>
2784                 // add gline
2785                 case '#':
2786                         handle_hash(token,params,source,reply,tcp_host);
2787                 break;
2788                 // . <mask> <who>
2789                 // remove gline
2790                 case '.':
2791                         handle_dot(token,params,source,reply,tcp_host);
2792                 break;
2793                 // # <mask> <who-set-it> <time-set> <duration> :<reason>
2794                 // add gline
2795                 case '{':
2796                         handle_add_sqline(token,params,source,reply,tcp_host);
2797                 break;
2798                 // . <mask> <who>
2799                 // remove gline
2800                 case '[':
2801                         handle_del_sqline(token,params,source,reply,tcp_host);
2802                 break;
2803                 // # <mask> <who-set-it> <time-set> <duration> :<reason>
2804                 // add gline
2805                 case '}':
2806                         handle_add_szline(token,params,source,reply,tcp_host);
2807                 break;
2808                 // . <mask> <who>
2809                 // remove gline
2810                 case ']':
2811                         handle_del_szline(token,params,source,reply,tcp_host);
2812                 break;
2813                 // | <nick> <opertype>
2814                 // set opertype
2815                 case '|':
2816                         handle_pipe(token,params,source,reply,tcp_host);
2817                 break;
2818                 // F <TS>
2819                 // end netburst
2820                 case 'F':
2821                         WriteOpers("Server %s has completed netburst. (%d secs)",tcp_host,TIME-nb_start);
2822                         handle_F(token,params,source,reply,tcp_host);
2823                         nb_start = 0;
2824                         // tell all the other servers to use this authcookie to connect back again
2825                         // got '+ test3.chatspike.net 7010 -2016508415' from test.chatspike.net
2826                         snprintf(buffer,MAXBUF,"+ %s %s %d %lu",tcp_host,ipaddr,port,(unsigned long)authcookie);
2827                         NetSendToAllExcept(tcp_host,buffer);
2828                 break;
2829                 case '/':
2830                         WriteOpers("Server %s is IRCServices-based server (assumes-SVSMODE) - Nickname Services: %s",tcp_host,params);
2831                         strlcpy(source->nickserv,params,NICKMAX);
2832                 break;
2833                 // F <TS>
2834                 // end netburst with no mesh creation
2835                 case 'f':
2836                         WriteOpers("Server %s has completed netburst. (%d secs)",tcp_host,TIME-nb_start);
2837                         handle_F(token,params,source,reply,tcp_host);
2838                         nb_start = 0;
2839                         // tell everyone else about the new server name so they just add it in the disconnected
2840                         // state
2841                         snprintf(buffer,MAXBUF,"u %s :%s",tcp_host,GetServerDescription(tcp_host).c_str());
2842                         NetSendToAllExcept(tcp_host,buffer);
2843                 break;
2844                 // X <reserved>
2845                 // Send netburst now
2846                 case 'X':
2847                         WriteOpers("Sending my netburst to %s",tcp_host);
2848                         DoSync(source,tcp_host);
2849                         WriteOpers("Send of netburst to %s completed",tcp_host);
2850                         NetSendMyRoutingTable();
2851                 break;
2852                 // anything else
2853                 default:
2854                         MOD_RESULT = 0;
2855                         string_list s;
2856                         char* data = strtok(params," ");
2857                         while (data)
2858                         {
2859                                 if (*data == ':')
2860                                 {
2861                                         // the last item is a special case
2862                                         data++;
2863                                         char datalast[MAXBUF];
2864                                         strlcpy(datalast,data,MAXBUF);
2865                                         data = strtok(NULL," ");
2866                                         while (data)
2867                                         {
2868                                                 strlcpy(datalast," ",MAXBUF);
2869                                                 strlcpy(datalast,data,MAXBUF);
2870                                                 data = strtok(NULL," ");
2871                                         }
2872                                         s.push_back(data);
2873                                         break;
2874                                 }
2875                                 s.push_back(data);
2876                                 data = strtok(NULL," ");
2877                         }
2878                         FOREACH_RESULT(OnMeshToken(token,s,source,reply,tcp_host,ipaddr,port));
2879                         if (!MOD_RESULT)
2880                                 WriteOpers("WARNING! Unknown datagram type '%c'",token);
2881                 break;
2882         }
2883 }
2884
2885
2886 void handle_link_packet(char* udp_msg, char* tcp_host, serverrec *serv)
2887 {
2888         if ((!strncmp(udp_msg,"USER ",5)) || (!strncmp(udp_msg,"NICK ",5)) || (!strncmp(udp_msg,"PASS ",5)) || (!strncmp(udp_msg,"SERVER ",7)))
2889         {
2890                 // a user on a server port, just close their connection.
2891                 RemoveServer(tcp_host);
2892                 return;
2893         }
2894
2895         char response[10240];
2896         char token = udp_msg[0];
2897         char* old = udp_msg;
2898
2899         if ((token != ':') && (strlen(udp_msg)>1) && (udp_msg[1] != ' '))
2900         {
2901                 WriteOpers("*** Discarded %d chars illegal data from %s",strlen(udp_msg),tcp_host);
2902         }
2903
2904         if (token == ':') // leading :servername or details - strip them off (services does this, sucky)
2905         {
2906                 char* src = udp_msg+1;
2907                 while (udp_msg[0] != ' ')
2908                         udp_msg++;
2909                 udp_msg[0] = 0;
2910                 udp_msg++;
2911                 char* comd = udp_msg;
2912                 while (udp_msg[0] != ' ')
2913                         udp_msg++;
2914                 udp_msg[0] = 0;
2915                 udp_msg++;
2916                 char data[MAXBUF];
2917                 char source[MAXBUF];
2918                 char command[MAXBUF];
2919                 strlcpy(data,udp_msg,512);
2920                 strlcpy(source,src,MAXBUF);
2921                 strlcpy(command,comd,MAXBUF);
2922                 udp_msg = old;
2923                 
2924                 // unused numeric:
2925                 // :services-dev.chatspike.net 433 Craig Craig :Nickname is registered to someone else
2926                 if (!strcmp(command,"433"))
2927                 {
2928                         token = '*';
2929                 }
2930                 if (!strcmp(command,"432"))
2931                 {
2932                         token = '*';
2933                 }
2934                 if (!strcmp(command,"PING"))
2935                 {
2936                         token = '*';
2937                 }
2938                 if (!strcmp(command,"NOTICE"))
2939                 {
2940                         snprintf(udp_msg,MAXBUF,"V %s %s",source,data);
2941                         log(DEBUG,"Rewrote NOTICE from services to: '%s'",udp_msg);
2942                         token = udp_msg[0];
2943                 }
2944                 if (!strcmp(command,"QUIT"))
2945                 {
2946                         if ((!udp_msg) || (!strcmp(data,"")) || (strcmp(data,":")))
2947                         {
2948                                 strcpy(data,":No reason");
2949                         }
2950                         if (!strcmp(data,":"))
2951                         {
2952                                 strcpy(data,":No reason");
2953                         }
2954                         snprintf(udp_msg,MAXBUF,"Q %s %s",source,data);
2955                         log(DEBUG,"Rewrote QUIT from services to: '%s'",udp_msg);
2956                         token = udp_msg[0];
2957                 }
2958                 if (!strcmp(command,"SQUIT"))
2959                 {
2960                         snprintf(udp_msg,MAXBUF,"& %s",source);
2961                         log(DEBUG,"Rewrote SQUIT from services to: '%s'",udp_msg);
2962                         token = udp_msg[0];
2963                 }
2964                 if (!strcmp(command,"SVSMODE"))
2965                 {
2966                         snprintf(udp_msg,MAXBUF,"m %s %s",source,data);
2967                         log(DEBUG,"Rewrote SVSMODE from services to: '%s'",udp_msg);
2968                         token = udp_msg[0];
2969                 }
2970                 if (!strcmp(command,"SVS2MODE"))
2971                 {
2972                         snprintf(udp_msg,MAXBUF,"m %s %s",source,data);
2973                         log(DEBUG,"Rewrote SVS2MODE from services to: '%s'",udp_msg);
2974                         token = udp_msg[0];
2975                 }
2976                 // todo: this wont work without u:lines
2977                 // in give_ops etc allow nick on a u:lined serv to do just about anything
2978                 if (!strcmp(command,"MODE"))
2979                 {
2980                         snprintf(udp_msg,MAXBUF,"m %s %s",source,data);
2981                         log(DEBUG,"Rewrote MODE from services to: '%s'",udp_msg);
2982                         token = udp_msg[0];
2983                 }
2984                 if (!strcmp(command,"KICK"))
2985                 {
2986                         snprintf(udp_msg,MAXBUF,"k %s %s",source,data);
2987                         log(DEBUG,"Rewrote KICK from services to: '%s'",udp_msg);
2988                         token = udp_msg[0];
2989                 }
2990                 if (!strcmp(command,"KILL"))
2991                 {
2992                         snprintf(udp_msg,MAXBUF,"K %s %s",source,data);
2993                         log(DEBUG,"Rewrote KILL from services to: '%s'",udp_msg);
2994                         token = udp_msg[0];
2995                 }
2996                 if (!strcmp(command,"SVSJOIN"))
2997                 {
2998                         snprintf(udp_msg,MAXBUF,"J %s",data);
2999                         NetSendToOne(tcp_host,udp_msg);
3000                         char* nick = strtok(data," ");
3001                         char* chan = strtok(NULL," ");
3002                         log(DEBUG,"Rewrote SVSJOIN from services to: '%s'",udp_msg);
3003                         userrec* u = Find(nick);
3004                         if (u)
3005                         {
3006                                 add_channel(u,chan,"",true);
3007                         }
3008                         token = udp_msg[0];
3009                 }
3010                 
3011         }
3012
3013         char* params = udp_msg + 2;
3014         char finalparam[1024];
3015         strcpy(finalparam," :xxxx");
3016         if (strstr(udp_msg," :")) {
3017                 strlcpy(finalparam,strstr(udp_msg," :"),1024);
3018         }
3019         
3020         
3021         if (token == '-') {
3022                 char* cookie = strtok(params," ");
3023                 char* servername = strtok(NULL," ");
3024                 char* serverdesc = finalparam+2;
3025
3026                 WriteOpers("AuthCookie CONNECT from %s (%s)",servername,tcp_host);
3027
3028                 for (int u = 0; u < auth_cookies.size(); u++)
3029                 {
3030                         if (auth_cookies[u] == atoi(cookie))
3031                         {
3032                                 WriteOpers("Allowed cookie from %s, is now part of the mesh",servername);
3033
3034
3035                                 for (int j = 0; j < 32; j++)
3036                                 {
3037                                         if (me[j] != NULL)
3038                                         {
3039                                                 for (int k = 0; k < me[j]->connectors.size(); k++)
3040                                                 {
3041                                                         if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),tcp_host))
3042                                                         {
3043                                                                 me[j]->connectors[k].SetServerName(servername);
3044                                                                 me[j]->connectors[k].SetDescription(serverdesc);
3045                                                                 me[j]->connectors[k].SetState(STATE_CONNECTED);
3046                                                                 NetSendMyRoutingTable();
3047                                                                 return;
3048                                                         }
3049                                                 }
3050                                         }
3051                                         WriteOpers("\2WARNING!\2 %s sent us an authentication packet but we are not authenticating with this server right now! Possible intrusion attempt!",tcp_host);
3052                                         return;
3053                                 }
3054
3055
3056                                 return;
3057                         }
3058                 }
3059                 // bad cookie, bad bad! go sit in the corner!
3060                 WriteOpers("Bad cookie from %s!",servername);
3061                 return;
3062         }
3063         else
3064         if (token == 'S') {
3065                 // S test.chatspike.net password portn :ChatSpike InspIRCd test server
3066                 char* servername = strtok(params," ");
3067                 char* password = strtok(NULL," ");
3068                 char* myport = strtok(NULL," ");
3069                 char* revision = strtok(NULL," ");
3070                 char* serverdesc = finalparam+2;
3071
3072                 password = password;
3073
3074                 WriteOpers("CONNECT from %s (%s) (their port: %d)",servername,tcp_host,atoi(myport));
3075                 
3076                 ircd_connector* cn = serv->FindHost(servername);
3077                 
3078                 if (cn)
3079                 {
3080                         WriteOpers("CONNECT aborted: Server %s already exists from %s",servername,ServerName);
3081                         char buffer[MAXBUF];
3082                         snprintf(buffer,MAXBUF,"E :Server %s already exists!",servername);
3083                         serv->SendPacket(buffer,tcp_host);
3084                         RemoveServer(tcp_host);
3085                         return;
3086                 }
3087
3088                 if (atoi(revision) != GetRevision())
3089                 {
3090                         WriteOpers("CONNECT aborted: Could not link to %s, is an incompatible version %s, our version is %d",servername,revision,GetRevision());
3091                         char buffer[MAXBUF];
3092                         sprintf(buffer,"E :Version number mismatch");
3093                         serv->SendPacket(buffer,tcp_host);
3094                         RemoveServer(tcp_host);
3095                         RemoveServer(servername);
3096                         return;
3097                 }
3098
3099                 for (int j = 0; j < serv->connectors.size(); j++)
3100                 {
3101                         if (!strcasecmp(serv->connectors[j].GetServerName().c_str(),tcp_host))
3102                         {
3103                                 serv->connectors[j].SetServerName(servername);
3104                                 serv->connectors[j].SetDescription(serverdesc);
3105                                 serv->connectors[j].SetServerPort(atoi(myport));
3106                         }
3107                 }
3108                 
3109                 
3110                 char Link_ServerName[1024];
3111                 char Link_IPAddr[1024];
3112                 char Link_Port[1024];
3113                 char Link_Pass[1024];
3114                 char Link_SendPass[1024];
3115                 int LinkPort = 0;
3116                 
3117                 // search for a corresponding <link> block in the config files
3118                 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
3119                 {
3120                         ConfValue("link","name",i,Link_ServerName,&config_f);
3121                         ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
3122                         ConfValue("link","port",i,Link_Port,&config_f);
3123                         ConfValue("link","recvpass",i,Link_Pass,&config_f);
3124                         ConfValue("link","sendpass",i,Link_SendPass,&config_f);
3125                         log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
3126                         LinkPort = atoi(Link_Port);
3127                         if ((!strcasecmp(Link_ServerName,servername)) && (!strcmp(Link_Pass,password)))
3128                         {
3129                                 // we have a matching link line -
3130                                 // send a 'diminutive' server message back...
3131                                 snprintf(response,10240,"s %s %s :%s",ServerName,Link_SendPass,ServerDesc);
3132                                 serv->SendPacket(response,servername);
3133
3134                                 for (int t = 0; t < serv->connectors.size(); t++)
3135                                 {
3136                                         if (!strcasecmp(serv->connectors[t].GetServerName().c_str(),servername))
3137                                         {
3138                                                 serv->connectors[t].SetState(STATE_CONNECTED);
3139                                         }
3140                                 }
3141                 
3142                                 return;
3143                         }
3144                 }
3145                 char buffer[MAXBUF];
3146                 sprintf(buffer,"E :Access is denied (no matching link block)");
3147                 serv->SendPacket(buffer,tcp_host);
3148                 WriteOpers("CONNECT from %s denied, no matching link block",servername);
3149                 RemoveServer(tcp_host);
3150                 RemoveServer(servername);
3151                 return;
3152         }
3153         else
3154         if (token == 's') {
3155                 // S test.chatspike.net password :ChatSpike InspIRCd test server
3156                 char* servername = strtok(params," ");
3157                 char* password = strtok(NULL," ");
3158                 char* serverdesc = finalparam+2;
3159
3160                 password = password;
3161                 
3162                 // TODO: we should do a check here to ensure that this server is one we recently initiated a
3163                 // link with, and didnt hear an 's' or 'E' back from yet (these are the only two valid responses
3164                 // to an 'S' command. If we didn't recently send an 'S' to this server, theyre trying to spoof
3165                 // a connect, so put out an oper alert!
3166                 
3167                 // for now, just accept all, we'll fix that later.
3168                 WriteOpers("%s accepted our link credentials ",servername);
3169                 
3170                 char Link_ServerName[1024];
3171                 char Link_IPAddr[1024];
3172                 char Link_Port[1024];
3173                 char Link_Pass[1024];
3174                 char Link_SendPass[1024];
3175                 int LinkPort = 0;
3176
3177                 // search for a corresponding <link> block in the config files
3178                 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
3179                 {
3180                         ConfValue("link","name",i,Link_ServerName,&config_f);
3181                         ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
3182                         ConfValue("link","port",i,Link_Port,&config_f);
3183                         ConfValue("link","recvpass",i,Link_Pass,&config_f);
3184                         ConfValue("link","sendpass",i,Link_SendPass,&config_f);
3185                         log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
3186                         LinkPort = atoi(Link_Port);
3187                         if (!strcasecmp(Link_ServerName,servername))
3188                         {
3189                                 // matching link at this end too, we're all done!
3190                                 // at this point we must begin key exchange and insert this
3191                                 // server into our 'active' table.
3192                                 for (int j = 0; j < 32; j++)
3193                                 {
3194                                         if (me[j] != NULL)
3195                                         {
3196                                                 for (int k = 0; k < me[j]->connectors.size(); k++)
3197                                                 {
3198                                                         if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),tcp_host))
3199                                                         {
3200                                                                 char buffer[MAXBUF];
3201                                                                 me[j]->connectors[k].SetDescription(serverdesc);
3202                                                                 me[j]->connectors[k].SetState(STATE_CONNECTED);
3203                                                                 sprintf(buffer,"X 0");
3204                                                                 serv->SendPacket(buffer,tcp_host);
3205                                                                 DoSync(me[j],tcp_host);
3206                                                                 NetSendMyRoutingTable();
3207                                                                 return;
3208                                                         }
3209                                                 }
3210                                         }
3211                                 }
3212                         }
3213                         else {
3214                                 log(DEBUG,"Server names '%s' and '%s' don't match",Link_ServerName,servername);
3215                         }
3216                 }
3217                 char buffer[MAXBUF];
3218                 sprintf(buffer,"E :Access is denied (no matching link block)");
3219                 serv->SendPacket(buffer,tcp_host);
3220                 WriteOpers("CONNECT from %s denied, no matching link block",servername);
3221                 RemoveServer(tcp_host);
3222                 RemoveServer(servername);
3223                 return;
3224         }
3225         else
3226         if (token == 'U') {
3227                 // U services.chatspike.net password :ChatSpike Services
3228                 //
3229                 // non-meshed link, used by services. Everything coming from a non-meshed link is auto broadcasted.
3230                 char* servername = strtok(params," ");
3231                 char* password = strtok(NULL," ");
3232                 char* serverdesc = finalparam+2;
3233                 
3234                 char Link_ServerName[1024];
3235                 char Link_IPAddr[1024];
3236                 char Link_Port[1024];
3237                 char Link_Pass[1024];
3238                 char Link_SendPass[1024];
3239                 int LinkPort = 0;
3240
3241                 log(DEBUG,"U-token linked server detected.\n\nservername='%s' password='%s'\n\n",servername,password);
3242
3243                 
3244                 for (int j = 0; j < 32; j++)
3245                 {
3246                         if (me[j] != NULL)
3247                         {
3248                                 for (int k = 0; k < me[j]->connectors.size(); k++)
3249                                 {
3250                                         if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),servername))
3251                                         {
3252                                                 char buffer[MAXBUF];
3253                                                 sprintf(buffer,"E :Access is denied (Server exists in the mesh)");
3254                                                 serv->SendPacket(buffer,tcp_host);
3255                                                 WriteOpers("CONNECT from %s denied, \"%s\" already exists!",tcp_host,servername);
3256                                                 RemoveServer(tcp_host);
3257                                                 return;
3258                                         }
3259                                 }
3260                         }
3261                 }
3262                 
3263                 // search for a corresponding <link> block in the config files
3264                 for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
3265                 {
3266                         ConfValue("link","name",i,Link_ServerName,&config_f);
3267                         ConfValue("link","ipaddr",i,Link_IPAddr,&config_f);
3268                         ConfValue("link","port",i,Link_Port,&config_f);
3269                         ConfValue("link","recvpass",i,Link_Pass,&config_f);
3270                         ConfValue("link","sendpass",i,Link_SendPass,&config_f);
3271                         log(DEBUG,"(%d) Comparing against name='%s', ipaddr='%s', port='%s', recvpass='%s'",i,Link_ServerName,Link_IPAddr,Link_Port,Link_Pass);
3272                         LinkPort = atoi(Link_Port);
3273                         if ((!strcasecmp(Link_ServerName,servername)) && (!strcmp(Link_Pass,password)))
3274                         {
3275                                 // matching link at this end too, we're all done!
3276                                 // at this point we must begin key exchange and insert this
3277                                 // server into our 'active' table.
3278                                 for (int j = 0; j < 32; j++)
3279                                 {
3280                                         if (me[j] != NULL)
3281                                         {
3282                                                 for (int k = 0; k < me[j]->connectors.size(); k++)
3283                                                 {
3284                                                         if (!strcasecmp(me[j]->connectors[k].GetServerName().c_str(),tcp_host))
3285                                                         {
3286                                                                 char buffer[MAXBUF];
3287                                                                 log(DEBUG,"Found matching link block");
3288                                                                 me[j]->connectors[k].SetDescription(serverdesc);
3289                                                                 me[j]->connectors[k].SetServerName(servername);
3290                                                                 me[j]->connectors[k].SetState(STATE_SERVICES);
3291                                                                 sprintf(buffer,"X 0");
3292                                                                 serv->SendPacket(buffer,servername);
3293                                                                 sprintf(buffer,"s %s %s %lu :%s",ServerName,Link_SendPass,LinkPort,ServerDesc);
3294                                                                 serv->SendPacket(buffer,servername);
3295                                                                 DoSync(me[j],servername);
3296                                                                 snprintf(buffer,MAXBUF,"H %s",servername);
3297                                                                 NetSendToAllExcept(servername,buffer);
3298                                                                 WriteOpers("Non-Mesh server %s has joined the network",servername);
3299                                                                 log(DEBUG,"******** SENDING MY ROUTING TABLE! *******");
3300                                                                 NetSendMyRoutingTable();
3301                                                                 return;
3302                                                         }
3303                                                 }
3304                                         }
3305                                 }
3306                         }
3307                         else {
3308                                 log(DEBUG,"Server names '%s' and '%s' don't match",Link_ServerName,servername);
3309                         }
3310                 }
3311                 log(DEBUG,"No matching link block found");
3312                 char buffer[MAXBUF];
3313                 sprintf(buffer,"E :Access is denied (no matching link block)");
3314                 serv->SendPacket(buffer,tcp_host);
3315                 WriteOpers("CONNECT from %s denied, no matching link block",servername);
3316                 RemoveServer(tcp_host);
3317                 RemoveServer(servername);
3318                 return;
3319         }
3320         else
3321         if (token == 'E') {
3322                 char* error_message = finalparam+2;
3323                 WriteOpers("ERROR from %s: %s",tcp_host,error_message);
3324                 return;
3325         }
3326         else {
3327                 for (int j = 0; j < 32; j++)
3328                 {
3329                         if (me[j] != NULL)
3330                         {
3331                                 for (int x = 0; x < me[j]->connectors.size(); x++)
3332                                 {
3333                                         log(DEBUG,"Servers are: '%s' '%s'",tcp_host,me[j]->connectors[x].GetServerName().c_str());
3334                                         if (!strcasecmp(me[j]->connectors[x].GetServerName().c_str(),tcp_host))
3335                                         {
3336                                                 if ((me[j]->connectors[x].GetState() == STATE_CONNECTED) || (me[j]->connectors[x].GetState() == STATE_SERVICES))
3337                                                 {
3338                                                         // found a valid ircd_connector.
3339                                                         process_restricted_commands(token,params,me[j],serv,tcp_host,me[j]->connectors[x].GetServerIP(),me[j]->connectors[x].GetServerPort());
3340                                                         return;
3341                                                 }
3342                                         }
3343                                 }
3344                         }
3345                 }
3346
3347                 log(DEBUG,"Unrecognised token or unauthenticated host in datagram from %s: %c",tcp_host,token);
3348         }
3349 }
3350
3351 long duration(const char* str)
3352 {
3353         char n_field[MAXBUF];
3354         long total = 0;
3355         const char* str_end = str + strlen(str);
3356         n_field[0] = 0;
3357         
3358         for (char* i = (char*)str; i < str_end; i++)
3359         {
3360                 // if we have digits, build up a string for the value in n_field,
3361                 // up to 10 digits in size.
3362                 if ((*i >= '0') && (*i <= '9'))
3363                 {
3364                         strlcat(n_field,i,10);
3365                 }
3366                 else
3367                 {
3368                         // we dont have a digit, check for numeric tokens
3369                         switch (tolower(*i))
3370                         {
3371                                 case 's':
3372                                         total += atoi(n_field);
3373                                 break;
3374
3375                                 case 'm':
3376                                         total += (atoi(n_field)*duration_m);
3377                                 break;
3378
3379                                 case 'h':
3380                                         total += (atoi(n_field)*duration_h);
3381                                 break;
3382
3383                                 case 'd':
3384                                         total += (atoi(n_field)*duration_d);
3385                                 break;
3386
3387                                 case 'w':
3388                                         total += (atoi(n_field)*duration_w);
3389                                 break;
3390
3391                                 case 'y':
3392                                         total += (atoi(n_field)*duration_y);
3393                                 break;
3394                         }
3395                         n_field[0] = 0;
3396                 }
3397         }
3398         // add trailing seconds
3399         total += atoi(n_field);
3400         
3401         return total;
3402 }
3403
3404
3405 void handle_kline(char **parameters, int pcnt, userrec *user)
3406 {
3407         if (pcnt >= 3)
3408         {
3409                 add_kline(duration(parameters[1]),user->nick,parameters[2],parameters[0]);
3410                 if (!duration(parameters[1]))
3411                 {
3412                         WriteOpers("*** %s added permenant K-line for %s.",user->nick,parameters[0]);
3413                 }
3414                 else
3415                 {
3416                         WriteOpers("*** %s added timed K-line for %s, expires in %d seconds.",user->nick,parameters[0],duration(parameters[1]));
3417                 }
3418         }
3419         else
3420         {
3421                 if (del_kline(parameters[0]))
3422                 {
3423                         WriteOpers("*** %s Removed K-line on %s.",user->nick,parameters[0]);
3424                 }
3425                 else
3426                 {
3427                         WriteServ(user->fd,"NOTICE %s :*** K-Line %s not found in list, try /stats k.",user->nick,parameters[0]);
3428                 }
3429         }
3430         apply_lines();
3431 }
3432
3433 void handle_eline(char **parameters, int pcnt, userrec *user)
3434 {
3435         if (pcnt >= 3)
3436         {
3437                 add_eline(duration(parameters[1]),user->nick,parameters[2],parameters[0]);
3438                 if (!duration(parameters[1]))
3439                 {
3440                         WriteOpers("*** %s added permenant E-line for %s.",user->nick,parameters[0]);
3441                 }
3442                 else
3443                 {
3444                         WriteOpers("*** %s added timed E-line for %s, expires in %d seconds.",user->nick,parameters[0],duration(parameters[1]));
3445                 }
3446         }
3447         else
3448         {
3449                 if (del_eline(parameters[0]))
3450                 {
3451                         WriteOpers("*** %s Removed E-line on %s.",user->nick,parameters[0]);
3452                 }
3453                 else
3454                 {
3455                         WriteServ(user->fd,"NOTICE %s :*** E-Line %s not found in list, try /stats e.",user->nick,parameters[0]);
3456                 }
3457         }
3458         // no need to apply the lines for an eline
3459 }
3460
3461 void handle_gline(char **parameters, int pcnt, userrec *user)
3462 {
3463         char netdata[MAXBUF];
3464         if (pcnt >= 3)
3465         {
3466                 add_gline(duration(parameters[1]),user->nick,parameters[2],parameters[0]);
3467                 // # <mask> <who-set-it> <time-set> <duration> :<reason>
3468                 snprintf(netdata,MAXBUF,"# %s %s %lu %lu :%s",parameters[0],user->nick,(unsigned long)TIME,(unsigned long)duration(parameters[1]),parameters[2]);
3469                 NetSendToAll(netdata);
3470                 if (!duration(parameters[1]))
3471                 {
3472                         WriteOpers("*** %s added permenant G-line for %s.",user->nick,parameters[0]);
3473                 }
3474                 else
3475                 {
3476                         WriteOpers("*** %s added timed G-line for %s, expires in %d seconds.",user->nick,parameters[0],duration(parameters[1]));
3477                 }
3478         }
3479         else
3480         {
3481                 if (del_gline(parameters[0]))
3482                 {
3483                         // . <mask> <who-removed-it>
3484                         snprintf(netdata,MAXBUF,". %s %s",parameters[0],user->nick);
3485                         WriteOpers("*** %s Removed G-line on %s.",user->nick,parameters[0]);
3486                 }
3487                 else
3488                 {
3489                         WriteServ(user->fd,"NOTICE %s :*** G-Line %s not found in list, try /stats g.",user->nick,parameters[0]);
3490                 }
3491         }
3492         apply_lines();
3493 }
3494
3495 void handle_zline(char **parameters, int pcnt, userrec *user)
3496 {
3497         if (pcnt >= 3)
3498         {
3499                 add_zline(duration(parameters[1]),user->nick,parameters[2],parameters[0]);
3500                 if (!duration(parameters[1]))
3501                 {
3502                         WriteOpers("*** %s added permenant Z-line for %s.",user->nick,parameters[0]);
3503                 }
3504                 else
3505                 {
3506                         WriteOpers("*** %s added timed Z-line for %s, expires in %d seconds.",user->nick,parameters[0],duration(parameters[1]));
3507                 }
3508         }
3509         else
3510         {
3511                 if (del_zline(parameters[0]))
3512                 {
3513                         WriteOpers("*** %s Removed Z-line on %s.",user->nick,parameters[0]);
3514                 }
3515                 else
3516                 {
3517                         WriteServ(user->fd,"NOTICE %s :*** Z-Line %s not found in list, try /stats Z.",user->nick,parameters[0]);
3518                 }
3519         }
3520         apply_lines();
3521 }
3522
3523 void handle_qline(char **parameters, int pcnt, userrec *user)
3524 {
3525         if (pcnt >= 3)
3526         {
3527                 add_qline(duration(parameters[1]),user->nick,parameters[2],parameters[0]);
3528                 if (!duration(parameters[1]))
3529                 {
3530                         WriteOpers("*** %s added permenant Q-line for %s.",user->nick,parameters[0]);
3531                 }
3532                 else
3533                 {
3534                         WriteOpers("*** %s added timed Q-line for %s, expires in %d seconds.",user->nick,parameters[0],duration(parameters[1]));
3535                 }
3536         }
3537         else
3538         {
3539                 if (del_qline(parameters[0]))
3540                 {
3541                         WriteOpers("*** %s Removed Q-line on %s.",user->nick,parameters[0]);
3542                 }
3543                 else
3544                 {
3545                         WriteServ(user->fd,"NOTICE %s :*** Q-Line %s not found in list, try /stats k.",user->nick,parameters[0]);
3546                 }
3547         }
3548         apply_lines();
3549 }
3550
3551