summaryrefslogtreecommitdiff
path: root/src/modules/m_spanningtree.cpp
blob: 7f42456bd9e057f1e43246a25528914eb47fe18c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
/*       +------------------------------------+
 *       | Inspire Internet Relay Chat Daemon |
 *       +------------------------------------+
 *
 *  Inspire is copyright (C) 2002-2005 ChatSpike-Dev.
 *                       E-mail:
 *                <brain@chatspike.net>
 *           	  <Craig@chatspike.net>
 *     
 * Written by Craig Edwards, Craig McLure, and others.
 * This program is free but copyrighted software; see
 *            the file COPYING for details.
 *
 * ---------------------------------------------------
 */

using namespace std;

#include <stdio.h>
#include <vector>
#include <deque>
#include "globals.h"
#include "inspircd_config.h"
#ifdef GCC3
#include <ext/hash_map>
#else
#include <hash_map>
#endif
#include "users.h"
#include "channels.h"
#include "modules.h"
#include "socket.h"
#include "helperfuncs.h"
#include "inspircd.h"
#include "inspstring.h"
#include "hashcomp.h"
#include "message.h"

#ifdef GCC3
#define nspace __gnu_cxx
#else
#define nspace std
#endif

enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };

typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, irc::StrHashComp> user_hash;
extern user_hash clientlist;

const char* OneToEither[] = { "PRIVMSG", "NOTICE", NULL };
const char* OneToMany[] = { "NICK", "QUIT", "JOIN", "PART", "MODE", "INVITE", "KICK", "KILL", NULL };
const char* OneToOne[] = { "REHASH", "DIE", "TRACE", "WHOIS", NULL };

class TreeServer;
class TreeSocket;

bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target);
bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit);
bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params);

class TreeServer
{
	TreeServer* Parent;
	std::vector<TreeServer*> Children;
	std::string ServerName;
	std::string ServerDesc;
	std::string VersionString;
	int UserCount;
	int OperCount;
	TreeSocket* Socket;	// for directly connected servers this points at the socket object
	
 public:

	TreeServer()
	{
		Parent = NULL;
		ServerName = "";
		ServerDesc = "";
		VersionString = "";
		UserCount = OperCount = 0;
	}

	TreeServer(std::string Name, std::string Desc) : ServerName(Name), ServerDesc(Desc)
	{
		Parent = NULL;
		VersionString = "";
		UserCount = OperCount = 0;
	}

	TreeServer(std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock) : Parent(Above), ServerName(Name), ServerDesc(Desc), Socket(Sock)
	{
		VersionString = "";
		UserCount = OperCount = 0;
	}

	std::string GetName()
	{
		return this->ServerName;
	}

	std::string GetDesc()
	{
		return this->ServerDesc;
	}

	std::string GetVersion()
	{
		return this->VersionString;
	}

	int GetUserCount()
	{
		return this->UserCount;
	}

	int GetOperCount()
	{
		return this->OperCount;
	}

	TreeSocket* GetSocket()
	{
		return this->Socket;
	}

	TreeServer* GetParent()
	{
		return this->Parent;
	}

	unsigned int ChildCount()
	{
		return Children.size();
	}

	TreeServer* GetChild(unsigned int n)
	{
		if (n < Children.size())
		{
			return Children[n];
		}
		else
		{
			return NULL;
		}
	}

	void AddChild(TreeServer* Child)
	{
		Children.push_back(Child);
	}

	bool DelChild(TreeServer* Child)
	{
		for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
		{
			if (*a == Child)
			{
				Children.erase(a);
				return true;
			}
		}
		return false;
	}
};

class Link
{
 public:
	 std::string Name;
	 std::string IPAddr;
	 int Port;
	 std::string SendPass;
	 std::string RecvPass;
};

/* $ModDesc: Povides a spanning tree server link protocol */

Server *Srv;
ConfigReader *Conf;
TreeServer *TreeRoot;
std::vector<Link> LinkBlocks;

TreeServer* RouteEnumerate(TreeServer* Current, std::string ServerName)
{
	if (Current->GetName() == ServerName)
		return Current;
	for (unsigned int q = 0; q < Current->ChildCount(); q++)
	{
		TreeServer* found = RouteEnumerate(Current->GetChild(q),ServerName);
		if (found)
		{
			return found;
		}
	}
	return NULL;
}

// Returns the locally connected server we must route a
// message through to reach server 'ServerName'. This
// only applies to one-to-one and not one-to-many routing.
TreeServer* BestRouteTo(std::string ServerName)
{
	log(DEBUG,"Finding best route to %s",ServerName.c_str());
	// first, find the server by recursively walking the tree
	TreeServer* Found = RouteEnumerate(TreeRoot,ServerName);
	// did we find it? If not, they did something wrong, abort.
	if (!Found)
	{
		log(DEBUG,"Failed to find %s by walking tree!",ServerName.c_str());
		return NULL;
	}
	else
	{
		// The server exists, follow its parent nodes until
		// the parent of the current is 'TreeRoot', we know
		// then that this is a directly-connected server.
		while ((Found) && (Found->GetParent() != TreeRoot))
		{
			Found = Found->GetParent();
		}
		log(DEBUG,"Route to %s is via %s",ServerName.c_str(),Found->GetName().c_str());
		return Found;
	}
}

bool LookForServer(TreeServer* Current, std::string ServerName)
{
	if (ServerName == Current->GetName())
		return true;
	for (unsigned int q = 0; q < Current->ChildCount(); q++)
	{
		if (LookForServer(Current->GetChild(q),ServerName))
			return true;
	}
	return false;
}

bool IsServer(std::string ServerName)
{
	return LookForServer(TreeRoot,ServerName);
}

class TreeSocket : public InspSocket
{
	std::string myhost;
	std::string in_buffer;
	ServerState LinkState;
	std::string InboundServerName;
	std::string InboundDescription;
	
 public:

	TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
		: InspSocket(host, port, listening, maxtime)
	{
		Srv->Log(DEBUG,"Create new listening");
		myhost = host;
		this->LinkState = LISTENER;
	}

	TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
		: InspSocket(host, port, listening, maxtime)
	{
		Srv->Log(DEBUG,"Create new outbound");
		myhost = ServerName;
		this->LinkState = CONNECTING;
	}

	TreeSocket(int newfd, char* ip)
		: InspSocket(newfd, ip)
	{
		Srv->Log(DEBUG,"Associate new inbound");
		this->LinkState = WAIT_AUTH_1;
	}
	
        virtual bool OnConnected()
	{
		if (this->LinkState == CONNECTING)
		{
			Srv->SendOpers("*** Connection to "+myhost+"["+this->GetIP()+"] established.");
			// we should send our details here.
			// if the other side is satisfied, they send theirs.
			// we do not need to change state here.
			for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
			{
				if (x->Name == this->myhost)
				{
					// found who we're supposed to be connecting to, send the neccessary gubbins.
					this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
					return true;
				}
			}
		}
		log(DEBUG,"Outbound connection ERROR: Could not find the right link block!");
		return true;
	}
	
        virtual void OnError(InspSocketError e)
	{
	}

        virtual int OnDisconnect()
	{
		return true;
	}

	// recursively send the server tree with distances as hops
	void SendServers(TreeServer* Current, TreeServer* s, int hops)
	{
		char command[1024];
		for (unsigned int q = 0; q < Current->ChildCount(); q++)
		{
			TreeServer* recursive_server = Current->GetChild(q);
			if (recursive_server != s)
			{
				// :source.server SERVER server.name hops :Description
				snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
				this->WriteLine(command);
				// down to next level
				this->SendServers(recursive_server, s, hops+1);
			}
		}
	}

	bool IntroduceClient(std::string source, std::deque<std::string> params)
	{
		// NICK age nick host dhost ident +modes ip :gecos
		//       0   1    2    3      4     5    6   7
		std::string nick = params[1];
		std::string host = params[2];
		std::string dhost = params[3];
		std::string ident = params[4];
		time_t age = atoi(params[0].c_str());
		std::string modes = params[5];
		std::string ip = params[6];
		std::string gecos = params[7];
		char* tempnick = (char*)nick.c_str();
		log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
		
		user_hash::iterator iter;
		iter = clientlist.find(tempnick);
		if (iter != clientlist.end())
		{
			// nick collision
			log(DEBUG,"Nick collision on %s!%s@%s",tempnick,ident.c_str(),host.c_str());
			return true;
		}
		
		clientlist[tempnick] = new userrec();
		clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
		strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
		strlcpy(clientlist[tempnick]->host, host.c_str(),160);
		strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
		clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
		strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
		strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
		clientlist[tempnick]->registered = 7;
		clientlist[tempnick]->signon = age;
		strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
		for (int i = 0; i < MAXCHANS; i++)
		{
			clientlist[tempnick]->chans[i].channel = NULL;
			clientlist[tempnick]->chans[i].uc_modes = 0;
		}
		DoOneToAllButSender(source,"NICK",params,source);
		return true;
	}

	// send all users and their channels
	void SendUsers(TreeServer* Current)
	{
		char data[MAXBUF];
		for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
		{
			snprintf(data,MAXBUF,":%s NICK %lu %s %s %s %s +%s %s :%s",u->second->server,(unsigned long)u->second->age,u->second->nick,u->second->host,u->second->dhost,u->second->ident,u->second->modes,u->second->ip,u->second->fullname);
			this->WriteLine(data);
			if (strchr(u->second->modes,'o'))
			{
				this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
			}
			char* chl = chlist(u->second,u->second);
			if (*chl)
			{
				this->WriteLine(":"+std::string(u->second->nick)+" FJOIN "+std::string(chl));
			}
		}
	}

	void DoBurst(TreeServer* s)
	{
		log(DEBUG,"Beginning network burst");
		Srv->SendOpers("*** Bursting to "+s->GetName()+".");
		this->WriteLine("BURST");
		// Send server tree
		this->SendServers(TreeRoot,s,1);
		// Send users and their channels
		this->SendUsers(s);
		// TODO: Send everything else (channel modes etc)
		this->WriteLine("ENDBURST");
	}

        virtual bool OnDataReady()
	{
		char* data = this->Read();
		if (data)
		{
			this->in_buffer += data;
			while (in_buffer.find("\n") != std::string::npos)
			{
				char* line = (char*)in_buffer.c_str();
				std::string ret = "";
			        while ((*line != '\n') && (strlen(line)))
				{
					ret = ret + *line;
					line++;
				}
				if ((*line == '\n') || (*line == '\r'))
					line++;
				in_buffer = line;
				if (!this->ProcessLine(ret))
				{
					return false;
				}
			}
		}
		return (data != NULL);
	}

	int WriteLine(std::string line)
	{
		return this->Write(line + "\r\n");
	}

	bool Error(std::deque<std::string> params)
	{
		if (params.size() < 1)
			return false;
		std::string Errmsg = params[0];
		std::string SName = myhost;
		if (InboundServerName != "")
		{
			SName = InboundServerName;
		}
		Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
		// we will return false to cause the socket to close.
		return false;
	}

	bool Outbound_Reply_Server(std::deque<std::string> params)
	{
		if (params.size() < 4)
			return false;
		std::string servername = params[0];
		std::string password = params[1];
		int hops = atoi(params[2].c_str());
		if (hops)
		{
			this->WriteLine("ERROR :Server too far away for authentication");
			return false;
		}
		std::string description = params[3];
		for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
		{
			if ((x->Name == servername) && (x->RecvPass == password))
			{
				// Begin the sync here. this kickstarts the
				// other side, waiting in WAIT_AUTH_2 state,
				// into starting their burst, as it shows
				// that we're happy.
				this->LinkState = CONNECTED;
				// we should add the details of this server now
				// to the servers tree, as a child of the root
				// node.
				TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
				TreeRoot->AddChild(Node);
				this->DoBurst(Node);
				return true;
			}
		}
		this->WriteLine("ERROR :Invalid credentials");
		return false;
	}

	bool Inbound_Server(std::deque<std::string> params)
	{
		if (params.size() < 4)
			return false;
		std::string servername = params[0];
		std::string password = params[1];
		int hops = atoi(params[2].c_str());
		if (hops)
		{
			this->WriteLine("ERROR :Server too far away for authentication");
			return false;
		}
		std::string description = params[3];
		for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
		{
			if ((x->Name == servername) && (x->RecvPass == password))
			{
				Srv->SendOpers("*** Verified incoming server connection from "+servername+"["+this->GetIP()+"] ("+description+")");
				this->InboundServerName = servername;
				this->InboundDescription = description;
				// this is good. Send our details: Our server name and description and hopcount of 0,
				// along with the sendpass from this block.
				this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
				// move to the next state, we are now waiting for THEM.
				this->LinkState = WAIT_AUTH_2;
				return true;
			}
		}
		this->WriteLine("ERROR :Invalid credentials");
		return false;
	}

	std::deque<std::string> Split(std::string line)
	{
		std::deque<std::string> n;
		std::stringstream s(line);
		std::string param = "";
		n.clear();
		int item = 0;
		while (!s.eof())
		{
			s >> param;
			if ((param.c_str()[0] == ':') && (item))
			{
				char* str = (char*)param.c_str();
				str++;
				param = str;
				std::string append;
				while (!s.eof())
				{
					append = "";
					s >> append;
					if (append != "")
					{
						param = param + " " + append;
					}
				}
			}
			item++;
			n.push_back(param);
		}
		return n;
	}

	bool ProcessLine(std::string line)
	{
		Srv->SendToModeMask("o",WM_AND,"inbound-line: '"+line+"'");

		std::deque<std::string> params = this->Split(line);
		std::string command = "";
		std::string prefix = "";
		if (((params[0].c_str())[0] == ':') && (params.size() > 1))
		{
			prefix = params[0];
			command = params[1];
			char* pref = (char*)prefix.c_str();
			prefix = ++pref;
			params.pop_front();
			params.pop_front();
		}
		else
		{
			prefix = "";
			command = params[0];
			params.pop_front();
		}
		
		switch (this->LinkState)
		{
			TreeServer* Node;
			
			case WAIT_AUTH_1:
				// Waiting for SERVER command from remote server. Server initiating
				// the connection sends the first SERVER command, listening server
				// replies with theirs if its happy, then if the initiator is happy,
				// it starts to send its net sync, which starts the merge, otherwise
				// it sends an ERROR.
				if (command == "SERVER")
				{
					return this->Inbound_Server(params);
				}
				else if (command == "ERROR")
				{
					return this->Error(params);
				}
			break;
			case WAIT_AUTH_2:
				// Waiting for start of other side's netmerge to say they liked our
				// password.
				if (command == "SERVER")
				{
					// cant do this, they sent it to us in the WAIT_AUTH_1 state!
					// silently ignore.
					return true;
				}
				else if (command == "BURST")
				{
					this->LinkState = CONNECTED;
					Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
	                                TreeRoot->AddChild(Node);
	                                this->DoBurst(Node);
				}
				else if (command == "ERROR")
				{
					return this->Error(params);
				}
				
			break;
			case LISTENER:
				this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
				return false;
			break;
			case CONNECTING:
				if (command == "SERVER")
				{
					// another server we connected to, which was in WAIT_AUTH_1 state,
					// has just sent us their credentials. If we get this far, theyre
					// happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
					// if we're happy with this, we should send our netburst which
					// kickstarts the merge.
					return this->Outbound_Reply_Server(params);
				}
			break;
			case CONNECTED:
				// This is the 'authenticated' state, when all passwords
				// have been exchanged and anything past this point is taken
				// as gospel.
				std::string target = "";
				if ((command == "NICK") && (params.size() > 1))
				{
					return this->IntroduceClient(prefix,params);
				}
				else
				{
					// not a special inter-server command.
					// Emulate the actual user doing the command,
					// this saves us having a huge ugly parser.
					userrec* who = Srv->FindNick(prefix);
					std::string sourceserv = this->myhost;
					if (this->InboundServerName != "")
					{
						sourceserv = this->InboundServerName;
					}
					if (who)
					{
						// its a user
						target = who->server;
						char* strparams[127];
						for (unsigned int q = 0; q < params.size(); q++)
						{
							strparams[q] = (char*)params[q].c_str();
						}
						Srv->CallCommandHandler(command, strparams, params.size(), who);
					}
					else
					{
						// its not a user. Its either a server, or somethings screwed up.
						if (IsServer(prefix))
						{
							target = Srv->GetServerName();
						}
						else
						{
							log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
							return true;
						}
					}
					return DoOneToAllButSender(prefix,command,params,sourceserv);

				}
				return true;
			break;	
		}
		return true;
	}

	virtual void OnTimeout()
	{
		if (this->LinkState = CONNECTING)
		{
			Srv->SendOpers("*** CONNECT: Connection to "+myhost+" timed out.");
		}
	}

	virtual void OnClose()
	{
	}

	virtual int OnIncomingConnection(int newsock, char* ip)
	{
		TreeSocket* s = new TreeSocket(newsock, ip);
		Srv->AddSocket(s);
		return true;
	}
};

bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit)
{
	// TODO: Special stuff with privmsg and notice
	std::string FullLine = ":" + prefix + " " + command;
	for (unsigned int x = 0; x < params.size(); x++)
	{
		FullLine = FullLine + " " + params[x];
	}
	for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
	{
		TreeServer* Route = TreeRoot->GetChild(x);
		if ((Route->GetSocket()) && (Route->GetName() != omit))
		{
			TreeSocket* Sock = Route->GetSocket();
			Sock->WriteLine(FullLine);
		}
	}
	return true;
}

bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params)
{
	std::string FullLine = ":" + prefix + " " + command;
	for (unsigned int x = 0; x < params.size(); x++)
	{
		FullLine = FullLine + " " + params[x];
	}
	for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
	{
		TreeServer* Route = TreeRoot->GetChild(x);
		if (Route->GetSocket())
		{
			TreeSocket* Sock = Route->GetSocket();
			Sock->WriteLine(FullLine);
		}
	}
	return true;
}

bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target)
{
	TreeServer* Route = BestRouteTo(target);
	if (Route)
	{
		std::string FullLine = ":" + prefix + " " + command;
		for (unsigned int x = 0; x < params.size(); x++)
		{
			FullLine = FullLine + " " + params[x];
		}
		if (Route->GetSocket())
		{
			TreeSocket* Sock = Route->GetSocket();
			Sock->WriteLine(FullLine);
		}
		return true;
	}
	else
	{
		log(DEBUG,"Could not route message with target %s: %s",target.c_str(),command.c_str());
		return true;
	}
}


class ModuleSpanningTree : public Module
{
	std::vector<TreeSocket*> Bindings;

 public:

	void ReadConfiguration(bool rebind)
	{
		if (rebind)
		{
			for (int j =0; j < Conf->Enumerate("bind"); j++)
			{
				std::string Type = Conf->ReadValue("bind","type",j);
				std::string IP = Conf->ReadValue("bind","address",j);
				long Port = Conf->ReadInteger("bind","port",j,true);
				if (Type == "servers")
				{
					if (IP == "*")
					{
						IP = "";
					}
					TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
					if (listener->GetState() == I_LISTENING)
					{
						Srv->AddSocket(listener);
						Bindings.push_back(listener);
					}
					else
					{
						log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
						listener->Close();
						delete listener;
					}
				}
			}
		}
		LinkBlocks.clear();
		for (int j =0; j < Conf->Enumerate("link"); j++)
		{
			Link L;
			L.Name = Conf->ReadValue("link","name",j);
			L.IPAddr = Conf->ReadValue("link","ipaddr",j);
			L.Port = Conf->ReadInteger("link","port",j,true);
			L.SendPass = Conf->ReadValue("link","sendpass",j);
			L.RecvPass = Conf->ReadValue("link","recvpass",j);
			LinkBlocks.push_back(L);
			log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
		}
	}

	ModuleSpanningTree()
	{
		Srv = new Server;
		Conf = new ConfigReader;
		Bindings.clear();

		// Create the root of the tree
		TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());

		ReadConfiguration(true);
	}

	void HandleLinks(char** parameters, int pcnt, userrec* user)
	{
		return;
	}

	void HandleLusers(char** parameters, int pcnt, userrec* user)
	{
		return;
	}

	void HandleMap(char** parameters, int pcnt, userrec* user)
	{
		return;
	}

	int HandleSquit(char** parameters, int pcnt, userrec* user)
	{
		return 1;
	}

	int HandleConnect(char** parameters, int pcnt, userrec* user)
	{
		for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
		{
			if (Srv->MatchText(x->Name.c_str(),parameters[0]))
			{
				WriteServ(user->fd,"NOTICE %s :*** CONNECT: Connecting to server: %s (%s:%d)",user->nick,x->Name.c_str(),x->IPAddr.c_str(),x->Port);
				TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
				Srv->AddSocket(newsocket);
				return 1;
			}
		}
		WriteServ(user->fd,"NOTICE %s :*** CONNECT: No matching server could be found in the config file.",user->nick);
		return 1;
	}

	virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
	{
		if (command == "CONNECT")
		{
			return this->HandleConnect(parameters,pcnt,user);
		}
		else if (command == "SQUIT")
		{
			return this->HandleSquit(parameters,pcnt,user);
		}
		else if (command == "MAP")
		{
			this->HandleMap(parameters,pcnt,user);
			return 1;
		}
		else if (command == "LUSERS")
		{
			this->HandleLusers(parameters,pcnt,user);
			return 1;
		}
		else if (command == "LINKS")
		{
			this->HandleLinks(parameters,pcnt,user);
			return 1;
		}
		return 0;
	}

	virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
	{
		if (target_type = TYPE_USER)
		{
			// route private messages which are targetted at clients only to the server
			// which needs to receive them
			userrec* d = (userrec*)dest;
			if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
			{
				std::deque<std::string> params;
				params.clear();
				params.push_back(d->nick);
				params.push_back(text);
				DoOneToOne(user->nick,"PRIVMSG",params,d->server);
			}
		}
	}

	virtual void OnUserJoin(userrec* user, chanrec* channel)
	{
		// Only do this for local users
		if (std::string(user->server) == Srv->GetServerName())
		{
			log(DEBUG,"**** User on %s JOINS %s",user->server,channel->name);
			std::deque<std::string> params;
			params.clear();
			params.push_back(channel->name);
			if (*channel->key)
			{
				log(DEBUG,"**** With key %s",channel->key);
				// if the channel has a key, force the join by emulating the key.
				params.push_back(channel->key);
			}
			DoOneToMany(user->nick,"JOIN",params);
		}
	}

	virtual ~ModuleSpanningTree()
	{
		delete Srv;
	}

	virtual Version GetVersion()
	{
		return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
	}
};


class ModuleSpanningTreeFactory : public ModuleFactory
{
 public:
	ModuleSpanningTreeFactory()
	{
	}
	
	~ModuleSpanningTreeFactory()
	{
	}
	
	virtual Module * CreateModule()
	{
		return new ModuleSpanningTree;
	}
	
};


extern "C" void * init_module( void )
{
	return new ModuleSpanningTreeFactory;
}