summaryrefslogtreecommitdiff
path: root/src/modules/m_spanningtree/treesocket2.cpp
blob: d287d4724f3f9ffdae14bdd492346b3d950d6eb4 (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
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
#include "configreader.h"
#include "users.h"
#include "channels.h"
#include "modules.h"
#include "commands/cmd_whois.h"
#include "commands/cmd_stats.h"
#include "socket.h"
#include "inspircd.h"
#include "wildcard.h"
#include "xline.h"
#include "transport.h"
#include "socketengine.h"

#include "m_spanningtree/main.h"
#include "m_spanningtree/utils.h"
#include "m_spanningtree/treeserver.h"
#include "m_spanningtree/link.h"
#include "m_spanningtree/treesocket.h"
#include "m_spanningtree/resolvers.h"
#include "m_spanningtree/handshaketimer.h"

/* $ModDep: m_spanningtree/timesynctimer.h m_spanningtree/resolvers.h m_spanningtree/main.h m_spanningtree/utils.h m_spanningtree/treeserver.h m_spanningtree/link.h m_spanningtree/treesocket.h */

int TreeSocket::WriteLine(std::string line)
{
	Instance->Log(DEBUG, "-> %s", line.c_str());
	line.append("\r\n");
	return this->Write(line);
}

/* Handle ERROR command */
bool TreeSocket::Error(std::deque<std::string> &params)
{
	if (params.size() < 1)
		return false;
	this->Instance->SNO->WriteToSnoMask('l',"ERROR from %s: %s",(InboundServerName != "" ? InboundServerName.c_str() : myhost.c_str()),params[0].c_str());
	/* we will return false to cause the socket to close. */
	return false;
}

/** remote MOTD. leet, huh? */
bool TreeSocket::Motd(const std::string &prefix, std::deque<std::string> &params)
{
	if (params.size() > 0)
	{
		if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
		{
			/* It's for our server */
			string_list results;
			userrec* source = this->Instance->FindNick(prefix);

			if (source)
			{
				std::deque<std::string> par;
				par.push_back(prefix);
				par.push_back("");

				if (!Instance->Config->MOTD.size())
				{
					par[1] = std::string("::")+Instance->Config->ServerName+" 422 "+source->nick+" :Message of the day file is missing.";
					Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
					return true;
				}

				par[1] = std::string("::")+Instance->Config->ServerName+" 375 "+source->nick+" :"+Instance->Config->ServerName+" message of the day";
				Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);

				for (unsigned int i = 0; i < Instance->Config->MOTD.size(); i++)
				{
					par[1] = std::string("::")+Instance->Config->ServerName+" 372 "+source->nick+" :- "+Instance->Config->MOTD[i];
					Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
				}

				par[1] = std::string("::")+Instance->Config->ServerName+" 376 "+source->nick+" End of message of the day.";
				Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
			}
		}
		else
		{
			/* Pass it on */
			userrec* source = this->Instance->FindNick(prefix);
			if (source)
				Utils->DoOneToOne(prefix, "MOTD", params, params[0]);
		}
	}
	return true;
}

/** remote ADMIN. leet, huh? */
bool TreeSocket::Admin(const std::string &prefix, std::deque<std::string> &params)
{
	if (params.size() > 0)
	{
		if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
		{
			/* It's for our server */
			string_list results;
			userrec* source = this->Instance->FindNick(prefix);
			if (source)
			{
				std::deque<std::string> par;
				par.push_back(prefix);
				par.push_back("");
				par[1] = std::string("::")+Instance->Config->ServerName+" 256 "+source->nick+" :Administrative info for "+Instance->Config->ServerName;
				Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
				par[1] = std::string("::")+Instance->Config->ServerName+" 257 "+source->nick+" :Name     - "+Instance->Config->AdminName;
				Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
				par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :Nickname - "+Instance->Config->AdminNick;
				Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
				par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :E-Mail   - "+Instance->Config->AdminEmail;
				Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
			}
		}
		else
		{
			/* Pass it on */
			userrec* source = this->Instance->FindNick(prefix);
			if (source)
				Utils->DoOneToOne(prefix, "ADMIN", params, params[0]);
		}
	}
	return true;
}

bool TreeSocket::Stats(const std::string &prefix, std::deque<std::string> &params)
{
	/* Get the reply to a STATS query if it matches this servername,
	 * and send it back as a load of PUSH queries
	 */
	if (params.size() > 1)
	{
		if (this->Instance->MatchText(this->Instance->Config->ServerName, params[1]))
		{
			/* It's for our server */
			string_list results;
			userrec* source = this->Instance->FindNick(prefix);
			if (source)
			{
				std::deque<std::string> par;
				par.push_back(prefix);
				par.push_back("");
				DoStats(this->Instance, *(params[0].c_str()), source, results);
				for (size_t i = 0; i < results.size(); i++)
				{
					par[1] = "::" + results[i];
					Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
				}
			}
		}
		else
		{
			/* Pass it on */
			userrec* source = this->Instance->FindNick(prefix);
			if (source)
				Utils->DoOneToOne(prefix, "STATS", params, params[1]);
		}
	}
	return true;
}


/** Because the core won't let users or even SERVERS set +o,
 * we use the OPERTYPE command to do this.
 */
bool TreeSocket::OperType(const std::string &prefix, std::deque<std::string> &params)
{
	if (params.size() != 1)
		return true;
	std::string opertype = params[0];
	userrec* u = this->Instance->FindNick(prefix);
	if (u)
	{
		u->modes[UM_OPERATOR] = 1;
		this->Instance->all_opers.push_back(u);
		strlcpy(u->oper,opertype.c_str(),NICKMAX-1);
		Utils->DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
		this->Instance->SNO->WriteToSnoMask('o',"From %s: User %s (%s@%s) is now an IRC operator of type %s",u->server, u->nick,u->ident,u->host,irc::Spacify(opertype.c_str()));
	}
	return true;
}

/** Because Andy insists that services-compatible servers must
 * implement SVSNICK and SVSJOIN, that's exactly what we do :p
 */
bool TreeSocket::ForceNick(const std::string &prefix, std::deque<std::string> &params)
{
	if (params.size() < 3)
		return true;

	userrec* u = this->Instance->FindNick(params[0]);

	if (u)
	{
		Utils->DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
		if (IS_LOCAL(u))
		{
			std::deque<std::string> par;
			par.push_back(params[1]);
			if (!u->ForceNickChange(params[1].c_str()))
			{
				userrec::QuitUser(this->Instance, u, "Nickname collision");
				return true;
			}
			u->age = atoi(params[2].c_str());
		}
	}
	return true;
}

/*
 * Remote SQUIT (RSQUIT). Routing works similar to SVSNICK: Route it to the server that the target is connected to locally,
 * then let that server do the dirty work (squit it!). Example:
 * A -> B -> C -> D: oper on A squits D, A routes to B, B routes to C, C notices D connected locally, kills it. -- w00t
 */
bool TreeSocket::RemoteSquit(const std::string &prefix, std::deque<std::string> &params)
{
	/* ok.. :w00t RSQUIT jupe.barafranca.com :reason here */
	if (params.size() < 2)
		return true;

	TreeServer* s = Utils->FindServerMask(params[0]);

	if (s)
	{
		if (s == Utils->TreeRoot)
		{
			this->Instance->SNO->WriteToSnoMask('l',"What the fuck, I recieved a remote SQUIT for myself? :< (from %s", prefix.c_str());
			return true;
		}

		TreeSocket* sock = s->GetSocket();

		if (sock)
		{
			/* it's locally connected, KILL IT! */
			Instance->SNO->WriteToSnoMask('l',"RSQUIT: Server \002%s\002 removed from network by %s: %s", params[0].c_str(), prefix.c_str(), params[1].c_str());
			sock->Squit(s,"Server quit by " + prefix + ": " + params[1]);
			Instance->SE->DelFd(sock);
			sock->Close();
			delete sock;
		}
		else
		{
			/* route the rsquit */
			params[1] = ":" + params[1];
			Utils->DoOneToOne(prefix, "RSQUIT", params, params[0]);
		}
	}
	else
	{
		/* mother fucker! it doesn't exist */
	}

	return true;
}

bool TreeSocket::ServiceJoin(const std::string &prefix, std::deque<std::string> &params)
{
	if (params.size() < 2)
		return true;

	userrec* u = this->Instance->FindNick(params[0]);

	if (u)
	{
		/* only join if it's local, otherwise just pass it on! */
		if (IS_LOCAL(u))
			chanrec::JoinUser(this->Instance, u, params[1].c_str(), false);
		Utils->DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
	}
	return true;
}

bool TreeSocket::RemoteRehash(const std::string &prefix, std::deque<std::string> &params)
{
	if (params.size() < 1)
		return false;

	std::string servermask = params[0];

	if (this->Instance->MatchText(this->Instance->Config->ServerName,servermask))
	{
		this->Instance->SNO->WriteToSnoMask('l',"Remote rehash initiated by \002"+prefix+"\002.");
		this->Instance->RehashServer();
		Utils->ReadConfiguration(false);
		InitializeDisabledCommands(Instance->Config->DisabledCommands, Instance);
	}
	Utils->DoOneToAllButSender(prefix,"REHASH",params,prefix);
	return true;
}

bool TreeSocket::RemoteKill(const std::string &prefix, std::deque<std::string> &params)
{
	if (params.size() != 2)
		return true;

	std::string nick = params[0];
	userrec* u = this->Instance->FindNick(prefix);
	userrec* who = this->Instance->FindNick(nick);

	if (who)
	{
		/* Prepend kill source, if we don't have one */
		std::string sourceserv = prefix;
		if (u)
		{
			sourceserv = u->server;
		}
		if (*(params[1].c_str()) != '[')
		{
			params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
		}
		std::string reason = params[1];
		params[1] = ":" + params[1];
		Utils->DoOneToAllButSender(prefix,"KILL",params,sourceserv);
		who->Write(":%s KILL %s :%s (%s)", sourceserv.c_str(), who->nick, sourceserv.c_str(), reason.c_str());
		userrec::QuitUser(this->Instance,who,reason);
	}
	return true;
}

bool TreeSocket::LocalPong(const std::string &prefix, std::deque<std::string> &params)
{
	if (params.size() < 1)
		return true;

	if (params.size() == 1)
	{
		TreeServer* ServerSource = Utils->FindServer(prefix);
		if (ServerSource)
		{
			ServerSource->SetPingFlag();
		}
	}
	else
	{
		std::string forwardto = params[1];
		if (forwardto == this->Instance->Config->ServerName)
		{
			/*
			 * this is a PONG for us
			 * if the prefix is a user, check theyre local, and if they are,
			 * dump the PONG reply back to their fd. If its a server, do nowt.
			 * Services might want to send these s->s, but we dont need to yet.
			 */
			userrec* u = this->Instance->FindNick(prefix);
			if (u)
			{
				u->WriteServ("PONG %s %s",params[0].c_str(),params[1].c_str());
			}
		}
		else
		{
			// not for us, pass it on :)
			Utils->DoOneToOne(prefix,"PONG",params,forwardto);
		}
	}

	return true;
}

bool TreeSocket::MetaData(const std::string &prefix, std::deque<std::string> &params)
{
	if (params.size() < 2)
		return true;
	else
		params.push_back("");
	TreeServer* ServerSource = Utils->FindServer(prefix);
	if (ServerSource)
	{
		if (params[0] == "*")
		{
			FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_OTHER,NULL,params[1],params[2]));
		}
		else if (*(params[0].c_str()) == '#')
		{
			chanrec* c = this->Instance->FindChan(params[0]);
			if (c)
			{
				FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));
			}
		}
		else if (*(params[0].c_str()) != '#')
		{
			userrec* u = this->Instance->FindNick(params[0]);
			if (u)
			{
				FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));
			}
		}
	}

	params[2] = ":" + params[2];
	Utils->DoOneToAllButSender(prefix,"METADATA",params,prefix);
	return true;
}

bool TreeSocket::ServerVersion(const std::string &prefix, std::deque<std::string> &params)
{
	if (params.size() < 1)
		return true;

	TreeServer* ServerSource = Utils->FindServer(prefix);

	if (ServerSource)
	{
		ServerSource->SetVersion(params[0]);
	}
	params[0] = ":" + params[0];
	Utils->DoOneToAllButSender(prefix,"VERSION",params,prefix);
	return true;
}

bool TreeSocket::ChangeHost(const std::string &prefix, std::deque<std::string> &params)
{
	if (params.size() < 1)
		return true;
	userrec* u = this->Instance->FindNick(prefix);

	if (u)
	{
		u->ChangeDisplayedHost(params[0].c_str());
		Utils->DoOneToAllButSender(prefix,"FHOST",params,u->server);
	}
	return true;
}

bool TreeSocket::AddLine(const std::string &prefix, std::deque<std::string> &params)
{
	if (params.size() < 6)
		return true;
	bool propogate = false;
	if (!this->bursting)
		Utils->lines_to_apply = 0;
	switch (*(params[0].c_str()))
	{
		case 'Z':
			propogate = Instance->XLines->add_zline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
			Instance->XLines->zline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
			if (propogate)
				Utils->lines_to_apply |= APPLY_ZLINES;
		break;
		case 'Q':
			propogate = Instance->XLines->add_qline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
			Instance->XLines->qline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
			if (propogate)
				Utils->lines_to_apply |= APPLY_QLINES;
		break;
		case 'E':
			propogate = Instance->XLines->add_eline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
			Instance->XLines->eline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
		break;
		case 'G':
			propogate = Instance->XLines->add_gline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
			Instance->XLines->gline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
			if (propogate)
				Utils->lines_to_apply |= APPLY_GLINES;
		break;
		case 'K':
			propogate = Instance->XLines->add_kline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
			if (propogate)
				Utils->lines_to_apply |= APPLY_KLINES;
		break;
		default:
			/* Just in case... */
			this->Instance->SNO->WriteToSnoMask('x',"\2WARNING\2: Invalid xline type '"+params[0]+"' sent by server "+prefix+", ignored!");
			propogate = false;
		break;
	}
	/* Send it on its way */
	if (propogate)
	{
		if (atoi(params[4].c_str()))
		{
			this->Instance->SNO->WriteToSnoMask('x',"%s Added %cLINE on %s to expire in %lu seconds (%s).",prefix.c_str(),*(params[0].c_str()),params[1].c_str(),atoi(params[4].c_str()),params[5].c_str());
		}
		else
		{
			this->Instance->SNO->WriteToSnoMask('x',"%s Added permenant %cLINE on %s (%s).",prefix.c_str(),*(params[0].c_str()),params[1].c_str(),params[5].c_str());
		}
		params[5] = ":" + params[5];
		Utils->DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
	}
	if (!this->bursting)
	{
		Instance->XLines->apply_lines(Utils->lines_to_apply);
		Utils->lines_to_apply = 0;
	}
	return true;
}

bool TreeSocket::ChangeName(const std::string &prefix, std::deque<std::string> &params)
{
	if (params.size() < 1)
		return true;
	userrec* u = this->Instance->FindNick(prefix);
	if (u)
	{
		u->ChangeName(params[0].c_str());
		params[0] = ":" + params[0];
		Utils->DoOneToAllButSender(prefix,"FNAME",params,u->server);
	}
	return true;
}

bool TreeSocket::Whois(const std::string &prefix, std::deque<std::string> &params)
{
	if (params.size() < 1)
		return true;
	userrec* u = this->Instance->FindNick(prefix);
	if (u)
	{
		// an incoming request
		if (params.size() == 1)
		{
			userrec* x = this->Instance->FindNick(params[0]);
			if ((x) && (IS_LOCAL(x)))
			{
				userrec* x = this->Instance->FindNick(params[0]);
				char signon[MAXBUF];
				char idle[MAXBUF];
				snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
				snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-Instance->Time(true)));
				std::deque<std::string> par;
				par.push_back(prefix);
				par.push_back(signon);
				par.push_back(idle);
				// ours, we're done, pass it BACK
				Utils->DoOneToOne(params[0],"IDLE",par,u->server);
			}
			else
			{
				// not ours pass it on
				Utils->DoOneToOne(prefix,"IDLE",params,x->server);
			}
		}
		else if (params.size() == 3)
		{
			std::string who_did_the_whois = params[0];
			userrec* who_to_send_to = this->Instance->FindNick(who_did_the_whois);
			if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
			{
				// an incoming reply to a whois we sent out
				std::string nick_whoised = prefix;
				unsigned long signon = atoi(params[1].c_str());
				unsigned long idle = atoi(params[2].c_str());
				if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
					do_whois(this->Instance,who_to_send_to,u,signon,idle,nick_whoised.c_str());
			}
			else
			{
				// not ours, pass it on
				Utils->DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
			}
		}
	}
	return true;
}

bool TreeSocket::Push(const std::string &prefix, std::deque<std::string> &params)
{
	if (params.size() < 2)
		return true;
	userrec* u = this->Instance->FindNick(params[0]);
	if (!u)
		return true;
	if (IS_LOCAL(u))
	{
		u->Write(params[1]);
	}
	else
	{
		// continue the raw onwards
		params[1] = ":" + params[1];
		Utils->DoOneToOne(prefix,"PUSH",params,u->server);
	}
	return true;
}

bool TreeSocket::HandleSetTime(const std::string &prefix, std::deque<std::string> &params)
{
	if (!params.size() || !Utils->EnableTimeSync)
		return true;

	bool force = false;

	if ((params.size() == 2) && (params[1] == "FORCE"))
		force = true;

	time_t rts = atoi(params[0].c_str());
	time_t us = Instance->Time(true);

	if (rts == us)
	{
		Utils->DoOneToAllButSender(prefix, "TIMESET", params, prefix);
	}
	else if (force || (rts < us))
	{
		int old = Instance->SetTimeDelta(rts - us);
		Instance->Log(DEBUG, "%s TS (diff %d) from %s applied (old delta was %d)", (force) ? "Forced" : "Lower", rts - us, prefix.c_str(), old);

		Utils->DoOneToAllButSender(prefix, "TIMESET", params, prefix);
	}
	else
	{
		Instance->Log(DEBUG, "Higher TS (diff %d) from %s overridden", us - rts, prefix.c_str());

		std::deque<std::string> oparams;
		oparams.push_back(ConvToStr(us));

		Utils->DoOneToMany(prefix, "TIMESET", oparams);
	}

	return true;
}

bool TreeSocket::Time(const std::string &prefix, std::deque<std::string> &params)
{
	// :source.server TIME remote.server sendernick
	// :remote.server TIME source.server sendernick TS
	if (params.size() == 2)
	{
		// someone querying our time?
		if (this->Instance->Config->ServerName == params[0])
		{
			userrec* u = this->Instance->FindNick(params[1]);
			if (u)
			{
				params.push_back(ConvToStr(Instance->Time(false)));
				params[0] = prefix;
				Utils->DoOneToOne(this->Instance->Config->ServerName,"TIME",params,params[0]);
			}
		}
		else
		{
			// not us, pass it on
			userrec* u = this->Instance->FindNick(params[1]);
			if (u)
				Utils->DoOneToOne(prefix,"TIME",params,params[0]);
		}
	}
	else if (params.size() == 3)
	{
		// a response to a previous TIME
		userrec* u = this->Instance->FindNick(params[1]);
		if ((u) && (IS_LOCAL(u)))
		{
			time_t rawtime = atol(params[2].c_str());
			struct tm * timeinfo;
			timeinfo = localtime(&rawtime);
			char tms[26];
			snprintf(tms,26,"%s",asctime(timeinfo));
			tms[24] = 0;
			u->WriteServ("391 %s %s :%s",u->nick,prefix.c_str(),tms);
		}
		else
		{
			if (u)
				Utils->DoOneToOne(prefix,"TIME",params,u->server);
		}
	}
	return true;
}

bool TreeSocket::LocalPing(const std::string &prefix, std::deque<std::string> &params)
{
	if (params.size() < 1)
		return true;
	if (params.size() == 1)
	{
		std::string stufftobounce = params[0];
		this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" PONG "+stufftobounce);
		return true;
	}
	else
	{
		std::string forwardto = params[1];
		if (forwardto == this->Instance->Config->ServerName)
		{
			// this is a ping for us, send back PONG to the requesting server
			params[1] = params[0];
			params[0] = forwardto;
			Utils->DoOneToOne(forwardto,"PONG",params,params[1]);
		}
		else
		{
			// not for us, pass it on :)
			Utils->DoOneToOne(prefix,"PING",params,forwardto);
		}
		return true;
	}
}

/** TODO: This creates a total mess of output and needs to really use irc::modestacker.
 */
bool TreeSocket::RemoveStatus(const std::string &prefix, std::deque<std::string> &params)
{
	if (params.size() < 1)
		return true;
	chanrec* c = Instance->FindChan(params[0]);
	if (c)
	{
		for (char modeletter = 'A'; modeletter <= 'z'; modeletter++)
		{
			ModeHandler* mh = Instance->Modes->FindMode(modeletter, MODETYPE_CHANNEL);
			if (mh)
				mh->RemoveMode(c);
		}
	}
	return true;
}

bool TreeSocket::RemoteServer(const std::string &prefix, std::deque<std::string> &params)
{
	if (params.size() < 4)
		return false;
	std::string servername = params[0];
	std::string password = params[1];
	// hopcount is not used for a remote server, we calculate this ourselves
	std::string description = params[3];
	TreeServer* ParentOfThis = Utils->FindServer(prefix);
	if (!ParentOfThis)
	{
		this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
		return false;
	}
	TreeServer* CheckDupe = Utils->FindServer(servername);
	if (CheckDupe)
	{
		this->WriteLine("ERROR :Server "+servername+" already exists!");
		this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+servername+"\2 denied, already exists");
		return false;
	}
	TreeServer* Node = new TreeServer(this->Utils,this->Instance,servername,description,ParentOfThis,NULL);
	ParentOfThis->AddChild(Node);
	params[3] = ":" + params[3];
	Utils->DoOneToAllButSender(prefix,"SERVER",params,prefix);
	this->Instance->SNO->WriteToSnoMask('l',"Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
	return true;
}

bool TreeSocket::Outbound_Reply_Server(std::deque<std::string> &params)
{
	if (params.size() < 4)
		return false;

	irc::string servername = params[0].c_str();
	std::string sname = 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");
		this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
		return false;
	}
	std::string description = params[3];
	for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
	{
		if ((x->Name == servername) && (x->RecvPass == password))
		{
			TreeServer* CheckDupe = Utils->FindServer(sname);
			if (CheckDupe)
			{
				this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
				this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
				return false;
			}
			// 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(this->Utils,this->Instance,sname,description,Utils->TreeRoot,this);
			Utils->TreeRoot->AddChild(Node);
			params[3] = ":" + params[3];
			Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,sname);
			this->bursting = true;
			this->DoBurst(Node);
			return true;
		}
	}
	this->WriteLine("ERROR :Invalid credentials");
	this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
	return false;
}

bool TreeSocket::Inbound_Server(std::deque<std::string> &params)
{
	if (params.size() < 4)
		return false;
	irc::string servername = params[0].c_str();
	std::string sname = 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");
		this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
		return false;
	}
	std::string description = params[3];
	for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
	{
		if ((x->Name == servername) && (x->RecvPass == password))
		{
			TreeServer* CheckDupe = Utils->FindServer(sname);
			if (CheckDupe)
			{
				this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
				this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
				return false;
			}
			this->Instance->SNO->WriteToSnoMask('l',"Verified incoming server connection from \002"+sname+"\002["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] ("+description+")");
			if (this->Hook)
			{
				std::string name = InspSocketNameRequest((Module*)Utils->Creator, this->Hook).Send();
				this->Instance->SNO->WriteToSnoMask('l',"Connection from \2"+sname+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] using transport \2"+name+"\2");
			}

			this->InboundServerName = sname;
			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(std::string("SERVER ")+this->Instance->Config->ServerName+" "+x->SendPass+" 0 :"+this->Instance->Config->ServerDesc);
			// move to the next state, we are now waiting for THEM.
			this->LinkState = WAIT_AUTH_2;
			return true;
		}
	}
	this->WriteLine("ERROR :Invalid credentials");
	this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
	return false;
}

void TreeSocket::Split(const std::string &line, std::deque<std::string> &n)
{
	n.clear();
	irc::tokenstream tokens(line);
	std::string param;
	while ((param = tokens.GetToken()) != "")
		n.push_back(param);
	return;
}

bool TreeSocket::ProcessLine(std::string &line)
{
	std::deque<std::string> params;
	irc::string command;
	std::string prefix;

	line = line.substr(0, line.find_first_of("\r\n"));

	if (line.empty())
		return true;

	Instance->Log(DEBUG, "<- %s", line.c_str());

	this->Split(line.c_str(),params);

	if ((params[0][0] == ':') && (params.size() > 1))
	{
		prefix = params[0].substr(1);
		params.pop_front();
	}
	command = params[0].c_str();
	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 == "PASS")
			{
				/* Silently ignored */
			}
			else if (command == "SERVER")
			{
				return this->Inbound_Server(params);
			}
			else if (command == "ERROR")
			{
				return this->Error(params);
			}
			else if (command == "USER")
			{
				this->WriteLine("ERROR :Client connections to this port are prohibited.");
				return false;
			}
			else if (command == "CAPAB")
			{
				return this->Capab(params);
			}
			else if ((command == "U") || (command == "S"))
			{
				this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
				return false;
			}
			else
			{
				std::string error("ERROR :Invalid command in negotiation phase: ");
				error.append(command.c_str());
				this->WriteLine(error);
				return false;
			}
		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 == "U") || (command == "S"))
			{
				this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
				return false;
			}
			else if (command == "BURST")
			{
				if (params.size() && Utils->EnableTimeSync)
				{
					/* If a time stamp is provided, apply synchronization */
					bool force = false;
					time_t them = atoi(params[0].c_str());
					time_t us = Instance->Time(false);
					int delta = them - us;
					if ((params.size() == 2) && (params[1] == "FORCE"))
						force = true;
					if ((delta < -600) || (delta > 600))
					{
						this->Instance->SNO->WriteToSnoMask('l',"\2ERROR\2: Your clocks are out by %d seconds (this is more than ten minutes). Link aborted, \2PLEASE SYNC YOUR CLOCKS!\2",abs(delta));
						this->WriteLine("ERROR :Your clocks are out by "+ConvToStr(abs(delta))+" seconds (this is more than ten minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
						return false;
					}

					if (force || (us > them))
					{
						this->Instance->SetTimeDelta(them - us);
						// Send this new timestamp to any other servers
						Utils->DoOneToMany(Utils->TreeRoot->GetName(), "TIMESET", params);
					}
					else
					{
						// Override the timestamp
						this->WriteLine(":" + Utils->TreeRoot->GetName() + " TIMESET " + ConvToStr(us));
					}
				}
				this->LinkState = CONNECTED;
				Node = new TreeServer(this->Utils,this->Instance,InboundServerName,InboundDescription,Utils->TreeRoot,this);
				Utils->TreeRoot->AddChild(Node);
				params.clear();
				params.push_back(InboundServerName);
				params.push_back("*");
				params.push_back("1");
				params.push_back(":"+InboundDescription);
				Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,InboundServerName);
				this->bursting = true;
				this->DoBurst(Node);
			}
			else if (command == "ERROR")
			{
				return this->Error(params);
			}
			else if (command == "CAPAB")
			{
				return this->Capab(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);
			}
			else if (command == "ERROR")
			{
				return this->Error(params);
			}
		break;
		case CONNECTED:
			// This is the 'authenticated' state, when all passwords
			// have been exchanged and anything past this point is taken
			// as gospel.

			if (prefix != "")
			{
				std::string direction = prefix;
				userrec* t = this->Instance->FindNick(prefix);
				if (t)
				{
					direction = t->server;
				}
				TreeServer* route_back_again = Utils->BestRouteTo(direction);
				if ((!route_back_again) || (route_back_again->GetSocket() != this))
				{
					if (route_back_again)
						Instance->Log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
					return true;
				}
				/* Fix by brain:
				 * When there is activity on the socket, reset the ping counter so
				 * that we're not wasting bandwidth pinging an active server.
				 */
				route_back_again->SetNextPingTime(time(NULL) + 60);
				route_back_again->SetPingFlag();
			}

			if (command == "SVSMODE")
			{
				/* Services expects us to implement
				 * SVSMODE. In inspircd its the same as
				 * MODE anyway.
				 */
				command = "MODE";
			}
			std::string target = "";
			/* Yes, know, this is a mess. Its reasonably fast though as we're
			 * working with std::string here.
			 */
			if ((command == "NICK") && (params.size() > 1))
			{
				return this->IntroduceClient(prefix,params);
			}
			else if (command == "FJOIN")
			{
				return this->ForceJoin(prefix,params);
			}
			else if (command == "STATS")
			{
				return this->Stats(prefix, params);
			}
			else if (command == "MOTD")
			{
				return this->Motd(prefix, params);
			}
			else if (command == "ADMIN")
			{
				return this->Admin(prefix, params);
			}
			else if (command == "SERVER")
			{
				return this->RemoteServer(prefix,params);
			}
			else if (command == "ERROR")
			{
				return this->Error(params);
			}
			else if (command == "OPERTYPE")
			{
				return this->OperType(prefix,params);
			}
			else if (command == "FMODE")
			{
				return this->ForceMode(prefix,params);
			}
			else if (command == "KILL")
			{
				return this->RemoteKill(prefix,params);
			}
			else if (command == "FTOPIC")
			{
				return this->ForceTopic(prefix,params);
			}
			else if (command == "REHASH")
			{
				return this->RemoteRehash(prefix,params);
			}
			else if (command == "METADATA")
			{
				return this->MetaData(prefix,params);
			}
			else if (command == "REMSTATUS")
			{
				return this->RemoveStatus(prefix,params);
			}
			else if (command == "PING")
			{
				/*
				 * We just got a ping from a server that's bursting.
				 * This can't be right, so set them to not bursting, and
				 * apply their lines.
				 */
				if (this->bursting)
				{
					this->bursting = false;
					Instance->XLines->apply_lines(Utils->lines_to_apply);
					Utils->lines_to_apply = 0;
				}
				if (prefix == "")
				{
					prefix = this->GetName();
				}
				return this->LocalPing(prefix,params);
			}
			else if (command == "PONG")
			{
				/*
				 * We just got a pong from a server that's bursting.
				 * This can't be right, so set them to not bursting, and
				 * apply their lines.
				 */
				if (this->bursting)
				{
					this->bursting = false;
					Instance->XLines->apply_lines(Utils->lines_to_apply);
					Utils->lines_to_apply = 0;
				}
				if (prefix == "")
				{
					prefix = this->GetName();
				}
				return this->LocalPong(prefix,params);
			}
			else if (command == "VERSION")
			{
				return this->ServerVersion(prefix,params);
			}
			else if (command == "FHOST")
			{
				return this->ChangeHost(prefix,params);
			}
			else if (command == "FNAME")
			{
				return this->ChangeName(prefix,params);
			}
			else if (command == "ADDLINE")
			{
				return this->AddLine(prefix,params);
			}
			else if (command == "SVSNICK")
			{
				if (prefix == "")
				{
					prefix = this->GetName();
				}
				return this->ForceNick(prefix,params);
			}
			else if (command == "RSQUIT")
			{
				return this->RemoteSquit(prefix, params);
			}
			else if (command == "IDLE")
			{
				return this->Whois(prefix,params);
			}
			else if (command == "PUSH")
			{
				return this->Push(prefix,params);
			}
			else if (command == "TIMESET")
			{
				return this->HandleSetTime(prefix, params);
			}
			else if (command == "TIME")
			{
				return this->Time(prefix,params);
			}
			else if ((command == "KICK") && (Utils->IsServer(prefix)))
			{
				std::string sourceserv = this->myhost;
				if (params.size() == 3)
				{
					userrec* user = this->Instance->FindNick(params[1]);
					chanrec* chan = this->Instance->FindChan(params[0]);
					if (user && chan)
					{
						if (!chan->ServerKickUser(user, params[2].c_str(), false))
							/* Yikes, the channels gone! */
							delete chan;
					}
				}
				if (this->InboundServerName != "")
				{
					sourceserv = this->InboundServerName;
				}
				return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
			}
			else if (command == "SVSJOIN")
			{
				if (prefix == "")
				{
					prefix = this->GetName();
				}
				return this->ServiceJoin(prefix,params);
			}
			else if (command == "SQUIT")
			{
				if (params.size() == 2)
				{
					this->Squit(Utils->FindServer(params[0]),params[1]);
				}
				return true;
			}
			else if (command == "OPERNOTICE")
			{
				std::string sourceserv = this->myhost;
				if (this->InboundServerName != "")
					sourceserv = this->InboundServerName;
				if (params.size() >= 1)
					Instance->WriteOpers("*** From " + sourceserv + ": " + params[0]);
				return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
			}
			else if (command == "MODENOTICE")
			{
				std::string sourceserv = this->myhost;
				if (this->InboundServerName != "")
					sourceserv = this->InboundServerName;
				if (params.size() >= 2)
				{
					Instance->WriteMode(params[0].c_str(), WM_AND, "*** From %s: %s", sourceserv.c_str(), params[1].c_str());
				}
				return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
			}
			else if (command == "SNONOTICE")
			{
				std::string sourceserv = this->myhost;
				if (this->InboundServerName != "")
					sourceserv = this->InboundServerName;
				if (params.size() >= 2)
				{
					Instance->SNO->WriteToSnoMask(*(params[0].c_str()), "From " + sourceserv + ": "+ params[1]);
				}
				return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
			}
			else if (command == "ENDBURST")
			{
				this->bursting = false;
				Instance->XLines->apply_lines(Utils->lines_to_apply);
				Utils->lines_to_apply = 0;
				std::string sourceserv = this->myhost;
				if (this->InboundServerName != "")
				{
					sourceserv = this->InboundServerName;
				}
				this->Instance->SNO->WriteToSnoMask('l',"Received end of netburst from \2%s\2",sourceserv.c_str());

				Event rmode((char*)sourceserv.c_str(), (Module*)Utils->Creator, "new_server");
				rmode.Send(Instance);

				return true;
			}
			else
			{
				// not a special inter-server command.
				// Emulate the actual user doing the command,
				// this saves us having a huge ugly parser.
				userrec* who = this->Instance->FindNick(prefix);
				std::string sourceserv = this->myhost;
				if (this->InboundServerName != "")
				{
					sourceserv = this->InboundServerName;
				}
				if ((!who) && (command == "MODE"))
				{
					if (Utils->IsServer(prefix))
					{
						const char* modelist[127];
						for (size_t i = 0; i < params.size(); i++)
							modelist[i] = params[i].c_str();
						userrec* fake = new userrec(Instance);
						fake->SetFd(FD_MAGIC_NUMBER);
						this->Instance->SendMode(modelist, params.size(), fake);

						delete fake;
						/* Hot potato! pass it on! */
						return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
					}
				}
				if (who)
				{
					if ((command == "NICK") && (params.size() > 0))
					{
						/* On nick messages, check that the nick doesnt
						 * already exist here. If it does, kill their copy,
						 * and our copy.
						 */
						userrec* x = this->Instance->FindNick(params[0]);
						if ((x) && (x != who))
						{
							std::deque<std::string> p;
							p.push_back(params[0]);
							p.push_back("Nickname collision ("+prefix+" -> "+params[0]+")");
							Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
							p.clear();
							p.push_back(prefix);
							p.push_back("Nickname collision");
							Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
							userrec::QuitUser(this->Instance,x,"Nickname collision ("+prefix+" -> "+params[0]+")");
							userrec* y = this->Instance->FindNick(prefix);
							if (y)
							{
								userrec::QuitUser(this->Instance,y,"Nickname collision");
							}
							return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
						}
					}
					// its a user
					target = who->server;
					const char* strparams[127];
					for (unsigned int q = 0; q < params.size(); q++)
					{
						strparams[q] = params[q].c_str();
					}
					switch (this->Instance->CallCommandHandler(command.c_str(), strparams, params.size(), who))
					{
						case CMD_INVALID:
							this->WriteLine("ERROR :Unrecognised command '"+std::string(command.c_str())+"' -- possibly loaded mismatched modules");
							return false;
						break;
						case CMD_FAILURE:
							return true;
						break;
						default:
							/* CMD_SUCCESS and CMD_USER_DELETED fall through here */
						break;
					}
				}
				else
				{
					// its not a user. Its either a server, or somethings screwed up.
					if (Utils->IsServer(prefix))
						target = this->Instance->Config->ServerName;
					else
						return true;
				}
				return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);

			}
			return true;
		break;
	}
	return true;
}

std::string TreeSocket::GetName()
{
	std::string sourceserv = this->myhost;
	if (this->InboundServerName != "")
	{
		sourceserv = this->InboundServerName;
	}
	return sourceserv;
}

void TreeSocket::OnTimeout()
{
	if (this->LinkState == CONNECTING)
	{
		this->Instance->SNO->WriteToSnoMask('l',"CONNECT: Connection to \002"+myhost+"\002 timed out.");
		Link* MyLink = Utils->FindLink(myhost);
		if (MyLink)
			Utils->DoFailOver(MyLink);
	}
}

void TreeSocket::OnClose()
{
	// Connection closed.
	// If the connection is fully up (state CONNECTED)
	// then propogate a netsplit to all peers.
	std::string quitserver = this->myhost;
	if (this->InboundServerName != "")
	{
		quitserver = this->InboundServerName;
	}
	TreeServer* s = Utils->FindServer(quitserver);
	if (s)
	{
		Squit(s,"Remote host closed the connection");
	}

	if (quitserver != "")
		this->Instance->SNO->WriteToSnoMask('l',"Connection to '\2%s\2' failed.",quitserver.c_str());
}

int TreeSocket::OnIncomingConnection(int newsock, char* ip)
{
	/* To prevent anyone from attempting to flood opers/DDoS by connecting to the server port,
	 * or discovering if this port is the server port, we don't allow connections from any
	 * IPs for which we don't have a link block.
	 */
	bool found = false;

	found = (std::find(Utils->ValidIPs.begin(), Utils->ValidIPs.end(), ip) != Utils->ValidIPs.end());
	if (!found)
	{
		for (vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
			if (irc::sockets::MatchCIDR(ip, (*i).c_str()))
				found = true;

		if (!found)
		{
			this->Instance->SNO->WriteToSnoMask('l',"Server connection from %s denied (no link blocks with that IP address)", ip);
			close(newsock);
			return false;
		}
	}

	TreeSocket* s = new TreeSocket(this->Utils, this->Instance, newsock, ip, this->Hook);
	s = s; /* Whinge whinge whinge, thats all GCC ever does. */
	return true;
}