aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Region/ClientStack/Linden/UDP/LLUDPServer.cs
blob: f52401aca333d8387654f396506540d5386bfa5c (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
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
/*
 * Copyright (c) Contributors, http://opensimulator.org/
 * See CONTRIBUTORS.TXT for a full list of copyright holders.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the OpenSimulator Project nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Threading;
using log4net;
using NDesk.Options;
using Nini.Config;
using OpenMetaverse.Packets;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Framework.Monitoring;
using OpenSim.Region.Framework.Scenes;
using OpenMetaverse;

using TokenBucket = OpenSim.Region.ClientStack.LindenUDP.TokenBucket;

namespace OpenSim.Region.ClientStack.LindenUDP
{
    /// <summary>
    /// A shim around LLUDPServer that implements the IClientNetworkServer interface
    /// </summary>
    public sealed class LLUDPServerShim : IClientNetworkServer
    {
        LLUDPServer m_udpServer;

        public LLUDPServerShim()
        {
        }

        public void Initialise(IPAddress listenIP, ref uint port, int proxyPortOffsetParm, bool allow_alternate_port, IConfigSource configSource, AgentCircuitManager circuitManager)
        {
            m_udpServer = new LLUDPServer(listenIP, ref port, proxyPortOffsetParm, allow_alternate_port, configSource, circuitManager);
        }

        public void AddScene(IScene scene)
        {
            m_udpServer.AddScene(scene);

            StatsManager.RegisterStat(
                new Stat(
                    "ClientLogoutsDueToNoReceives",
                    "Number of times a client has been logged out because no packets were received before the timeout.",
                    "",
                    "",
                    "clientstack",
                    scene.Name,
                    StatType.Pull,
                    MeasuresOfInterest.None,
                    stat => stat.Value = m_udpServer.ClientLogoutsDueToNoReceives,
                    StatVerbosity.Debug));

            StatsManager.RegisterStat(
                new Stat(
                    "IncomingUDPReceivesCount",
                    "Number of UDP receives performed",
                    "",
                    "",
                    "clientstack",
                    scene.Name,
                    StatType.Pull,
                    MeasuresOfInterest.AverageChangeOverTime,
                    stat => stat.Value = m_udpServer.UdpReceives,
                    StatVerbosity.Debug));

            StatsManager.RegisterStat(
                new Stat(
                    "IncomingPacketsProcessedCount",
                    "Number of inbound LL protocol packets processed",
                    "",
                    "",
                    "clientstack",
                    scene.Name,
                    StatType.Pull,
                    MeasuresOfInterest.AverageChangeOverTime,
                    stat => stat.Value = m_udpServer.IncomingPacketsProcessed,
                    StatVerbosity.Debug));

            StatsManager.RegisterStat(
                new Stat(
                    "IncomingPacketsMalformedCount",
                    "Number of inbound UDP packets that could not be recognized as LL protocol packets.",
                    "",
                    "",
                    "clientstack",
                    scene.Name,
                    StatType.Pull,
                    MeasuresOfInterest.AverageChangeOverTime,
                    stat => stat.Value = m_udpServer.IncomingMalformedPacketCount,
                    StatVerbosity.Info));

            StatsManager.RegisterStat(
                new Stat(
                    "IncomingPacketsOrphanedCount",
                    "Number of inbound packets that were not initial connections packets and could not be associated with a viewer.",
                    "",
                    "",
                    "clientstack",
                    scene.Name,
                    StatType.Pull,
                    MeasuresOfInterest.AverageChangeOverTime,
                    stat => stat.Value = m_udpServer.IncomingOrphanedPacketCount,
                    StatVerbosity.Info));

            StatsManager.RegisterStat(
                new Stat(
                    "IncomingPacketsResentCount",
                    "Number of inbound packets that clients indicate are resends.",
                    "",
                    "",
                    "clientstack",
                    scene.Name,
                    StatType.Pull,
                    MeasuresOfInterest.AverageChangeOverTime,
                    stat => stat.Value = m_udpServer.IncomingPacketsResentCount,
                    StatVerbosity.Debug));

            StatsManager.RegisterStat(
                new Stat(
                    "OutgoingUDPSendsCount",
                    "Number of UDP sends performed",
                    "",
                    "",
                    "clientstack",
                    scene.Name,
                    StatType.Pull,
                    MeasuresOfInterest.AverageChangeOverTime,
                    stat => stat.Value = m_udpServer.UdpSends,
                    StatVerbosity.Debug));

            StatsManager.RegisterStat(
                new Stat(
                    "OutgoingPacketsResentCount",
                    "Number of packets resent because a client did not acknowledge receipt",
                    "",
                    "",
                    "clientstack",
                    scene.Name,
                    StatType.Pull,
                    MeasuresOfInterest.AverageChangeOverTime,
                    stat => stat.Value = m_udpServer.PacketsResentCount,
                    StatVerbosity.Debug));

            StatsManager.RegisterStat(
                new Stat(
                    "AverageUDPProcessTime",
                    "Average number of milliseconds taken to process each incoming UDP packet in a sample.",
                    "This is for initial receive processing which is separate from the later client LL packet processing stage.",
                    "ms",
                    "clientstack",
                    scene.Name,
                    StatType.Pull,
                    MeasuresOfInterest.None,
                    stat => stat.Value = m_udpServer.AverageReceiveTicksForLastSamplePeriod / TimeSpan.TicksPerMillisecond,
//                    stat => 
//                        stat.Value = Math.Round(m_udpServer.AverageReceiveTicksForLastSamplePeriod / TimeSpan.TicksPerMillisecond, 7),
                    StatVerbosity.Debug));
        }

        public bool HandlesRegion(Location x)
        {
            return m_udpServer.HandlesRegion(x);
        }

        public void Start()
        {
            m_udpServer.Start();
        }

        public void Stop()
        {
            m_udpServer.Stop();
        }
    }

    /// <summary>
    /// The LLUDP server for a region. This handles incoming and outgoing
    /// packets for all UDP connections to the region
    /// </summary>
    public class LLUDPServer : OpenSimUDPBase
    {
        private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        /// <summary>Maximum transmission unit, or UDP packet size, for the LLUDP protocol</summary>
        public const int MTU = 1400;

        /// <summary>Number of forced client logouts due to no receipt of packets before timeout.</summary>
        public int ClientLogoutsDueToNoReceives { get; private set; }

        /// <summary>
        /// Default packet debug level given to new clients
        /// </summary>
        public int DefaultClientPacketDebugLevel { get; set; }

        /// <summary>The measured resolution of Environment.TickCount</summary>
        public readonly float TickCountResolution;

        /// <summary>Number of prim updates to put on the queue each time the 
        /// OnQueueEmpty event is triggered for updates</summary>
        public readonly int PrimUpdatesPerCallback;

        /// <summary>Number of texture packets to put on the queue each time the
        /// OnQueueEmpty event is triggered for textures</summary>
        public readonly int TextureSendLimit;

        /// <summary>Handlers for incoming packets</summary>
        //PacketEventDictionary packetEvents = new PacketEventDictionary();
        /// <summary>Incoming packets that are awaiting handling</summary>
        private OpenMetaverse.BlockingQueue<IncomingPacket> packetInbox = new OpenMetaverse.BlockingQueue<IncomingPacket>();

        /// <summary></summary>
        //private UDPClientCollection m_clients = new UDPClientCollection();
        /// <summary>Bandwidth throttle for this UDP server</summary>
        protected TokenBucket m_throttle;
        
        /// <summary>Bandwidth throttle rates for this UDP server</summary>
        public ThrottleRates ThrottleRates { get; private set; }
        
        /// <summary>Manages authentication for agent circuits</summary>
        private AgentCircuitManager m_circuitManager;

        /// <summary>Reference to the scene this UDP server is attached to</summary>
        protected Scene m_scene;

        /// <summary>The X/Y coordinates of the scene this UDP server is attached to</summary>
        private Location m_location;

        /// <summary>The size of the receive buffer for the UDP socket. This value
        /// is passed up to the operating system and used in the system networking
        /// stack. Use zero to leave this value as the default</summary>
        private int m_recvBufferSize;

        /// <summary>Flag to process packets asynchronously or synchronously</summary>
        private bool m_asyncPacketHandling;

        /// <summary>Tracks whether or not a packet was sent each round so we know
        /// whether or not to sleep</summary>
        private bool m_packetSent;

        /// <summary>Environment.TickCount of the last time that packet stats were reported to the scene</summary>
        private int m_elapsedMSSinceLastStatReport = 0;

        /// <summary>Environment.TickCount of the last time the outgoing packet handler executed</summary>
        private int m_tickLastOutgoingPacketHandler;

        /// <summary>Keeps track of the number of elapsed milliseconds since the last time the outgoing packet handler looped</summary>
        private int m_elapsedMSOutgoingPacketHandler;

        /// <summary>Keeps track of the number of 100 millisecond periods elapsed in the outgoing packet handler executed</summary>
        private int m_elapsed100MSOutgoingPacketHandler;

        /// <summary>Keeps track of the number of 500 millisecond periods elapsed in the outgoing packet handler executed</summary>
        private int m_elapsed500MSOutgoingPacketHandler;

        /// <summary>Flag to signal when clients should check for resends</summary>
        protected bool m_resendUnacked;

        /// <summary>Flag to signal when clients should send ACKs</summary>
        protected bool m_sendAcks;

        /// <summary>Flag to signal when clients should send pings</summary>
        protected bool m_sendPing;

        /// <summary>
        /// Event used to signal when queued packets are available for sending.
        /// </summary>
        /// <remarks>
        /// This allows the outbound loop to only operate when there is data to send rather than continuously polling.
        /// Some data is sent immediately and not queued.  That data would not trigger this event.
        /// </remarks>
        private AutoResetEvent m_dataPresentEvent = new AutoResetEvent(false);

        private Pool<IncomingPacket> m_incomingPacketPool;

        /// <summary>
        /// Stat for number of packets in the main pool awaiting use.
        /// </summary>
        private Stat m_poolCountStat;

        /// <summary>
        /// Stat for number of packets in the inbound packet pool awaiting use.
        /// </summary>
        private Stat m_incomingPacketPoolStat;

        private int m_defaultRTO = 0;
        private int m_maxRTO = 0;
        private int m_ackTimeout = 0;
        private int m_pausedAckTimeout = 0;
        private bool m_disableFacelights = false;

        public Socket Server { get { return null; } }

        /// <summary>
        /// Record how many packets have been resent
        /// </summary>
        internal int PacketsResentCount { get; set; }

        /// <summary>
        /// Record how many packets have been sent
        /// </summary>
        internal int PacketsSentCount { get; set; }

        /// <summary>
        /// Record how many incoming packets are indicated as resends by clients.
        /// </summary>
        internal int IncomingPacketsResentCount { get; set; }

        /// <summary>
        /// Record how many inbound packets could not be recognized as LLUDP packets.
        /// </summary>
        public int IncomingMalformedPacketCount { get; private set; }

        /// <summary>
        /// Record how many inbound packets could not be associated with a simulator circuit.
        /// </summary>
        public int IncomingOrphanedPacketCount { get; private set; }

        /// <summary>
        /// Record current outgoing client for monitoring purposes.
        /// </summary>
        private IClientAPI m_currentOutgoingClient;

        /// <summary>
        /// Recording current incoming client for monitoring purposes.
        /// </summary>
        private IClientAPI m_currentIncomingClient;

        public LLUDPServer(
            IPAddress listenIP, ref uint port, int proxyPortOffsetParm, bool allow_alternate_port,
            IConfigSource configSource, AgentCircuitManager circuitManager)
            : base(listenIP, (int)port)
        {
            #region Environment.TickCount Measurement

            // Measure the resolution of Environment.TickCount
            TickCountResolution = 0f;
            for (int i = 0; i < 5; i++)
            {
                int start = Environment.TickCount;
                int now = start;
                while (now == start)
                    now = Environment.TickCount;
                TickCountResolution += (float)(now - start) * 0.2f;
            }
            m_log.Info("[LLUDPSERVER]: Average Environment.TickCount resolution: " + TickCountResolution + "ms");
            TickCountResolution = (float)Math.Ceiling(TickCountResolution);

            #endregion Environment.TickCount Measurement

            m_circuitManager = circuitManager;
            int sceneThrottleBps = 0;
            bool usePools = false;

            IConfig config = configSource.Configs["ClientStack.LindenUDP"];
            if (config != null)
            {
                m_asyncPacketHandling = config.GetBoolean("async_packet_handling", true);
                m_recvBufferSize = config.GetInt("client_socket_rcvbuf_size", 0);
                sceneThrottleBps = config.GetInt("scene_throttle_max_bps", 0);

                PrimUpdatesPerCallback = config.GetInt("PrimUpdatesPerCallback", 100);
                TextureSendLimit = config.GetInt("TextureSendLimit", 20);

                m_defaultRTO = config.GetInt("DefaultRTO", 0);
                m_maxRTO = config.GetInt("MaxRTO", 0);
                m_disableFacelights = config.GetBoolean("DisableFacelights", false);
                m_ackTimeout = 1000 * config.GetInt("AckTimeout", 60);
                m_pausedAckTimeout = 1000 * config.GetInt("PausedAckTimeout", 300);
            }
            else
            {
                PrimUpdatesPerCallback = 100;
                TextureSendLimit = 20;
                m_ackTimeout = 1000 * 60; // 1 minute
                m_pausedAckTimeout = 1000 * 300; // 5 minutes
            }

            // FIXME: This actually only needs to be done once since the PacketPool is shared across all servers.
            // However, there is no harm in temporarily doing it multiple times.
            IConfig packetConfig = configSource.Configs["PacketPool"];
            if (packetConfig != null)
            {
                PacketPool.Instance.RecyclePackets = packetConfig.GetBoolean("RecyclePackets", true);
                PacketPool.Instance.RecycleDataBlocks = packetConfig.GetBoolean("RecycleDataBlocks", true);
                usePools = packetConfig.GetBoolean("RecycleBaseUDPPackets", usePools);
            }

            #region BinaryStats
            config = configSource.Configs["Statistics.Binary"];
            m_shouldCollectStats = false;
            if (config != null)
            {
                m_shouldCollectStats = config.GetBoolean("Enabled", false);
                binStatsMaxFilesize = TimeSpan.FromSeconds(config.GetInt("packet_headers_period_seconds", 300));
                binStatsDir = config.GetString("stats_dir", ".");
                m_aggregatedBWStats = config.GetBoolean("aggregatedBWStats", false);
            }
            #endregion BinaryStats

            m_throttle = new TokenBucket(null, sceneThrottleBps);
            ThrottleRates = new ThrottleRates(configSource);

            if (usePools)
                EnablePools();
        }

        public void Start()
        {
            StartInbound();
            StartOutbound();

            m_elapsedMSSinceLastStatReport = Environment.TickCount;
        }

        private void StartInbound()
        {
            m_log.InfoFormat(
                "[LLUDPSERVER]: Starting inbound packet processing for the LLUDP server in {0} mode with UsePools = {1}",
                m_asyncPacketHandling ? "asynchronous" : "synchronous", UsePools);

            base.StartInbound(m_recvBufferSize, m_asyncPacketHandling);

            // This thread will process the packets received that are placed on the packetInbox
            Watchdog.StartThread(
                IncomingPacketHandler,
                string.Format("Incoming Packets ({0})", m_scene.RegionInfo.RegionName),
                ThreadPriority.Normal,
                false,
                true,
                GetWatchdogIncomingAlarmData,
                Watchdog.DEFAULT_WATCHDOG_TIMEOUT_MS);
        }

        private new void StartOutbound()
        {
            m_log.Info("[LLUDPSERVER]: Starting outbound packet processing for the LLUDP server");

            base.StartOutbound();

            Watchdog.StartThread(
                OutgoingPacketHandler,
                string.Format("Outgoing Packets ({0})", m_scene.RegionInfo.RegionName),
                ThreadPriority.Normal,
                false,
                true,
                GetWatchdogOutgoingAlarmData,
                Watchdog.DEFAULT_WATCHDOG_TIMEOUT_MS);
        }

        public void Stop()
        {
            m_log.Info("[LLUDPSERVER]: Shutting down the LLUDP server for " + m_scene.RegionInfo.RegionName);
            base.StopOutbound();
            base.StopInbound();
        }

        protected override bool EnablePools()
        {
            if (!UsePools)
            {
                base.EnablePools();

                m_incomingPacketPool = new Pool<IncomingPacket>(() => new IncomingPacket(), 500);

                return true;
            }

            return false;
        }

        protected override bool DisablePools()
        {
            if (UsePools)
            {
                base.DisablePools();

                StatsManager.DeregisterStat(m_incomingPacketPoolStat);

                // We won't null out the pool to avoid a race condition with code that may be in the middle of using it.

                return true;
            }

            return false;
        }

        /// <summary>
        /// This is a seperate method so that it can be called once we have an m_scene to distinguish different scene
        /// stats.
        /// </summary>
        private void EnablePoolStats()
        {
            m_poolCountStat
                = new Stat(
                    "UDPPacketBufferPoolCount",
                    "Objects within the UDPPacketBuffer pool",
                    "The number of objects currently stored within the UDPPacketBuffer pool",
                    "",
                    "clientstack",
                    m_scene.Name,
                    StatType.Pull,
                    stat => stat.Value = Pool.Count,
                    StatVerbosity.Debug);

            StatsManager.RegisterStat(m_poolCountStat);

            m_incomingPacketPoolStat
                = new Stat(
                    "IncomingPacketPoolCount",
                    "Objects within incoming packet pool",
                    "The number of objects currently stored within the incoming packet pool",
                    "",
                    "clientstack",
                    m_scene.Name,
                    StatType.Pull,
                    stat => stat.Value = m_incomingPacketPool.Count,
                    StatVerbosity.Debug);

            StatsManager.RegisterStat(m_incomingPacketPoolStat);
        }

        /// <summary>
        /// Disables pool stats.
        /// </summary>
        private void DisablePoolStats()
        {
            StatsManager.DeregisterStat(m_poolCountStat);
            m_poolCountStat = null;

            StatsManager.DeregisterStat(m_incomingPacketPoolStat);
            m_incomingPacketPoolStat = null;
        }

        /// <summary>
        /// If the outgoing UDP thread times out, then return client that was being processed to help with debugging.
        /// </summary>
        /// <returns></returns>
        private string GetWatchdogIncomingAlarmData()
        {
            return string.Format(
                "Client is {0}",
                m_currentIncomingClient != null ? m_currentIncomingClient.Name : "none");
        }

        /// <summary>
        /// If the outgoing UDP thread times out, then return client that was being processed to help with debugging.
        /// </summary>
        /// <returns></returns>
        private string GetWatchdogOutgoingAlarmData()
        {
            return string.Format(
                "Client is {0}",
                m_currentOutgoingClient != null ? m_currentOutgoingClient.Name : "none");
        }

        public void AddScene(IScene scene)
        {
            if (m_scene != null)
            {
                m_log.Error("[LLUDPSERVER]: AddScene() called on an LLUDPServer that already has a scene");
                return;
            }

            if (!(scene is Scene))
            {
                m_log.Error("[LLUDPSERVER]: AddScene() called with an unrecognized scene type " + scene.GetType());
                return;
            }

            m_scene = (Scene)scene;
            m_location = new Location(m_scene.RegionInfo.RegionHandle);

            StatsManager.RegisterStat(
                new Stat(
                    "InboxPacketsCount",
                    "Number of LL protocol packets waiting for the second stage of processing after initial receive.",
                    "Number of LL protocol packets waiting for the second stage of processing after initial receive.",
                    "",
                    "clientstack",
                    scene.Name,
                    StatType.Pull,
                    MeasuresOfInterest.AverageChangeOverTime,
                    stat => stat.Value = packetInbox.Count,
                    StatVerbosity.Debug));

            // XXX: These stats are also pool stats but we register them separately since they are currently not
            // turned on and off by EnablePools()/DisablePools()
            StatsManager.RegisterStat(
                new PercentageStat(
                    "PacketsReused",
                    "Packets reused",
                    "Number of packets reused out of all requests to the packet pool",
                    "clientstack",
                    m_scene.Name,
                    StatType.Pull,
                    stat => 
                        { PercentageStat pstat = (PercentageStat)stat; 
                          pstat.Consequent = PacketPool.Instance.PacketsRequested; 
                          pstat.Antecedent = PacketPool.Instance.PacketsReused; },
                    StatVerbosity.Debug));

            StatsManager.RegisterStat(
                new PercentageStat(
                    "PacketDataBlocksReused",
                    "Packet data blocks reused",
                    "Number of data blocks reused out of all requests to the packet pool",
                    "clientstack",
                    m_scene.Name,
                    StatType.Pull,
                    stat =>
                        { PercentageStat pstat = (PercentageStat)stat; 
                          pstat.Consequent = PacketPool.Instance.BlocksRequested; 
                          pstat.Antecedent = PacketPool.Instance.BlocksReused; },
                    StatVerbosity.Debug));

            StatsManager.RegisterStat(
                new Stat(
                    "PacketsPoolCount",
                    "Objects within the packet pool",
                    "The number of objects currently stored within the packet pool",
                    "",
                    "clientstack",
                    m_scene.Name,
                    StatType.Pull,
                    stat => stat.Value = PacketPool.Instance.PacketsPooled,
                    StatVerbosity.Debug));

            StatsManager.RegisterStat(
                new Stat(
                    "PacketDataBlocksPoolCount",
                    "Objects within the packet data block pool",
                    "The number of objects currently stored within the packet data block pool",
                    "",
                    "clientstack",
                    m_scene.Name,
                    StatType.Pull,
                    stat => stat.Value = PacketPool.Instance.BlocksPooled,
                    StatVerbosity.Debug));
        
            // We delay enabling pool stats to AddScene() instead of Initialize() so that we can distinguish pool stats by
            // scene name
            if (UsePools)
                EnablePoolStats();

            MainConsole.Instance.Commands.AddCommand(
                "Debug", false, "debug lludp packet",
                 "debug lludp packet [--default | --all] <level> [<avatar-first-name> <avatar-last-name>]",
                 "Turn on packet debugging",
                   "If level >  255 then all incoming and outgoing packets are logged.\n"
                 + "If level <= 255 then incoming AgentUpdate and outgoing SimStats and SimulatorViewerTimeMessage packets are not logged.\n"
                 + "If level <= 200 then incoming RequestImage and outgoing ImagePacket, ImageData, LayerData and CoarseLocationUpdate packets are not logged.\n"
                 + "If level <= 100 then incoming ViewerEffect and AgentAnimation and outgoing ViewerEffect and AvatarAnimation packets are not logged.\n"
                 + "If level <=  50 then outgoing ImprovedTerseObjectUpdate packets are not logged.\n"
                 + "If level <= 0 then no packets are logged.\n"
                 + "If --default is specified then the level becomes the default logging level for all subsequent agents.\n"
                 + "If --all is specified then the level becomes the default logging level for all current and subsequent agents.\n"
                 + "In these cases, you cannot also specify an avatar name.\n"
                 + "If an avatar name is given then only packets from that avatar are logged.",
                 HandlePacketCommand);

            MainConsole.Instance.Commands.AddCommand(
                "Debug",
                false,
                "debug lludp start",
                "debug lludp start <in|out|all>",
                "Control LLUDP packet processing.",
                "No effect if packet processing has already started.\n"
                    + "in  - start inbound processing.\n"
                    + "out - start outbound processing.\n"
                    + "all - start in and outbound processing.\n",
                HandleStartCommand);

            MainConsole.Instance.Commands.AddCommand(
                "Debug",
                false,
                "debug lludp stop",
                "debug lludp stop <in|out|all>",
                "Stop LLUDP packet processing.",
                "No effect if packet processing has already stopped.\n"
                    + "in  - stop inbound processing.\n"
                    + "out - stop outbound processing.\n"
                    + "all - stop in and outbound processing.\n",
                HandleStopCommand);

            MainConsole.Instance.Commands.AddCommand(
                "Debug",
                false,
                "debug lludp pool",
                "debug lludp pool <on|off>",
                "Turn object pooling within the lludp component on or off.",
                HandlePoolCommand);

            MainConsole.Instance.Commands.AddCommand(
                "Debug",
                false,
                "debug lludp status",
                "debug lludp status",
                "Return status of LLUDP packet processing.",
                HandleStatusCommand);

            MainConsole.Instance.Commands.AddCommand(
                "Debug",
                false,
                "debug lludp toggle agentupdate",
                "debug lludp toggle agentupdate",
                "Toggle whether agentupdate packets are processed or simply discarded.",
                HandleAgentUpdateCommand);
        }

        private void HandlePacketCommand(string module, string[] args)
        {
            if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_scene)
                return;

            bool setAsDefaultLevel = false;
            bool setAll = false;
            OptionSet optionSet = new OptionSet()
                .Add("default", o => setAsDefaultLevel = (o != null))
                .Add("all", o => setAll = (o != null));
            List<string> filteredArgs = optionSet.Parse(args);

            string name = null;

            if (filteredArgs.Count == 6)
            {
                if (!(setAsDefaultLevel || setAll))
                {
                    name = string.Format("{0} {1}", filteredArgs[4], filteredArgs[5]);
                }
                else
                {
                    MainConsole.Instance.OutputFormat("ERROR: Cannot specify a user name when setting default/all logging level");
                    return;
                }
            }

            if (filteredArgs.Count > 3)
            {
                int newDebug;
                if (int.TryParse(filteredArgs[3], out newDebug))
                {
                    if (setAsDefaultLevel || setAll)
                    {
                        DefaultClientPacketDebugLevel = newDebug;

                        MainConsole.Instance.OutputFormat(
                            "Packet debug for {0} clients set to {1} in {2}",
                            (setAll ? "all" : "future"), DefaultClientPacketDebugLevel, m_scene.Name);

                        if (setAll)
                        {
                            m_scene.ForEachScenePresence(sp =>
                            {
                                MainConsole.Instance.OutputFormat(
                                    "Packet debug for {0} ({1}) set to {2} in {3}",
                                    sp.Name, sp.IsChildAgent ? "child" : "root", newDebug, m_scene.Name);

                                sp.ControllingClient.DebugPacketLevel = newDebug;
                            });
                        }
                    }
                    else
                    {
                        m_scene.ForEachScenePresence(sp =>
                        {
                            if (name == null || sp.Name == name)
                            {
                                MainConsole.Instance.OutputFormat(
                                    "Packet debug for {0} ({1}) set to {2} in {3}",
                                    sp.Name, sp.IsChildAgent ? "child" : "root", newDebug, m_scene.Name);

                                sp.ControllingClient.DebugPacketLevel = newDebug;
                            }
                        });
                    }
                }
                else
                {
                    MainConsole.Instance.Output("Usage: debug lludp packet [--default | --all] 0..255 [<first-name> <last-name>]");
                }
            }
        }

        private void HandleStartCommand(string module, string[] args)
        {
            if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_scene)
                return;

            if (args.Length != 4)
            {
                MainConsole.Instance.Output("Usage: debug lludp start <in|out|all>");
                return;
            }

            string subCommand = args[3];

            if (subCommand == "in" || subCommand == "all")
                StartInbound();

            if (subCommand == "out" || subCommand == "all")
                StartOutbound();
        }

        private void HandleStopCommand(string module, string[] args)
        {
            if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_scene)
                return;

            if (args.Length != 4)
            {
                MainConsole.Instance.Output("Usage: debug lludp stop <in|out|all>");
                return;
            }

            string subCommand = args[3];

            if (subCommand == "in" || subCommand == "all")
                StopInbound();

            if (subCommand == "out" || subCommand == "all")
                StopOutbound();
        }

        private void HandlePoolCommand(string module, string[] args)
        {
            if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_scene)
                return;

            if (args.Length != 4)
            {
                MainConsole.Instance.Output("Usage: debug lludp pool <on|off>");
                return;
            }

            string enabled = args[3];

            if (enabled == "on")
            {
                if (EnablePools())
                {
                    EnablePoolStats();
                    MainConsole.Instance.OutputFormat("Packet pools enabled on {0}", m_scene.Name);
                }
            }
            else if (enabled == "off")
            {
                if (DisablePools())
                {
                    DisablePoolStats();
                    MainConsole.Instance.OutputFormat("Packet pools disabled on {0}", m_scene.Name);
                }
            }
            else
            {
                MainConsole.Instance.Output("Usage: debug lludp pool <on|off>");
            }
        }

        bool m_discardAgentUpdates;

        private void HandleAgentUpdateCommand(string module, string[] args)
        {
            if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_scene)
                return;

            m_discardAgentUpdates = !m_discardAgentUpdates;

            MainConsole.Instance.OutputFormat(
                "Discard AgentUpdates now {0} for {1}", m_discardAgentUpdates, m_scene.Name);
        }

        private void HandleStatusCommand(string module, string[] args)
        {
            if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_scene)
                return;

            MainConsole.Instance.OutputFormat(
                "IN  LLUDP packet processing for {0} is {1}", m_scene.Name, IsRunningInbound ? "enabled" : "disabled");

            MainConsole.Instance.OutputFormat(
                "OUT LLUDP packet processing for {0} is {1}", m_scene.Name, IsRunningOutbound ? "enabled" : "disabled");

            MainConsole.Instance.OutputFormat("LLUDP pools in {0} are {1}", m_scene.Name, UsePools ? "on" : "off");

            MainConsole.Instance.OutputFormat(
                "Packet debug level for new clients is {0}", DefaultClientPacketDebugLevel);
        }

        public bool HandlesRegion(Location x)
        {
            return x == m_location;
        }

//        public void BroadcastPacket(Packet packet, ThrottleOutPacketType category, bool sendToPausedAgents, bool allowSplitting)
//        {
//            // CoarseLocationUpdate and AvatarGroupsReply packets cannot be split in an automated way
//            if ((packet.Type == PacketType.CoarseLocationUpdate || packet.Type == PacketType.AvatarGroupsReply) && allowSplitting)
//                allowSplitting = false;
//
//            if (allowSplitting && packet.HasVariableBlocks)
//            {
//                byte[][] datas = packet.ToBytesMultiple();
//                int packetCount = datas.Length;
//
//                if (packetCount < 1)
//                    m_log.Error("[LLUDPSERVER]: Failed to split " + packet.Type + " with estimated length " + packet.Length);
//
//                for (int i = 0; i < packetCount; i++)
//                {
//                    byte[] data = datas[i];
//                    m_scene.ForEachClient(
//                        delegate(IClientAPI client)
//                        {
//                            if (client is LLClientView)
//                                SendPacketData(((LLClientView)client).UDPClient, data, packet.Type, category, null);
//                        }
//                    );
//                }
//            }
//            else
//            {
//                byte[] data = packet.ToBytes();
//                m_scene.ForEachClient(
//                    delegate(IClientAPI client)
//                    {
//                        if (client is LLClientView)
//                            SendPacketData(((LLClientView)client).UDPClient, data, packet.Type, category, null);
//                    }
//                );
//            }
//        }

        /// <summary>
        /// Start the process of sending a packet to the client.
        /// </summary>
        /// <param name="udpClient"></param>
        /// <param name="packet"></param>
        /// <param name="category"></param>
        /// <param name="allowSplitting"></param>
        /// <param name="method">
        /// The method to call if the packet is not acked by the client.  If null, then a standard
        /// resend of the packet is done.
        /// </param>
        public virtual void SendPacket(
            LLUDPClient udpClient, Packet packet, ThrottleOutPacketType category, bool allowSplitting, UnackedPacketMethod method)
        {
            // CoarseLocationUpdate packets cannot be split in an automated way
            if (packet.Type == PacketType.CoarseLocationUpdate && allowSplitting)
                allowSplitting = false;

            bool packetQueued = false;

            if (allowSplitting && packet.HasVariableBlocks)
            {
                byte[][] datas = packet.ToBytesMultiple();
                int packetCount = datas.Length;

                if (packetCount < 1)
                    m_log.Error("[LLUDPSERVER]: Failed to split " + packet.Type + " with estimated length " + packet.Length);

                for (int i = 0; i < packetCount; i++)
                {
                    byte[] data = datas[i];
                    if (!SendPacketData(udpClient, data, packet.Type, category, method))
                        packetQueued = true;
                }
            }
            else
            {
                byte[] data = packet.ToBytes();
                if (!SendPacketData(udpClient, data, packet.Type, category, method))
                    packetQueued = true;
            }

            PacketPool.Instance.ReturnPacket(packet);

            if (packetQueued)
                m_dataPresentEvent.Set();
        }

        /// <summary>
        /// Start the process of sending a packet to the client.
        /// </summary>
        /// <param name="udpClient"></param>
        /// <param name="data"></param>
        /// <param name="type"></param>
        /// <param name="category"></param>
        /// <param name="method">
        /// The method to call if the packet is not acked by the client.  If null, then a standard
        /// resend of the packet is done.
        /// </param>
        /// <returns>true if the data was sent immediately, false if it was queued for sending</returns>
        public bool SendPacketData(
            LLUDPClient udpClient, byte[] data, PacketType type, ThrottleOutPacketType category, UnackedPacketMethod method)
        {
            int dataLength = data.Length;
            bool doZerocode = (data[0] & Helpers.MSG_ZEROCODED) != 0;
            bool doCopy = true;

            // Frequency analysis of outgoing packet sizes shows a large clump of packets at each end of the spectrum.
            // The vast majority of packets are less than 200 bytes, although due to asset transfers and packet splitting
            // there are a decent number of packets in the 1000-1140 byte range. We allocate one of two sizes of data here
            // to accomodate for both common scenarios and provide ample room for ACK appending in both
            int bufferSize = (dataLength > 180) ? LLUDPServer.MTU : 200;

            UDPPacketBuffer buffer = new UDPPacketBuffer(udpClient.RemoteEndPoint, bufferSize);

            // Zerocode if needed
            if (doZerocode)
            {
                try
                {
                    dataLength = Helpers.ZeroEncode(data, dataLength, buffer.Data);
                    doCopy = false;
                }
                catch (IndexOutOfRangeException)
                {
                    // The packet grew larger than the bufferSize while zerocoding.
                    // Remove the MSG_ZEROCODED flag and send the unencoded data
                    // instead
                    m_log.Debug("[LLUDPSERVER]: Packet exceeded buffer size during zerocoding for " + type + ". DataLength=" + dataLength +
                        " and BufferLength=" + buffer.Data.Length + ". Removing MSG_ZEROCODED flag");
                    data[0] = (byte)(data[0] & ~Helpers.MSG_ZEROCODED);
                }
            }

            // If the packet data wasn't already copied during zerocoding, copy it now
            if (doCopy)
            {
                if (dataLength <= buffer.Data.Length)
                {
                    Buffer.BlockCopy(data, 0, buffer.Data, 0, dataLength);
                }
                else
                {
                    bufferSize = dataLength;
                    buffer = new UDPPacketBuffer(udpClient.RemoteEndPoint, bufferSize);

                    // m_log.Error("[LLUDPSERVER]: Packet exceeded buffer size! This could be an indication of packet assembly not obeying the MTU. Type=" +
                    //     type + ", DataLength=" + dataLength + ", BufferLength=" + buffer.Data.Length + ". Dropping packet");
                    Buffer.BlockCopy(data, 0, buffer.Data, 0, dataLength);
                }
            }

            buffer.DataLength = dataLength;

            #region Queue or Send

            OutgoingPacket outgoingPacket = new OutgoingPacket(udpClient, buffer, category, null);
            // If we were not provided a method for handling unacked, use the UDPServer default method
            outgoingPacket.UnackedMethod = ((method == null) ? delegate(OutgoingPacket oPacket) { ResendUnacked(oPacket); } : method);

            // If a Linden Lab 1.23.5 client receives an update packet after a kill packet for an object, it will 
            // continue to display the deleted object until relog.  Therefore, we need to always queue a kill object
            // packet so that it isn't sent before a queued update packet.
            bool forceQueue = (type == PacketType.KillObject);

            if (!outgoingPacket.Client.EnqueueOutgoing(outgoingPacket, forceQueue))
            {
                SendPacketFinal(outgoingPacket);
                return true;
            }
            else
            {
                return false;
            }

            #endregion Queue or Send
        }

        public void SendAcks(LLUDPClient udpClient)
        {
            uint ack;

            if (udpClient.PendingAcks.Dequeue(out ack))
            {
                List<PacketAckPacket.PacketsBlock> blocks = new List<PacketAckPacket.PacketsBlock>();
                PacketAckPacket.PacketsBlock block = new PacketAckPacket.PacketsBlock();
                block.ID = ack;
                blocks.Add(block);

                while (udpClient.PendingAcks.Dequeue(out ack))
                {
                    block = new PacketAckPacket.PacketsBlock();
                    block.ID = ack;
                    blocks.Add(block);
                }

                PacketAckPacket packet = new PacketAckPacket();
                packet.Header.Reliable = false;
                packet.Packets = blocks.ToArray();

                SendPacket(udpClient, packet, ThrottleOutPacketType.Unknown, true, null);
            }
        }

        public void SendPing(LLUDPClient udpClient)
        {
            StartPingCheckPacket pc = (StartPingCheckPacket)PacketPool.Instance.GetPacket(PacketType.StartPingCheck);
            pc.Header.Reliable = false;

            pc.PingID.PingID = (byte)udpClient.CurrentPingSequence++;
            // We *could* get OldestUnacked, but it would hurt performance and not provide any benefit
            pc.PingID.OldestUnacked = 0;

            SendPacket(udpClient, pc, ThrottleOutPacketType.Unknown, false, null);
        }

        public void CompletePing(LLUDPClient udpClient, byte pingID)
        {
            CompletePingCheckPacket completePing = new CompletePingCheckPacket();
            completePing.PingID.PingID = pingID;
            SendPacket(udpClient, completePing, ThrottleOutPacketType.Unknown, false, null);
        }

        public void HandleUnacked(LLClientView client)
        {
            LLUDPClient udpClient = client.UDPClient;

            if (!udpClient.IsConnected)
                return;

            // Disconnect an agent if no packets are received for some time
            int timeoutTicks = m_ackTimeout;

            // Allow more slack if the client is "paused" eg file upload dialogue is open
            // Some sort of limit is needed in case the client crashes, loses its network connection
            // or some other disaster prevents it from sendung the AgentResume
            if (udpClient.IsPaused)
                timeoutTicks = m_pausedAckTimeout;

            if (client.IsActive &&
                (Environment.TickCount & Int32.MaxValue) - udpClient.TickLastPacketReceived > timeoutTicks)
            {
                // We must set IsActive synchronously so that we can stop the packet loop reinvoking this method, even
                // though it's set later on by LLClientView.Close()
                client.IsActive = false;

                // Fire this out on a different thread so that we don't hold up outgoing packet processing for
                // everybody else if this is being called due to an ack timeout.
                // This is the same as processing as the async process of a logout request.
                Util.FireAndForget(o => DeactivateClientDueToTimeout(client, timeoutTicks));

                return;
            }

            // Get a list of all of the packets that have been sitting unacked longer than udpClient.RTO
            List<OutgoingPacket> expiredPackets = udpClient.NeedAcks.GetExpiredPackets(udpClient.RTO);

            if (expiredPackets != null)
            {
                //m_log.Debug("[LLUDPSERVER]: Handling " + expiredPackets.Count + " packets to " + udpClient.AgentID + ", RTO=" + udpClient.RTO);
                // Exponential backoff of the retransmission timeout
                udpClient.BackoffRTO();
                for (int i = 0; i < expiredPackets.Count; ++i)
                    expiredPackets[i].UnackedMethod(expiredPackets[i]);
            }
        }

        public void ResendUnacked(OutgoingPacket outgoingPacket)
        {
            //m_log.DebugFormat("[LLUDPSERVER]: Resending packet #{0} (attempt {1}), {2}ms have passed",
            //    outgoingPacket.SequenceNumber, outgoingPacket.ResendCount, Environment.TickCount - outgoingPacket.TickCount);

            // Set the resent flag
            outgoingPacket.Buffer.Data[0] = (byte)(outgoingPacket.Buffer.Data[0] | Helpers.MSG_RESENT);
            outgoingPacket.Category = ThrottleOutPacketType.Resend;

            // Bump up the resend count on this packet
            Interlocked.Increment(ref outgoingPacket.ResendCount);

            // Requeue or resend the packet
            if (!outgoingPacket.Client.EnqueueOutgoing(outgoingPacket, false))
                SendPacketFinal(outgoingPacket);
        }

        public void Flush(LLUDPClient udpClient)
        {
            // FIXME: Implement?
        }

        /// <summary>
        /// Actually send a packet to a client.
        /// </summary>
        /// <param name="outgoingPacket"></param>
        internal void SendPacketFinal(OutgoingPacket outgoingPacket)
        {
            UDPPacketBuffer buffer = outgoingPacket.Buffer;
            byte flags = buffer.Data[0];
            bool isResend = (flags & Helpers.MSG_RESENT) != 0;
            bool isReliable = (flags & Helpers.MSG_RELIABLE) != 0;
            bool isZerocoded = (flags & Helpers.MSG_ZEROCODED) != 0;
            LLUDPClient udpClient = outgoingPacket.Client;

            if (!udpClient.IsConnected)
                return;

            #region ACK Appending

            int dataLength = buffer.DataLength;

            // NOTE: I'm seeing problems with some viewers when ACKs are appended to zerocoded packets so I've disabled that here
            if (!isZerocoded)
            {
                // Keep appending ACKs until there is no room left in the buffer or there are
                // no more ACKs to append
                uint ackCount = 0;
                uint ack;
                while (dataLength + 5 < buffer.Data.Length && udpClient.PendingAcks.Dequeue(out ack))
                {
                    Utils.UIntToBytesBig(ack, buffer.Data, dataLength);
                    dataLength += 4;
                    ++ackCount;
                }

                if (ackCount > 0)
                {
                    // Set the last byte of the packet equal to the number of appended ACKs
                    buffer.Data[dataLength++] = (byte)ackCount;
                    // Set the appended ACKs flag on this packet
                    buffer.Data[0] = (byte)(buffer.Data[0] | Helpers.MSG_APPENDED_ACKS);
                }
            }

            buffer.DataLength = dataLength;

            #endregion ACK Appending

            #region Sequence Number Assignment

            if (!isResend)
            {
                // Not a resend, assign a new sequence number
                uint sequenceNumber = (uint)Interlocked.Increment(ref udpClient.CurrentSequence);
                Utils.UIntToBytesBig(sequenceNumber, buffer.Data, 1);
                outgoingPacket.SequenceNumber = sequenceNumber;

                if (isReliable)
                {
                    // Add this packet to the list of ACK responses we are waiting on from the server
                    udpClient.NeedAcks.Add(outgoingPacket);
                }
            }
            else
            {
                Interlocked.Increment(ref udpClient.PacketsResent);

                // We're not going to worry about interlock yet since its not currently critical that this total count
                // is 100% correct
                PacketsResentCount++;
            }

            #endregion Sequence Number Assignment

            // Stats tracking
            Interlocked.Increment(ref udpClient.PacketsSent);

            // We're not going to worry about interlock yet since its not currently critical that this total count
            // is 100% correct
            PacketsSentCount++;

            // Put the UDP payload on the wire
            AsyncBeginSend(buffer);

            // Keep track of when this packet was sent out (right now)
            outgoingPacket.TickCount = Environment.TickCount & Int32.MaxValue;
        }

        private void RecordMalformedInboundPacket(IPEndPoint endPoint)
        {
//                if (m_malformedCount < 100)
//                    m_log.DebugFormat("[LLUDPSERVER]: Dropped malformed packet: " + e.ToString());

            IncomingMalformedPacketCount++;

            if ((IncomingMalformedPacketCount % 10000) == 0)
                m_log.WarnFormat(
                    "[LLUDPSERVER]: Received {0} malformed packets so far, probable network attack.  Last was from {1}", 
                    IncomingMalformedPacketCount, endPoint);
        }

        public override void PacketReceived(UDPPacketBuffer buffer)
        {
            // Debugging/Profiling
            //try { Thread.CurrentThread.Name = "PacketReceived (" + m_scene.RegionInfo.RegionName + ")"; }
            //catch (Exception) { }
//            m_log.DebugFormat(
//                "[LLUDPSERVER]: Packet received from {0} in {1}", buffer.RemoteEndPoint, m_scene.RegionInfo.RegionName);

            LLUDPClient udpClient = null;
            Packet packet = null;
            int packetEnd = buffer.DataLength - 1;
            IPEndPoint endPoint = (IPEndPoint)buffer.RemoteEndPoint;

            #region Decoding

            if (buffer.DataLength < 7)
            {
//                m_log.WarnFormat(
//                    "[LLUDPSERVER]: Dropping undersized packet with {0} bytes received from {1} in {2}",
//                    buffer.DataLength, buffer.RemoteEndPoint, m_scene.RegionInfo.RegionName);

                RecordMalformedInboundPacket(endPoint);

                return; // Drop undersized packet
            }

            int headerLen = 7;
            if (buffer.Data[6] == 0xFF)
            {
                if (buffer.Data[7] == 0xFF)
                    headerLen = 10;
                else
                    headerLen = 8;
            }

            if (buffer.DataLength < headerLen)
            {
//                m_log.WarnFormat(
//                    "[LLUDPSERVER]: Dropping packet with malformed header received from {0} in {1}",
//                    buffer.RemoteEndPoint, m_scene.RegionInfo.RegionName);

                RecordMalformedInboundPacket(endPoint);

                return; // Malformed header
            }

            try
            {
//                packet = Packet.BuildPacket(buffer.Data, ref packetEnd,
//                    // Only allocate a buffer for zerodecoding if the packet is zerocoded
//                    ((buffer.Data[0] & Helpers.MSG_ZEROCODED) != 0) ? new byte[4096] : null);
                // If OpenSimUDPBase.UsePool == true (which is currently separate from the PacketPool) then we
                // assume that packet construction does not retain a reference to byte[] buffer.Data (instead, all
                // bytes are copied out).
                packet = PacketPool.Instance.GetPacket(buffer.Data, ref packetEnd,
                    // Only allocate a buffer for zerodecoding if the packet is zerocoded
                    ((buffer.Data[0] & Helpers.MSG_ZEROCODED) != 0) ? new byte[4096] : null);
            }
            catch (Exception e)
            {
                if (IncomingMalformedPacketCount < 100)
                    m_log.DebugFormat("[LLUDPSERVER]: Dropped malformed packet: " + e.ToString());
            }

            // Fail-safe check
            if (packet == null)
            {
                if (IncomingMalformedPacketCount < 100)
                {
                    m_log.WarnFormat("[LLUDPSERVER]: Malformed data, cannot parse {0} byte packet from {1}, data {2}:",
                        buffer.DataLength, buffer.RemoteEndPoint, Utils.BytesToHexString(buffer.Data, buffer.DataLength, null));
                }

                RecordMalformedInboundPacket(endPoint);

                return;
            }

            #endregion Decoding

            #region Packet to Client Mapping

            // UseCircuitCode handling
            if (packet.Type == PacketType.UseCircuitCode)
            {
                // We need to copy the endpoint so that it doesn't get changed when another thread reuses the
                // buffer.
                object[] array = new object[] { new IPEndPoint(endPoint.Address, endPoint.Port), packet };

                Util.FireAndForget(HandleUseCircuitCode, array);

                return;
            }
            else if (packet.Type == PacketType.CompleteAgentMovement)
            {
                // Send ack straight away to let the viewer know that we got it.
                SendAckImmediate(endPoint, packet.Header.Sequence);

                // We need to copy the endpoint so that it doesn't get changed when another thread reuses the
                // buffer.
                object[] array = new object[] { new IPEndPoint(endPoint.Address, endPoint.Port), packet };

                Util.FireAndForget(HandleCompleteMovementIntoRegion, array);

                return;
            }

            // Determine which agent this packet came from
            IClientAPI client;
            if (!m_scene.TryGetClient(endPoint, out client) || !(client is LLClientView))
            {
                //m_log.Debug("[LLUDPSERVER]: Received a " + packet.Type + " packet from an unrecognized source: " + address + " in " + m_scene.RegionInfo.RegionName);

                IncomingOrphanedPacketCount++;

                if ((IncomingOrphanedPacketCount % 10000) == 0)
                    m_log.WarnFormat(
                        "[LLUDPSERVER]: Received {0} orphaned packets so far.  Last was from {1}", 
                        IncomingOrphanedPacketCount, endPoint);

                return;
            }

            udpClient = ((LLClientView)client).UDPClient;

            if (!udpClient.IsConnected)
                return;

            #endregion Packet to Client Mapping

            // Stats tracking
            Interlocked.Increment(ref udpClient.PacketsReceived);

            int now = Environment.TickCount & Int32.MaxValue;
            udpClient.TickLastPacketReceived = now;

            #region ACK Receiving

            // Handle appended ACKs
            if (packet.Header.AppendedAcks && packet.Header.AckList != null)
            {
//                m_log.DebugFormat(
//                    "[LLUDPSERVER]: Handling {0} appended acks from {1} in {2}",
//                    packet.Header.AckList.Length, client.Name, m_scene.Name);

                for (int i = 0; i < packet.Header.AckList.Length; i++)
                    udpClient.NeedAcks.Acknowledge(packet.Header.AckList[i], now, packet.Header.Resent);
            }

            // Handle PacketAck packets
            if (packet.Type == PacketType.PacketAck)
            {
                PacketAckPacket ackPacket = (PacketAckPacket)packet;

//                m_log.DebugFormat(
//                    "[LLUDPSERVER]: Handling {0} packet acks for {1} in {2}",
//                    ackPacket.Packets.Length, client.Name, m_scene.Name);

                for (int i = 0; i < ackPacket.Packets.Length; i++)
                    udpClient.NeedAcks.Acknowledge(ackPacket.Packets[i].ID, now, packet.Header.Resent);

                // We don't need to do anything else with PacketAck packets
                return;
            }

            #endregion ACK Receiving

            #region ACK Sending

            if (packet.Header.Reliable)
            {
//                m_log.DebugFormat(
//                    "[LLUDPSERVER]: Adding ack request for {0} {1} from {2} in {3}",
//                    packet.Type, packet.Header.Sequence, client.Name, m_scene.Name);

                udpClient.PendingAcks.Enqueue(packet.Header.Sequence);

                // This is a somewhat odd sequence of steps to pull the client.BytesSinceLastACK value out,
                // add the current received bytes to it, test if 2*MTU bytes have been sent, if so remove
                // 2*MTU bytes from the value and send ACKs, and finally add the local value back to
                // client.BytesSinceLastACK. Lockless thread safety
                int bytesSinceLastACK = Interlocked.Exchange(ref udpClient.BytesSinceLastACK, 0);
                bytesSinceLastACK += buffer.DataLength;
                if (bytesSinceLastACK > LLUDPServer.MTU * 2)
                {
                    bytesSinceLastACK -= LLUDPServer.MTU * 2;
                    SendAcks(udpClient);
                }
                Interlocked.Add(ref udpClient.BytesSinceLastACK, bytesSinceLastACK);
            }

            #endregion ACK Sending

            #region Incoming Packet Accounting

            // We're not going to worry about interlock yet since its not currently critical that this total count
            // is 100% correct
            if (packet.Header.Resent)
                IncomingPacketsResentCount++;

            // Check the archive of received reliable packet IDs to see whether we already received this packet
            if (packet.Header.Reliable && !udpClient.PacketArchive.TryEnqueue(packet.Header.Sequence))
            {
                if (packet.Header.Resent)
                    m_log.DebugFormat(
                        "[LLUDPSERVER]: Received a resend of already processed packet #{0}, type {1} from {2}", 
                        packet.Header.Sequence, packet.Type, client.Name);
                 else
                    m_log.WarnFormat(
                        "[LLUDPSERVER]: Received a duplicate (not marked as resend) of packet #{0}, type {1} from {2}",
                        packet.Header.Sequence, packet.Type, client.Name);

                // Avoid firing a callback twice for the same packet
                return;
            }

            #endregion Incoming Packet Accounting

            #region BinaryStats
            LogPacketHeader(true, udpClient.CircuitCode, 0, packet.Type, (ushort)packet.Length);
            #endregion BinaryStats

            if (packet.Type == PacketType.AgentUpdate)
            {
                if (m_discardAgentUpdates)
                    return;

                ((LLClientView)client).TotalAgentUpdates++;

                AgentUpdatePacket agentUpdate = (AgentUpdatePacket)packet;

                LLClientView llClient = client as LLClientView;
                if (agentUpdate.AgentData.SessionID != client.SessionId 
                    || agentUpdate.AgentData.AgentID != client.AgentId
                    || !(llClient == null || llClient.CheckAgentUpdateSignificance(agentUpdate.AgentData)) )
                {
                    PacketPool.Instance.ReturnPacket(packet);
                    return;
                }
            }

            #region Ping Check Handling

            if (packet.Type == PacketType.StartPingCheck)
            {
//                m_log.DebugFormat("[LLUDPSERVER]: Handling ping from {0} in {1}", client.Name, m_scene.Name);

                // We don't need to do anything else with ping checks
                StartPingCheckPacket startPing = (StartPingCheckPacket)packet;
                CompletePing(udpClient, startPing.PingID.PingID);

                if ((Environment.TickCount - m_elapsedMSSinceLastStatReport) >= 3000)
                {
                    udpClient.SendPacketStats();
                    m_elapsedMSSinceLastStatReport = Environment.TickCount;
                }
                return;
            }
            else if (packet.Type == PacketType.CompletePingCheck)
            {
                // We don't currently track client ping times
                return;
            }

            #endregion Ping Check Handling

            IncomingPacket incomingPacket;

            // Inbox insertion
            if (UsePools)
            {
                incomingPacket = m_incomingPacketPool.GetObject();
                incomingPacket.Client = (LLClientView)client;
                incomingPacket.Packet = packet;
            }
            else
            {
                incomingPacket = new IncomingPacket((LLClientView)client, packet);
            }

            packetInbox.Enqueue(incomingPacket);
        }

        #region BinaryStats

        public class PacketLogger
        {
            public DateTime StartTime;
            public string Path = null;
            public System.IO.BinaryWriter Log = null;
        }

        public static PacketLogger PacketLog;

        protected static bool m_shouldCollectStats = false;
        // Number of seconds to log for
        static TimeSpan binStatsMaxFilesize = TimeSpan.FromSeconds(300);
        static object binStatsLogLock = new object();
        static string binStatsDir = "";

        //for Aggregated In/Out BW logging
        static bool m_aggregatedBWStats = false;
        static long m_aggregatedBytesIn = 0;
        static long m_aggregatedByestOut = 0;
        static object aggBWStatsLock = new object();

        public static long AggregatedLLUDPBytesIn
        {
            get { return m_aggregatedBytesIn; }
        }
        public static long AggregatedLLUDPBytesOut
        {
            get {return m_aggregatedByestOut;}
        }

        public static void LogPacketHeader(bool incoming, uint circuit, byte flags, PacketType packetType, ushort size)
        {
            if (m_aggregatedBWStats)
            {
                lock (aggBWStatsLock)
                {
                    if (incoming)
                        m_aggregatedBytesIn += size;
                    else
                        m_aggregatedByestOut += size;
                }
            }

            if (!m_shouldCollectStats) return;

            // Binary logging format is TTTTTTTTCCCCFPPPSS, T=Time, C=Circuit, F=Flags, P=PacketType, S=size

            // Put the incoming bit into the least significant bit of the flags byte
            if (incoming)
                flags |= 0x01;
            else
                flags &= 0xFE;

            // Put the flags byte into the most significant bits of the type integer
            uint type = (uint)packetType;
            type |= (uint)flags << 24;

            // m_log.Debug("1 LogPacketHeader(): Outside lock");
            lock (binStatsLogLock)
            {
                DateTime now = DateTime.Now;

                // m_log.Debug("2 LogPacketHeader(): Inside lock. now is " + now.Ticks);
                try
                {
                    if (PacketLog == null || (now > PacketLog.StartTime + binStatsMaxFilesize))
                    {
                        if (PacketLog != null && PacketLog.Log != null)
                        {
                            PacketLog.Log.Close();
                        }

                        // First log file or time has expired, start writing to a new log file
                        PacketLog = new PacketLogger();
                        PacketLog.StartTime = now;
                        PacketLog.Path = (binStatsDir.Length > 0 ? binStatsDir + System.IO.Path.DirectorySeparatorChar.ToString() : "")
                                + String.Format("packets-{0}.log", now.ToString("yyyyMMddHHmmss"));
                        PacketLog.Log = new BinaryWriter(File.Open(PacketLog.Path, FileMode.Append, FileAccess.Write));
                    }

                    // Serialize the data
                    byte[] output = new byte[18];
                    Buffer.BlockCopy(BitConverter.GetBytes(now.Ticks), 0, output, 0, 8);
                    Buffer.BlockCopy(BitConverter.GetBytes(circuit), 0, output, 8, 4);
                    Buffer.BlockCopy(BitConverter.GetBytes(type), 0, output, 12, 4);
                    Buffer.BlockCopy(BitConverter.GetBytes(size), 0, output, 16, 2);

                    // Write the serialized data to disk
                    if (PacketLog != null && PacketLog.Log != null)
                        PacketLog.Log.Write(output);
                }
                catch (Exception ex)
                {
                    m_log.Error("Packet statistics gathering failed: " + ex.Message, ex);
                    if (PacketLog.Log != null)
                    {
                        PacketLog.Log.Close();
                    }
                    PacketLog = null;
                }
            }
        }

        #endregion BinaryStats

        private void HandleUseCircuitCode(object o)
        {
            IPEndPoint endPoint = null;
            IClientAPI client = null;

            try
            {
    //            DateTime startTime = DateTime.Now;
                object[] array = (object[])o;
                endPoint = (IPEndPoint)array[0];
                UseCircuitCodePacket uccp = (UseCircuitCodePacket)array[1];

                m_log.DebugFormat(
                    "[LLUDPSERVER]: Handling UseCircuitCode request for circuit {0} to {1} from IP {2}",
                    uccp.CircuitCode.Code, m_scene.RegionInfo.RegionName, endPoint);
    
                AuthenticateResponse sessionInfo;
                if (IsClientAuthorized(uccp, out sessionInfo))
                {
                    // Begin the process of adding the client to the simulator
                    client
                        = AddClient(
                            uccp.CircuitCode.Code,
                            uccp.CircuitCode.ID,
                            uccp.CircuitCode.SessionID,
                            endPoint,
                            sessionInfo);
            
                    // Send ack straight away to let the viewer know that the connection is active.
                    // The client will be null if it already exists (e.g. if on a region crossing the client sends a use
                    // circuit code to the existing child agent.  This is not particularly obvious.
                    SendAckImmediate(endPoint, uccp.Header.Sequence);
            
                    // We only want to send initial data to new clients, not ones which are being converted from child to root.
                    if (client != null)
                    {
                        AgentCircuitData aCircuit = m_scene.AuthenticateHandler.GetAgentCircuitData(uccp.CircuitCode.Code);
                        bool tp = (aCircuit.teleportFlags > 0);
                        // Let's delay this for TP agents, otherwise the viewer doesn't know where to get resources from
                        if (!tp)
                            client.SceneAgent.SendInitialDataToMe();
                    }
                }
                else
                {
                    // Don't create clients for unauthorized requesters.
                    m_log.WarnFormat(
                        "[LLUDPSERVER]: Ignoring connection request for {0} to {1} with unknown circuit code {2} from IP {3}",
                        uccp.CircuitCode.ID, m_scene.RegionInfo.RegionName, uccp.CircuitCode.Code, endPoint);
                }
    
                //            m_log.DebugFormat(
    //                "[LLUDPSERVER]: Handling UseCircuitCode request from {0} took {1}ms", 
    //                buffer.RemoteEndPoint, (DateTime.Now - startTime).Milliseconds);

            }
            catch (Exception e)
            {
                m_log.ErrorFormat(
                    "[LLUDPSERVER]: UseCircuitCode handling from endpoint {0}, client {1} {2} failed.  Exception {3}{4}",
                    endPoint != null ? endPoint.ToString() : "n/a",
                    client != null ? client.Name : "unknown",
                    client != null ? client.AgentId.ToString() : "unknown",
                    e.Message,
                    e.StackTrace);
            }
        }

        private void HandleCompleteMovementIntoRegion(object o)
        {
            IPEndPoint endPoint = null;
            IClientAPI client = null;

            try
            {
                object[] array = (object[])o;
                endPoint = (IPEndPoint)array[0];
                CompleteAgentMovementPacket packet = (CompleteAgentMovementPacket)array[1];

                m_log.DebugFormat(
                    "[LLUDPSERVER]: Handling CompleteAgentMovement request from {0} in {1}", endPoint, m_scene.Name);

                // Determine which agent this packet came from
                // We need to wait here because in when using the OpenSimulator V2 teleport protocol to travel to a destination
                // simulator with no existing child presence, the viewer (at least LL 3.3.4) will send UseCircuitCode 
                // and then CompleteAgentMovement immediately without waiting for an ack.  As we are now handling these
                // packets asynchronously, we need to account for this thread proceeding more quickly than the 
                // UseCircuitCode thread.
                int count = 40;
                while (count-- > 0)
                {
                    if (m_scene.TryGetClient(endPoint, out client))
                    {
                        if (!client.IsActive)
                        {
                            // This check exists to catch a condition where the client has been closed by another thread
                            // but has not yet been removed from the client manager (and possibly a new connection has
                            // not yet been established).
                            m_log.DebugFormat(
                                "[LLUDPSERVER]: Received a CompleteAgentMovement from {0} for {1} in {2} but client is not active yet.  Waiting.",
                                endPoint, client.Name, m_scene.Name);
                        }
                        else if (client.SceneAgent == null)
                        {
                            // This check exists to catch a condition where the new client has been added to the client
                            // manager but the SceneAgent has not yet been set in Scene.AddNewAgent().  If we are too
                            // eager, then the new ScenePresence may not have registered a listener for this messsage
                            // before we try to process it.
                            // XXX: A better long term fix may be to add the SceneAgent before the client is added to 
                            // the client manager
                            m_log.DebugFormat(
                                "[LLUDPSERVER]: Received a CompleteAgentMovement from {0} for {1} in {2} but client SceneAgent not set yet.  Waiting.",
                                endPoint, client.Name, m_scene.Name);
                        }
                        else
                        {
                            break;
                        }
                    }
                    else
                    {
                        m_log.DebugFormat(
                            "[LLUDPSERVER]: Received a CompleteAgentMovement from {0} in {1} but no client exists yet.  Waiting.", 
                            endPoint, m_scene.Name);
                    }

                    Thread.Sleep(200);
                }

                if (client == null)
                {
                    m_log.DebugFormat(
                        "[LLUDPSERVER]: No client found for CompleteAgentMovement from {0} in {1} after wait.  Dropping.",
                        endPoint, m_scene.Name);

                    return;
                }
                else if (!client.IsActive || client.SceneAgent == null)
                {
                    // This check exists to catch a condition where the client has been closed by another thread
                    // but has not yet been removed from the client manager.
                    // The packet could be simply ignored but it is useful to know if this condition occurred for other debugging
                    // purposes.
                    m_log.DebugFormat(
                        "[LLUDPSERVER]: Received a CompleteAgentMovement from {0} for {1} in {2} but client is not active after wait.  Dropping.",
                        endPoint, client.Name, m_scene.Name);

                    return;
                }

                IncomingPacket incomingPacket1;

                // Inbox insertion
                if (UsePools)
                {
                    incomingPacket1 = m_incomingPacketPool.GetObject();
                    incomingPacket1.Client = (LLClientView)client;
                    incomingPacket1.Packet = packet;
                }
                else
                {
                    incomingPacket1 = new IncomingPacket((LLClientView)client, packet);
                }

                packetInbox.Enqueue(incomingPacket1);
            }
            catch (Exception e)
            {
                m_log.ErrorFormat(
                    "[LLUDPSERVER]: CompleteAgentMovement handling from endpoint {0}, client {1} {2} failed.  Exception {3}{4}",
                    endPoint != null ? endPoint.ToString() : "n/a",
                    client != null ? client.Name : "unknown",
                    client != null ? client.AgentId.ToString() : "unknown",
                    e.Message,
                    e.StackTrace);
            }
        }

        /// <summary>
        /// Send an ack immediately to the given endpoint.
        /// </summary>
        /// <remarks>
        /// FIXME: Might be possible to use SendPacketData() like everything else, but this will require refactoring so
        /// that we can obtain the UDPClient easily at this point.
        /// </remarks>
        /// <param name="remoteEndpoint"></param>
        /// <param name="sequenceNumber"></param>
        private void SendAckImmediate(IPEndPoint remoteEndpoint, uint sequenceNumber)
        {
            PacketAckPacket ack = new PacketAckPacket();
            ack.Header.Reliable = false;
            ack.Packets = new PacketAckPacket.PacketsBlock[1];
            ack.Packets[0] = new PacketAckPacket.PacketsBlock();
            ack.Packets[0].ID = sequenceNumber;

            SendAckImmediate(remoteEndpoint, ack);
        }

        public virtual void SendAckImmediate(IPEndPoint remoteEndpoint, PacketAckPacket ack)
        {
            byte[] packetData = ack.ToBytes();
            int length = packetData.Length;

            UDPPacketBuffer buffer = new UDPPacketBuffer(remoteEndpoint, length);
            buffer.DataLength = length;

            Buffer.BlockCopy(packetData, 0, buffer.Data, 0, length);

            AsyncBeginSend(buffer);
        }

        private bool IsClientAuthorized(UseCircuitCodePacket useCircuitCode, out AuthenticateResponse sessionInfo)
        {
            UUID agentID = useCircuitCode.CircuitCode.ID;
            UUID sessionID = useCircuitCode.CircuitCode.SessionID;
            uint circuitCode = useCircuitCode.CircuitCode.Code;

            sessionInfo = m_circuitManager.AuthenticateSession(sessionID, agentID, circuitCode);
            return sessionInfo.Authorised;
        }

        /// <summary>
        /// Add a client.
        /// </summary>
        /// <param name="circuitCode"></param>
        /// <param name="agentID"></param>
        /// <param name="sessionID"></param>
        /// <param name="remoteEndPoint"></param>
        /// <param name="sessionInfo"></param>
        /// <returns>The client if it was added.  Null if the client already existed.</returns>
        protected virtual IClientAPI AddClient(
            uint circuitCode, UUID agentID, UUID sessionID, IPEndPoint remoteEndPoint, AuthenticateResponse sessionInfo)
        {
            IClientAPI client = null;

            // We currently synchronize this code across the whole scene to avoid issues such as
            // http://opensimulator.org/mantis/view.php?id=5365  However, once locking per agent circuit can be done
            // consistently, this lock could probably be removed.
            lock (this)
            {
                if (!m_scene.TryGetClient(agentID, out client))
                {
                    LLUDPClient udpClient = new LLUDPClient(this, ThrottleRates, m_throttle, circuitCode, agentID, remoteEndPoint, m_defaultRTO, m_maxRTO);
    
                    client = new LLClientView(m_scene, this, udpClient, sessionInfo, agentID, sessionID, circuitCode);
                    client.OnLogout += LogoutHandler;
                    client.DebugPacketLevel = DefaultClientPacketDebugLevel;
    
                    ((LLClientView)client).DisableFacelights = m_disableFacelights;
    
                    client.Start();
                }
            }

            return client;
        }

        /// <summary>
        /// Deactivates the client if we don't receive any packets within a certain amount of time (default 60 seconds).
        /// </summary>
        /// <remarks>
        /// If a connection is active then we will always receive packets even if nothing else is happening, due to
        /// regular client pings.
        /// </remarks>
        /// <param name='client'></param>
        /// <param name='timeoutTicks'></param>
        private void DeactivateClientDueToTimeout(LLClientView client, int timeoutTicks)
        {
            lock (client.CloseSyncLock)
            {    
                ClientLogoutsDueToNoReceives++;

                m_log.WarnFormat(
                    "[LLUDPSERVER]: No packets received from {0} agent of {1} for {2}ms in {3}.  Disconnecting.",
                    client.SceneAgent.IsChildAgent ? "child" : "root", client.Name, timeoutTicks, m_scene.Name);
    
                if (!client.SceneAgent.IsChildAgent)
                     client.Kick("Simulator logged you out due to connection timeout.");
            }

            m_scene.CloseAgent(client.AgentId, true);
        }

        private void IncomingPacketHandler()
        {
            // Set this culture for the thread that incoming packets are received
            // on to en-US to avoid number parsing issues
            Culture.SetCurrentCulture();

            while (IsRunningInbound)
            {
                try
                {
                    IncomingPacket incomingPacket = null;

                    /*
                    // HACK: This is a test to try and rate limit packet handling on Mono.
                    // If it works, a more elegant solution can be devised
                    if (Util.FireAndForgetCount() < 2)
                    {
                        //m_log.Debug("[LLUDPSERVER]: Incoming packet handler is sleeping");
                        Thread.Sleep(30);
                    }
                     */

                    if (packetInbox.Dequeue(100, ref incomingPacket))
                    {
                        ProcessInPacket(incomingPacket);//, incomingPacket); Util.FireAndForget(ProcessInPacket, incomingPacket);

                        if (UsePools)
                            m_incomingPacketPool.ReturnObject(incomingPacket);
                    }
                }
                catch (Exception ex)
                {
                    m_log.Error("[LLUDPSERVER]: Error in the incoming packet handler loop: " + ex.Message, ex);
                }

                Watchdog.UpdateThread();
            }

            if (packetInbox.Count > 0)
                m_log.Warn("[LLUDPSERVER]: IncomingPacketHandler is shutting down, dropping " + packetInbox.Count + " packets");
            packetInbox.Clear();

            Watchdog.RemoveThread();
        }

        private void OutgoingPacketHandler()
        {
            // Set this culture for the thread that outgoing packets are sent
            // on to en-US to avoid number parsing issues
            Culture.SetCurrentCulture();

            // Typecast the function to an Action<IClientAPI> once here to avoid allocating a new
            // Action generic every round
            Action<IClientAPI> clientPacketHandler = ClientOutgoingPacketHandler;

            while (base.IsRunningOutbound)
            {
                try
                {
                    m_packetSent = false;

                    #region Update Timers

                    m_resendUnacked = false;
                    m_sendAcks = false;
                    m_sendPing = false;

                    // Update elapsed time
                    int thisTick = Environment.TickCount & Int32.MaxValue;
                    if (m_tickLastOutgoingPacketHandler > thisTick)
                        m_elapsedMSOutgoingPacketHandler += ((Int32.MaxValue - m_tickLastOutgoingPacketHandler) + thisTick);
                    else
                        m_elapsedMSOutgoingPacketHandler += (thisTick - m_tickLastOutgoingPacketHandler);

                    m_tickLastOutgoingPacketHandler = thisTick;

                    // Check for pending outgoing resends every 100ms
                    if (m_elapsedMSOutgoingPacketHandler >= 100)
                    {
                        m_resendUnacked = true;
                        m_elapsedMSOutgoingPacketHandler = 0;
                        m_elapsed100MSOutgoingPacketHandler += 1;
                    }

                    // Check for pending outgoing ACKs every 500ms
                    if (m_elapsed100MSOutgoingPacketHandler >= 5)
                    {
                        m_sendAcks = true;
                        m_elapsed100MSOutgoingPacketHandler = 0;
                        m_elapsed500MSOutgoingPacketHandler += 1;
                    }

                    // Send pings to clients every 5000ms
                    if (m_elapsed500MSOutgoingPacketHandler >= 10)
                    {
                        m_sendPing = true;
                        m_elapsed500MSOutgoingPacketHandler = 0;
                    }

                    #endregion Update Timers

                    // Use this for emergency monitoring -- bug hunting
                    //if (m_scene.EmergencyMonitoring)
                    //    clientPacketHandler = MonitoredClientOutgoingPacketHandler;
                    //else
                    //    clientPacketHandler = ClientOutgoingPacketHandler;

                    // Handle outgoing packets, resends, acknowledgements, and pings for each
                    // client. m_packetSent will be set to true if a packet is sent
                    m_scene.ForEachClient(clientPacketHandler);

                    m_currentOutgoingClient = null;

                    // If nothing was sent, sleep for the minimum amount of time before a
                    // token bucket could get more tokens
                    //if (!m_packetSent)
                    //    Thread.Sleep((int)TickCountResolution);
                    //
                    // Instead, now wait for data present to be explicitly signalled.  Evidence so far is that with
                    // modern mono it reduces CPU base load since there is no more continuous polling.
                    if (!m_packetSent)
                        m_dataPresentEvent.WaitOne(100);

                    Watchdog.UpdateThread();
                }
                catch (Exception ex)
                {
                    m_log.Error("[LLUDPSERVER]: OutgoingPacketHandler loop threw an exception: " + ex.Message, ex);
                }
            }

            Watchdog.RemoveThread();
        }

        protected void ClientOutgoingPacketHandler(IClientAPI client)
        {
            m_currentOutgoingClient = client;

            try
            {
                if (client is LLClientView)
                {
                    LLClientView llClient = (LLClientView)client;
                    LLUDPClient udpClient = llClient.UDPClient;

                    if (udpClient.IsConnected)
                    {
                        if (m_resendUnacked)
                            HandleUnacked(llClient);

                        if (m_sendAcks)
                            SendAcks(udpClient);

                        if (m_sendPing)
                            SendPing(udpClient);

                        // Dequeue any outgoing packets that are within the throttle limits
                        if (udpClient.DequeueOutgoing())
                            m_packetSent = true;
                    }
                }
            }
            catch (Exception ex)
            {
                m_log.Error(
                    string.Format("[LLUDPSERVER]: OutgoingPacketHandler iteration for {0} threw ", client.Name), ex);
            }
        }

        #region Emergency Monitoring
        // Alternative packet handler fuull of instrumentation
        // Handy for hunting bugs
        private Stopwatch watch1 = new Stopwatch();
        private Stopwatch watch2 = new Stopwatch();

        private float avgProcessingTicks = 0;
        private float avgResendUnackedTicks = 0;
        private float avgSendAcksTicks = 0;
        private float avgSendPingTicks = 0;
        private float avgDequeueTicks = 0;
        private long nticks = 0;
        private long nticksUnack = 0;
        private long nticksAck = 0;
        private long nticksPing = 0;
        private int npacksSent = 0;
        private int npackNotSent = 0;

        /// <summary>
        /// Number of inbound packets processed since startup.
        /// </summary>
        public long IncomingPacketsProcessed { get; private set; }

        private void MonitoredClientOutgoingPacketHandler(IClientAPI client)
        {
            nticks++;
            watch1.Start();
            m_currentOutgoingClient = client;

            try
            {
                if (client is LLClientView)
                {
                    LLClientView llClient = (LLClientView)client;
                    LLUDPClient udpClient = llClient.UDPClient;

                    if (udpClient.IsConnected)
                    {
                        if (m_resendUnacked)
                        {
                            nticksUnack++;
                            watch2.Start();

                            HandleUnacked(llClient);

                            watch2.Stop();
                            avgResendUnackedTicks = (nticksUnack - 1)/(float)nticksUnack * avgResendUnackedTicks + (watch2.ElapsedTicks / (float)nticksUnack);
                            watch2.Reset();
                        }

                        if (m_sendAcks)
                        {
                            nticksAck++;
                            watch2.Start();
                            
                            SendAcks(udpClient);

                            watch2.Stop();
                            avgSendAcksTicks = (nticksAck - 1) / (float)nticksAck * avgSendAcksTicks + (watch2.ElapsedTicks / (float)nticksAck);
                            watch2.Reset();
                        }

                        if (m_sendPing)
                        {
                            nticksPing++;
                            watch2.Start();
                            
                            SendPing(udpClient);

                            watch2.Stop();
                            avgSendPingTicks = (nticksPing - 1) / (float)nticksPing * avgSendPingTicks + (watch2.ElapsedTicks / (float)nticksPing);
                            watch2.Reset();
                        }

                        watch2.Start();
                        // Dequeue any outgoing packets that are within the throttle limits
                        if (udpClient.DequeueOutgoing())
                        {
                            m_packetSent = true;
                            npacksSent++;
                        }
                        else
                        {
                            npackNotSent++;
                        }

                        watch2.Stop();
                        avgDequeueTicks = (nticks - 1) / (float)nticks * avgDequeueTicks + (watch2.ElapsedTicks / (float)nticks);
                        watch2.Reset();

                    }
                    else
                    {
                        m_log.WarnFormat("[LLUDPSERVER]: Client is not connected");
                    }
                }
            }
            catch (Exception ex)
            {
                m_log.Error("[LLUDPSERVER]: OutgoingPacketHandler iteration for " + client.Name +
                    " threw an exception: " + ex.Message, ex);
            }
            watch1.Stop();
            avgProcessingTicks = (nticks - 1) / (float)nticks * avgProcessingTicks + (watch1.ElapsedTicks / (float)nticks);
            watch1.Reset();

            // reuse this -- it's every ~100ms
            if (m_scene.EmergencyMonitoring && nticks % 100 == 0)
            {
                m_log.InfoFormat("[LLUDPSERVER]: avg processing ticks: {0} avg unacked: {1} avg acks: {2} avg ping: {3} avg dequeue: {4} (TickCountRes: {5} sent: {6} notsent: {7})", 
                    avgProcessingTicks, avgResendUnackedTicks, avgSendAcksTicks, avgSendPingTicks, avgDequeueTicks, TickCountResolution, npacksSent, npackNotSent);
                npackNotSent = npacksSent = 0;
            }

        }

        #endregion 

        private void ProcessInPacket(IncomingPacket incomingPacket)
        {
            Packet packet = incomingPacket.Packet;
            LLClientView client = incomingPacket.Client;

            if (client.IsActive)
            {
                m_currentIncomingClient = client;

                try
                {
                    // Process this packet
                    client.ProcessInPacket(packet);
                }
                catch (ThreadAbortException)
                {
                    // If something is trying to abort the packet processing thread, take that as a hint that it's time to shut down
                    m_log.Info("[LLUDPSERVER]: Caught a thread abort, shutting down the LLUDP server");
                    Stop();
                }
                catch (Exception e)
                {
                    // Don't let a failure in an individual client thread crash the whole sim.
                    m_log.Error(
                        string.Format(
                            "[LLUDPSERVER]: Client packet handler for {0} for packet {1} threw ",
                            client.Name, packet.Type),
                        e);
                }
                finally
                {
                    m_currentIncomingClient = null;
                }
            }
            else
            {
                m_log.DebugFormat(
                    "[LLUDPSERVER]: Dropped incoming {0} for dead client {1} in {2}",
                    packet.Type, client.Name, m_scene.RegionInfo.RegionName);
            }

            IncomingPacketsProcessed++;
        }

        protected void LogoutHandler(IClientAPI client)
        {
            client.SendLogoutPacket();

            if (!client.IsLoggingOut)
            {
                client.IsLoggingOut = true;
                m_scene.CloseAgent(client.AgentId, false);
            }
        }
    }
}