aboutsummaryrefslogtreecommitdiffstats
path: root/alljoyn_core/router/UDPTransport.cc
blob: a17402f21336207619006ef6a9d9efbcdc42f868 (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
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
/**
 * @file
 * UDPTransport is an implementation of UDPTransportBase for daemons.
 */

/******************************************************************************
 *    Copyright (c) Open Connectivity Foundation (OCF), AllJoyn Open Source
 *    Project (AJOSP) Contributors and others.
 *
 *    SPDX-License-Identifier: Apache-2.0
 *
 *    All rights reserved. This program and the accompanying materials are
 *    made available under the terms of the Apache License, Version 2.0
 *    which accompanies this distribution, and is available at
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Copyright (c) Open Connectivity Foundation and Contributors to AllSeen
 *    Alliance. All rights reserved.
 *
 *    Permission to use, copy, modify, and/or distribute this software for
 *    any purpose with or without fee is hereby granted, provided that the
 *    above copyright notice and this permission notice appear in all
 *    copies.
 *
 *    THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
 *    WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
 *    WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
 *    AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
 *    DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
 *    PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
 *    TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 *    PERFORMANCE OF THIS SOFTWARE.
 ******************************************************************************/

#include <algorithm>
#include <qcc/platform.h>
#include <qcc/IPAddress.h>
#include <qcc/Socket.h>
#include <qcc/Thread.h>
#include <qcc/Condition.h>
#include <qcc/String.h>
#include <qcc/StringUtil.h>
#include <qcc/IfConfig.h>
#include <qcc/LockLevel.h>
#include <qcc/PerfCounters.h>

#include <alljoyn/AllJoynStd.h>
#include <alljoyn/BusAttachment.h>
#include <alljoyn/Session.h>
#include <alljoyn/TransportMask.h>

#include <BusUtil.h>
#include "BusInternal.h"
#include "BusController.h"
#include "ConfigDB.h"
#include "RemoteEndpoint.h"
#include "Router.h"
#include "DaemonRouter.h"

#include "ArdpProtocol.h"
#include "ns/IpNameService.h"
#include "UDPTransport.h"
#if ARDP_TESTHOOKS
#include "ScatterGatherList.h"
#endif

/*
 * How the transport fits into the system
 * ======================================
 *
 * AllJoyn provides the concept of a Transport which provides a relatively
 * abstract way for the daemon to use different network mechanisms for getting
 * Messages from place to another.  Conceptually, think of, for example, a Unix
 * transport that moves bits using unix domain sockets or a TCP transport that
 * moves Messages over a TCP connection.  A UDP transport moves Messages over
 * UDP datagrams using a reliability layer.
 *
 * BSD sockets is oriented toward clients and servers.  There are different
 * sockets calls required for a program implementing a server-side part and a
 * client side part.  The server-side listens for incoming connection requests
 * and the client-side initiates the requests.  AllJoyn clients are bus
 * attachments that our Applications may use and these can only initiate
 * connection requests to AllJoyn daemons.  Although dameons may at first blush
 * appear as the service side of a typical BSD sockets client-server pair, it
 * turns out that while daemons obviously must listen for incoming connections,
 * they also must be able to initiate connection requests to other daemons.
 * This explains the presence of both connect-like methods and listen-like
 * methods here.
 *
 * A fundamental idiom in the AllJoyn system is that of a thread.  Active
 * objects in the system that have threads wandering through them will implement
 * Start(), Stop() and Join() methods.  These methods work together to manage
 * the autonomous activities that can happen in a UDPTransport.  These
 * activities are carried out by so-called hardware threads.  POSIX defines
 * functions used to control hardware threads, which it calls pthreads.  Many
 * threading packages use similar constructs.
 *
 * In a threading package, a start method asks the underlying system to arrange
 * for the start of thread execution.  Threads are not necessarily running when
 * the start method returns, but they are being *started*.  Some time later, a
 * thread of execution appears in a thread run function, at which point the
 * thread is considered *running*.  In the case of the UDPTransport, the Start()
 * method spins up a thread to run the basic maintenance operations such as
 * deciding when to listen and advertise.  Another thread(s) is started to deal
 * with handling callbacks for deadlock avoidance.  The AllJoyn daemon is a
 * fundamentally multithreaded environemnt, so multiple threads may be trying to
 * connect, disconnect, and write from the daemon side, and at the same time
 * connect, disconnect, read and write callbacks may be coming from the network
 * side.  This means that as soon as UDPTransport::Start() is executed, multiple
 * threads, originating both in the transport and from outside, may be wandering
 * around in objects used by the tansport; and so one must be very careful about
 * resource management.  This is the source of much of the complexity in this
 * module.
 *
 * In generic threads packages, executing a stop method asks the underlying
 * system to arrange for a thread to end its execution.  The system typically
 * sends a message to the thread to ask it to stop doing what it is doing.  The
 * thread is running until it responds to the stop message, at which time the
 * run method exits and the thread is considered *stopping*.  The UDPTransport
 * provides a Stop() method to do exactly that.  Note that neither of Start()
 * nor Stop() are synchronous in the sense that one has actually accomplished
 * the desired effect upon the return from a call.  Of particular interest is
 * the fact that after a call to Stop(), threads will still be *running* for
 * some non-deterministic time.  In order to wait until all of the threads have
 * actually stopped, a blocking call is required.  In threading packages this is
 * typically called join, and our corresponding method is called Join().  A user
 * of the UDPTransport must assume that immediately after a call to Start() is
 * begun, and until a call to Join() returns, there may be threads of execution
 * wandering anywhere in the transport and in any callback registered by the
 * caller.  The same model applies to connection endpoints (_UDPEndpoint)
 * instances.  Further complicating _UDPEndpoint design is that the thread
 * lifetime methods may be called repeatedly or never (in the case of some forms
 * of timeout); and so the transport needs to ensure that all combinations of
 * these state transitions occur in an orderly and deterministic manner.
 *
 * The high-level process regarding how an advertisement translates into a
 * transport Connect() is a bit opaque, so we paint a high-level picture here.
 * First, a service (that will be *handling* RPC calls and *emitting* signals)
 * acquires a name on the bus, binds a session port and calls AdvertiseName.
 * This filters down (possibly through language bindings) to the AllJoyn Object.
 * The AllJoynObj essentially turns a DBus into an AllJoyn bus.  The AllJoyn
 * Object consults the transports on the transport list (the UDP transport is
 * one of those) and eventually sends an advertisement request to each specified
 * transport by calling each transport's EnableAdvertisement() method.  We
 * transnslate this call to a call to the IpNameService::AdvertiseName()
 * method we call since we are an IP-based transport.  The IP name service will
 * multicast the advertisements to other daemons listening on our device's
 * connected networks.
 *
 * A client that is interested in using the service calls the discovery
 * method FindAdvertisedName.  This filters down (possibly through
 * language bindings) to the AllJoyn object, into the transports on the
 * transport list (us) and we eventually call IpNameService::FindAdvertisedName()
 * since we are an IP-based transport.  The IP name service multicasts the
 * discovery message to other daemons listening on our networks.
 *
 * The daemon remembers which clients have expressed interest in which services,
 * and expects name services to call back with the bus addresses of daemons they
 * find which have the associated services.  When a new advertisement is
 * received, the name service fires a callback into the transport, and it, in turn, calls
 * into its associated BusListener to pass the information back to the daemon.
 *
 * The callback includes information about the discovered name, the IP address,
 * port and daemon GUID of the remote daemon (now Routing Node).  This bus
 * address is "hidden" from interested clients and replaced with a more generic
 * name and TransportMask bit (for us it will be TRANSPORT_UDP).  The client
 * either responds by (1) ignoring the advertisement; (2) waiting to accumulate
 * more answers to see what the options are; or (3) joins a session to the
 * implied daemon/service.  A reference to a SessionOpts object is provided as a
 * parameter to a JoinSession call if the client wants to connect.  This
 * SessionOpts reference is passed down into the transport (selected by the
 * TransportMask) into the Connect() method which is used to establish the
 * connection and can be used to determine if the discovered name posesses
 * certain desired characteristics (to aid in determine the course of action
 * of the client
 *
 * There are four basic connection mechanisms that are described by the options.
 * These can be viewed as a matrix;
 *
 *                                                      IPv4               IPv6
 *                                                 ---------------    ---------------
 *     TRAFFIC MESSAGES | TRAFFIC_RAW_RELIABLE  |   Reliable IPv4      Reliable IPv6
 *     TRAFFIC_RAW_UNRELIABLE                   |  Unreliable IPv4    Unreliable IPv6
 *
 * Note that although the UDP protocol is unreliable, the AllJoyn Reliable Datagram
 * Protocol is an additional reliability layer, so that TRAFFIC_MESSAGES are actually
 * sent over the UDP protocol.

 * The bits in the provided SessionOpts select the row, but the column is left
 * free (unspecified).  This means that it is up to the transport to figure out
 * which one to use.  Clearly, if only one of the two address flavors is
 * possible (known from examining the returned bus address which is called a
 * connect spec in the Connect() method) the transport should choose that one.
 * If both IPv4 or IPv6 are available, it is up to the transport (again, us) to
 * choose the "best" method since we don't bother clients with that level of
 * detail.
 *
 * Perhaps somewhat counter-intuitively, advertisements relating to the
 * UDP Transport use the addr (unreliable IPv4 or IPv6 address), and port
 * unreliable IPv4 or IPv6 port).
 * At the same time, the UDP Transport tells clients of the transport that it
 * supports TRAFFIC MESSAGES only.  This is because the underlying network
 * protocol used is UDP which is inherently unreliable.  We provide a
 * reliability layer to translate the unreliable UDP4 and UDP6 datagrams into
 * reliable AllJoyn messages.  The UDP Transpot does not provide RAW sockets
 * which is a deprecated traffic type.
 *
 * Internals
 * =========
 *
 * We spend a lot of time on the threading aspects of the transport since they
 * are often the hardest part to get right and are complicated.  This is where
 * the bugs live.
 *
 * As mentioned above, the AllJoyn system uses the concept of a Transport.  You
 * are looking at the UDPTransport.  Each transport also has the concept of an
 * Endpoint.  The most important function fo an endpoint is to provide (usually)
 * non-blocking semantics to higher level code.  If the source thread overruns
 * the ability of the transport to move bits (reliably), we must apply
 * back-pressure by blocking the calling thread, but usually a call to PushBytes
 * results in an immediate UDP datagram sendto.  In the UDP transport there are
 * separate worker threads assigned to reading UDP datagrams, running the
 * reliability layer and dispatching received AllJoyn messages.
 *
 * Endpoints are specialized into the LocalEndpoint and the RemoteEndpoint
 * classes.  LocalEndpoint represents a connection from a router to the local
 * bus attachment or daemon (within the "current" process).  A RemoteEndpoint
 * represents a connection from a router to a remote attachment or daemon.  By
 * definition, the UDPTransport provides RemoteEndpoint functionality.
 *
 * RemoteEndpoints are further specialized according to the flavor of the
 * corresponding transport, and so you will see a UDPEndpoint class defined
 * below which provides functionality to send messages from the local router to
 * a destination off of the local process using a UDP transport mechanism.
 *
 * RemoteEndpoints use AllJoyn stream objects to actually move bits.  In UDP
 * this is a bit of an oxymoron, however an AllJoyn stream is a thin layer on
 * top of a Socket (which is another thin layer on top of a BSD socket) that
 * provides a PushBytes() method.  Although UDP is not a stream-based protocol,
 * we treat each received datagram as a separate stream for the purposes of
 * passing back to the AllJoyn core which expectes to be able to read bytes from
 * a message backing object.
 *
 * Unlike a TCP transport, there are no dedicated receive threads.  Receive
 * operations in UDP are not associted with a particular endpoint at all, other
 * than using the required endpoint as a convencient place holder for a
 * connection data structure.  The UDP Transport operates more in an
 * Asynchronous IO-like fashion.  Received datagrams appear out of the ARDP
 * protocol as callbacks and are sent into a callback dispatcher thread.  Once
 * the dispatcher has an inbound datagram(s) it reassembles and unmarshals the
 * datagrams into an AllJoyn Message.  It then calls into the daemon
 * (PushMessage) to arrange for delivery.  A separate thread runs the
 * maintenance aspects of the UDP reliability layer (to drive retransmissions,
 * timeouts, etc.) and the endpoint management code (to drive the lifetime state
 * transitions of endpoints).
 *
 * The UDPEndpoint inherits some infrastructure from the more generic
 * RemoteEndpoint class.  Since the UDP transport is a not a stream-based
 * protocol, it does redefine some of the basic operation of the RemoteEndpoint
 * to suit its needs.  The RemoteEndpoint is also somewhat bound to the concept
 * of stream and receive thread, so we have to jump through some hoops to
 * coexist.
 *
 * The UDP endpoint does not use SASL for authentication and implements required
 * dameon exchanges in the SYN, SYN + ACK echanges of the underlying ARDP
 * protocol.  Although there is no authentication, per se, we still call this
 * handshake phase authentication since the BusHello is part of the
 * authentication phase of the TCP Transport.  Authentication can, of course,
 * succeed or fail based on timely interaction between the two sides, but it can
 * also be abused in a denial of service attack.  If a client simply starts the
 * process but never responds, it could tie up a daemon's resources, and
 * coordinated action could bring down a daemon.  Because of this, we provide a
 * way to reach in and abort authentications that are "taking too long" and free
 * the associated resources.
 *
 * As described above, a daemon can listen for inbound connections and it can
 * initiate connections to remote daemons.  Authentication must happen in both
 * cases and so we need to worry about denial of service in both directions and
 * recover gracefully.
 *
 * When the daemon is brought up, its TransportList is Start()ed.  The transport
 * specs string (e.g., "unix:abstract=alljoyn;udp:;tcp:") is provided to
 * TransportList::Start() as a parameter.  The transport specs string is parsed
 * and in the example above, results in "unix" transports, "tcp" transports and
 * "udp" transports being instantiated and started.  As mentioned previously
 * "udp:" in the daemon translates into UDPTransport.  Once the desired
 * transports are instantiated, each is Start()ed in turn.  In the case of the
 * UDPTransport, this will start the maintenance loop.  Initially there are no
 * sockets to listen on.
 *
 * The daemon then needs to start listening on inbound addresses and ports.
 * This is done by the StartListen() command.  This also takes the same kind of
 * server args string shown above but this time the address and port information
 * are used.  For example, one might use the string
 * "udp:addr=0.0.0.0,port=9955;" to specify which address and port to listen
 * to.  This Bus::StartListen() call is translated into a transport
 * StartListen() call which is provided with the string described above, which
 * we call a "listen spec".  Our UDPTransport::StartListen() will arange to
 * create two sockets: one for incoming connections (sessions hosted by us) and
 * one for outgoing connections (sessions hosted by other routing nodes).
 * Both sockets will be bound to the address provided. The socket for incoming
 * connections will be bound to the port provided, the socket for outgoing
 * connections is always bound to an ephemeral port. Both sockets will be
 * added to a list of "listenFds".  Another of the many
 * complications we have to deal with is that the Android Compatibility Test
 * Suite (CTS) requires that an idle phone not have any sockets listening for
 * inbound data.  In order to pass the CTS in the case of the pre-installed
 * daemon, we must only have open name service sockets when actively advertising
 * or discovering.  This implies that we need to track the adveritsement state
 * and enable or disable the name service depending on that state.
 *
 * An inbound connection request in the UDP transport is consists of receiving a
 * SYN datagram.  The AcceptCb() is called from the reliability layer (on
 * reception of a SYN packet) in order to ask whether or not the connection
 * should be accepted.  If AcceptCb() determines there are enough resources for
 * a new connection it will call ARDP_Accept to provide a BusHello reply and
 * return true indicating acceptance, or false which means rejection.  If the
 * connection is accepted, a ConnectCb() is fired and the callback dispatcher
 * thread will ultimately handle the incoming request and create a UDPEndpoint
 * for the *proposed* new connection.
 *
 * Recall that an endpoint is not brought up immediately, but an authentication
 * step must be performed.  The required information (BusHello reply) is
 * provided back in the SYN + ACK packet.  The final ACK of the three-way
 * handshake completes the inbound connection establishment process.
 * If the authentication takes "too long" we assume that a denial of service
 * attack in in progress.  We fail such partial connections and the endpoint
 * management code removes them.
 *
 * A daemon transport can accept incoming connections, and it can make outgoing
 * connections to another daemon.  This case is simpler than the accept case
 * since it is expected that a socket connect can block higner level code, so it
 * is possible to do authentication in the context of the thread calling
 * Connect().  Connect() is provided a so-called "connect spec" which provides
 * an IP address ("addr=xxxx"), port ("port=yyyy") in a String.  A check is
 * always made to catch an attempt for the daemon to connect to itself which is
 * a system-defined error (it causes the daemon grief, so we avoid it here by
 * looking to see if one of the listenFds is listening on an interface that
 * corresponds to the address in the connect spec).  If the connect is allowed,
 * ee kick off a process in the underlying UDP reliability layer that
 * corresponds to the 3-way handshake of TCP.
 *
 * Shutting the UDPTransport down involves orchestrating the orderly termination
 * of:
 *
 *   1) Threads that may be running in the maintenance loop with associated Events
 *      and their dependent socketFds stored in the listenFds list;
 *   3) The callback dispatcher thread that may be out wandering around in the
 *      daemon doing its work;
 *   2) Threads that may be running around in endpoints and streams trying to write
 *      Mesages to the network.
 *
 * We have to be careful to follow the AllJoyn threading model transitions in
 * both the UDPTransport and all of its associated _UdpEndpoints.  There are
 * reference counts of endpoints to be respected as well.  In order to ensure
 * orderly termination of endoints and deterministic disposition of threads
 * which may be executing in those endpoints, We want the last reference count
 * held on an endpoint to be the one held by the transport.  There is much
 * work (see IncrementAndFetch, DecrementAndFetch, ManagedObj for example)
 * done to ensure this outcome.
 *
 * There are a lot of very carefully managed relationships here, so be careful
 * when making changes to the thread and resource management aspects of any
 * transport.  Taking lock order lightly is a recipe for disaster.  Always
 * consider what locks are taken where and in what order.  It's quite easy to
 * shoot yourself in multiple feet you never knew you had if you make an unwise
 * modification, and this can sometimes result in tiny little time-bombs set to
 * go off in seemingly completely unrelated code.
 *
 * A note on connection establishment
 * ==================================
 *
 * In the TCP transport, a separate synchronous sequence is executed before
 * AllJoyn messages can begin flowing.  First a NUL byte is sent as is required
 * in the DBus spec.  In order to get a destination address for the BusHello
 * message, the local side relies on the SASL three-way handshake exchange:
 *
 *     SYN ------------>
 *                       <- SYN + ACK
 *     ACK ------------>
 *     NUL ------------>
 *     AUTH ANONYMOUS ->
 *                       <- OK <GUID>
 *     BEGIN ---------->
 *
 * Once this is done, the active connector sends a BusHello Message and the
 * passive side sends a response
 *
 *     BusHello ------->
 *                       <- BusHello reply
 *
 * In the UDP Transport, we get rid of basically the whole Authentication
 * process and exchange required information in the SYN, SYN + ACK and
 * ACK packets of the protocol three-way handshake.
 *
 * The initial ARDP SYN packet *implies* AUTH_ANONYMOUS and contains the
 * BusHello message data from the Local (initiating/active) side of the
 * connection.  The SYN + ACK segment in response from the remote side contains
 * the response to the BusHello that was sent in the SYN packet.
 *
 *     SYN + BusHello -->
 *                        <- SYN + ACK + BusHello Reply
 *     ACK ------------->
 *
 * This all happens in a TCP-like SYN, SYN + ACK, ACK exchange with AllJoyn
 * data.  At the reception of the final ACK, the connection is up and running.
 *
 * This exchange is implemented using a number of callback functions that
 * fire on the local (active) and remote (passive) side of the connection.
 *
 * 1) The actively connecting side provides a BusHello message in call to
 *    ARDP_Connect().  As described above, ARDP provides this message as data in
 *    the SYN segment which is the first part of the three-way handshake;
 *
 * 2) When the passive side receives the SYN segment, its AcceptCb() callback is
 *    fired.  The data provided in the accept callback contains the BusHello
 *    message from the actively opening side.  The passive side, if it chooses
 *    to accept the connection, makes a call to ARDP_Accept() with its reply to
 *    the BusHello from the active side as data.  ARDP provides this data back
 *    in the SYN + ACK segment as the second part of its three-way handshake;
 *
 * 3) The actively connecting side receives a ConnectCb() callback as a result
 *    of the SYN + ACK coming back from the passive side.  This indicates that
 *    the newly established connection is going into the OPEN state from the
 *    local side's (ARDP) perspective.  Prior to firing the callback, ARDP
 *    automatically sends the final ACK and completes the three-way handshake.
 *    The ConectCb() with the active indication means that a SYN + ACK has been
 *    received that includes the reply to the original BusHello message.
 *
 * 4) When the final ACK of the three-way handshake is delivered to the passive
 *    opener side, it transitions the passive side to the OPEN state and fires
 *    a ConnectCb() callback with the passive indication meaning that the final
 *    ACK of the three-way handhake has arrived.
 *
 * From the perspective of the UDP Transport, this translates into the following
 * sequence diagram that reflects the three-way handshake that is going on under
 * the whole thing.
 *
 *                  Active Side                          Passive Side
 *                  ===========                          ============
 *      ARDP_Connect([out]BusHello message) --> AcceptCb([in]BusHello message) -----+
 *                                                                                  |
 * +--- ConnectCb([in]BusHello reply) <-------- ARDP_Accept([out]BusHello reply) <--+
 * |
 * +------------------------------------------> ConnectCb(NULL)
 *
 */

#define QCC_MODULE "UDP"

#define SENT_SANITY 0   /**< If non-zero make sure ARDP is returning buffers correctly (expensive) */
#define BYTEDUMPS 0     /**< If non-zero do byte-by-byte debug dumps of sent and received buffers (super-expensive) */
#define RETURN_ORPHAN_BUFS 0 /**< If non-zero, call ARDP_RecvReady on any buffers we can't forward (processed after endpoint is torn down) */

using namespace std;
using namespace qcc;

const uint32_t UDP_STALL_REPORT_INTERVAL = 10000; /** Minimum time between stall warning log messages */

const uint32_t UDP_ENDPOINT_MANAGEMENT_TIMER = 1000;  /** Maximum time between calls to ManageEndpoints -- a watchdog */
const uint32_t UDP_ENDPOINT_MANAGEMENT_MIN = 100;  /** There's really no reason to run the management faster than this */
const uint32_t UDP_WAIT_WATCHDOG_TIMEOUT = 5000; /** Max time in EP_WAITING state before giving up on sending msgs */
const uint32_t UDP_WATCHDOG_TIMEOUT = 30000;  /**< How long to wait before printing an error if an endpoint is not going away */
const uint32_t UDP_MESSAGE_PUMP_TIMEOUT = 10000;  /**< How long to keep a message pump thread running with nothing to do */

const uint32_t UDP_CONNECT_TIMEOUT = 1000;  /**< How long before we expect a connection to complete */
const uint32_t UDP_CONNECT_RETRIES = 10;  /**< How many times do we retry a connection before giving up */
const uint32_t UDP_INITIAL_DATA_TIMEOUT = 1000;  /**< Initial value for how long do we wait before retrying sending data */
const uint32_t UDP_TOTAL_DATA_RETRY_TIMEOUT = 30000;  /**< Initial total amount of time to try and send data before giving up */
const uint32_t UDP_MIN_DATA_RETRIES = 5;  /**< Minimum number of times to try and send data before giving up */
const uint32_t UDP_PERSIST_INTERVAL = 1000;  /**< How long do we wait before pinging the other side due to a zero window */
const uint32_t UDP_TOTAL_APP_TIMEOUT = 30000;  /**< How long to we try to ping for window opening before deciding app is not pulling data */
const uint32_t UDP_LINK_TIMEOUT = 30000;  /**< How long before we decide a link is down (with no reponses to keepalive probes */
const uint32_t UDP_KEEPALIVE_RETRIES = 5;  /**< How many times do we try to probe on an idle link before terminating the connection */
const uint32_t UDP_FAST_RETRANSMIT_ACK_COUNTER = 1;  /**< How many duplicate acknowledgements to we need to trigger a data retransmission */
const uint32_t UDP_DELAYED_ACK_TIMEOUT = 100; /**< How long do we wait until acknowledging received segments */
const uint32_t UDP_TIMEWAIT = 1000;  /**< How long do we stay in TIMWAIT state before releasing the per-connection resources */

/*
 * Note that UDP_SEGBMAX * UDP_SEGMAX must be greater than or equal to
 * ALLJOYN_MAX_PACKET_LEN (135168) to ensure we can deliver a maximally sized AllJoyn
 * message.
 */
const uint32_t UDP_SEGBMAX = 4440;  /**< Maximum size of an ARDP segment (quantum of reliable transmission) */
const uint32_t UDP_SEGMAX = 93;  /**< Maximum number of ARDP segment in-flight (bandwidth-delay product sizing) */

/*
 * The default address for use in listen specs. INADDR_ANY or IN6ADDR_ANY means to listen
 * for UDP connections on any interfaces that are currently up or any that may
 * come up in the future.
 */
static const char* ADDR4_DEFAULT = "0.0.0.0";
static const char* ADDR6_DEFAULT = "::";

/*
 * The default port for use in listen specs.
 */
static const uint16_t PORT_DEFAULT = 9955;

namespace ajn {

/**
 * Name of transport used in transport specs.
 */
const char* UDPTransport::TransportName = "udp";

/**
 * Default router advertisement prefix.  Currently Thin Library devices cannot
 * connect to routing nodes over UDP.
 */
const char* const UDPTransport::ALLJOYN_DEFAULT_ROUTER_ADVERTISEMENT_PREFIX = "org.alljoyn.BusNode.";

/**
 * Prefix to quietly advertise when working around ASACORE-1298.  Keeps an
 * advertisement outstanding to prevent closing listen sockets out from under
 * UDP Endpoints.
 */
#if WORKAROUND_1298
const char* const WORKAROUND_1298_PREFIX = "org.alljoyn.wa1298.";
#endif

const char* TestConnStr = "ARDP TEST CONNECT REQUEST";
const char* TestAcceptStr = "ARDP TEST ACCEPT";

#ifndef NDEBUG
#if BYTEDUMPS
static void DumpLine(uint8_t* buf, uint32_t len, uint32_t width)
{
    for (uint32_t i = 0; i < width; ++i) {
        if (i > len) {
            printf("   ");
        } else {
            printf("%02x ", buf[i]);
        }
    }
    printf(": ");
    for (uint32_t i = 0; i < len && i < width; ++i) {
        if (iscntrl(buf[i]) || !isascii(buf[i])) {
            printf(".");
        } else {
            printf("%c", buf[i]);
        }
    }
    printf("\n");
}

static void DumpBytes(uint8_t* buf, uint32_t len)
{
    if (_QCC_DbgPrintCheck(DBG_GEN_MESSAGE, QCC_MODULE)) {
        for (uint32_t i = 0; i < len; i += 16) {
            DumpLine(buf + i, len - i > 16 ? 16 : len - i, 16);
        }
    }
}
#endif // BYTEDUMPS
#endif // NDEBUG

#ifndef NDEBUG
/*
 * Quick Debug Print for focused printf debugging outside QCC framework.  Useful
 * if you want to get your bearings but don't want to see the entire debug spew.
 * Use just like QCC_DebugPrintf.
 */
#define QDP(x)        \
    do {              \
        qdtm();       \
        printf x;     \
        printf("\n"); \
    } while (0)

void qdtm(void)
{
    printf("******** %u: ", GetTimestamp());
}

#else
#define QDP(x) do { } while (0)
#endif

#ifndef NDEBUG
#define SEAL_SIZE 4

static void SealBuffer(uint8_t* p)
{
    *p++ = 'S';
    *p++ = 'E';
    *p++ = 'A';
    *p++ = 'L';
}

static void CheckSeal(uint8_t* p)
{
    QCC_ASSERT(*p++ == 'S' && *p++ == 'E' && *p++ == 'A' && *p++ == 'L' && "CheckSeal(): Seal blown");
}
#endif

class ArdpStream;

/*
 * An endpoint class to abstract the notion of an addressible point in the
 * network.  Endpoints are used by the Routing Node to deal with the details of
 * moving bits from here to there.
 */
class _UDPEndpoint : public _RemoteEndpoint {
  public:
    /**
     * The UDP Transport is a flavor of a RemoteEndpoint.  The daemon thinks of
     * remote endpoints as moving through a number of states, some that have
     * threads wandering around and some that do not.  In order to make sure we
     * are in agreement with what the daemon things we will be doing we keep
     * state regarding what threads would be doing if they were actually here
     * and running.  We also keep track of how endpoints were started and how
     * they move through the process from construction to running.
     *
     *
     *                     +----------------+
     *                     | EP_INITIALIZED |
     *                     +----------------+
     *                           |    |
     *                 Connect() |    | AcceptCb()
     *                           |    |
     *               +-----------+    +-----------+
     *               |                            |
     *               v                            v
     *     +-------------------+        +--------------------+
     *     | EP_ACTIVE_STARTED |        | EP_PASSIVE_STARTED |
     *     +-------------------+        +--------------------+
     *               |                            |
     *    Handshake  |                            | Handshake
     *               +-----------+    +-----------+
     *          Daemon Register  |    |  Daemon Register
     *                           v    v
     *                     +----------------+
     *                     |   EP_STARTED   |
     *                     +----------------+
     *                              |
     *                   Shut down  | <----------------------+
     *                              |                        | Idle
     *                              v                        |
     *                     +----------------+          +----------------+
     *                     |   EP_STOPPING  | -------> |   EP_WAITING   |
     *                     +----------------+  local   +----------------+
     *                              |        disconnect
     *                 Thread join  |
     *                              v
     *                     +----------------+
     *                     |   EP_JOINED    |
     *                     +----------------+
     *                              |
     *           Daemon Unregister  |
     *                              v
     *                     +----------------+
     *                     |     EP_DONE    |
     *                     +----------------+
     *
     *
     * When an endoint is constructed, it begins its live in EP_INITIALIZED.
     * endpoints are constructed for the purpose of service passive or active
     * connections.  A passive connection is one that is driven from a connection
     * coming in from a remote host.  An active connection is one that is driven
     * by a local thread calling UDPTransport::Connect().
     *
     * When an inbound connection causes an accept callback to fire, AcceptCb()
     * will create a UDP Endpoint and set the state to EP_PASSIVE_STARTED.
     * These endoints are put on the m_preList for deadlock avoidance and are
     * then quickly moved to the m_authList where they wait for authentication
     * to complete.  When the three-way ARDP handshake completes, as indicated
     * by a DoConnectcb() firing for that connection, the endpoint is removed
     * from the m_authList and put on the running endpoint list.  Since Start()
     * can't be called with locks held (it calls out to the daemon router), it
     * is actually called after the endpoint goes onto the endpoint list,
     * meaning we will see endpoints in state EP_PASSIVE_STARTED for short
     * periods of time on the running endpoints list.
     *
     * When an outbound connection causes a UDP Endpoint to be created the endpoint
     * is set to state EP_ACTIVE_STARTED.  This is done in the DoConnectCB() function
     * that indicates that the three-way handshake has completed.  For the same
     * deadlock-avoidance reason as in the passive case, the endpoint is placed on the
     * running endpoint list and then Start() is called.  This means will will see
     * endpoints on the running endpoint list for transient periods of time in state
     * EP_ACTIVE_STARTED.
     *
     * Once started, it means that the endpoint is connected (registered) to the
     * daemon router and is happily running and capable of pumping messages in and
     * out.
     *
     * As soon as either the local side or the remote side decides that the
     * endpoint has been around long enough, Stop() is called.  This may happen
     * either due to a Disconnect callback in the case of the remote side, or a
     * Stop() called as the result of a LeaveSession on the local side.  It is
     * possible that there are multiple threads running around in the endpoint
     * due to unconsumed remote messages making their way through the router,
     * unsent messages of local origin making their way down to ARDP, or threads
     * trying to PushMessage into the endpoint.  The transition into state
     * EP_STOPPING means the no new operations are allowed on the endpoint and
     * the process of causing all threads to abort and leave the endpoint are
     * started.
     *
     * If the source of the disconnect is a local LeaveSession, we need to
     * simulate socket shutdown behavior.  Specifically, we simulate
     * shutdown(sockfd, SHUT_RDWR) which is what is done in the TCP Transport.
     * In this state, we wait until all buffers sent to ARDP have been disposed
     * of one way or another.  If the other side receives all queued buffers and
     * acknowledges them we have a clean endpoint shutdown.  This additional state
     * is called EP_WAITING and is enabled only if a local (expected) disconnect
     * has been received.
     *
     * After the endpoint is EP_STOPPING and EP_WAITING is not enabled, or if
     * the endpoint is EP_WAITING and queued buffers are fully sent, the
     * endpoint management function notices the situation and then calls Join()
     * to mark the endpoint as being thread-free, buffer-free ande ready to
     * close.  This causes the endpoint to enter the EP_JOINED state.
     *
     * Once an endpoint is in state EP_JOINED, an exit function is scheduled to
     * be run to make sure the endpoint is completely disconnected from the
     * daemon router.  This Exit() function will set the endpoint state to
     * EP_DONE when its job is done.
     *
     * If the endpoint is in state EP_DONE, the endpoint management thread will
     * remove it from the running endpoint list and delete it.
     */
    enum EndpointState {
        EP_ILLEGAL = 0,
        EP_INITIALIZED,      /**< The endpoint structure has been allocated but not used */
        EP_ACTIVE_STARTED,   /**< The endpoint has begun the process of coming up, due to a active connection request */
        EP_PASSIVE_STARTED,  /**< The endpoint has begun the process of coming up, due to a passive connection request */
        EP_STARTED,          /**< The endpoint is ready for use, registered with daemon, maybe threads wandering thorugh */
        EP_STOPPING,         /**< The endpoint is stopping but join has not been called */
        EP_WAITING,          /**< Waiting for ARDP to send any queued data before closing (disconnecting) */
        EP_JOINED,           /**< The endpoint is stopping and join has been called */
        EP_DONE              /**< Threads have been shut down and joined */
    };

#ifndef NDEBUG
    void PrintEpState(const char* prefix)
    {
        switch (m_epState) {
        case EP_INITIALIZED:
            QCC_DbgPrintf(("%s: EP_INITIALIZED", prefix));
            break;

        case EP_ACTIVE_STARTED:
            QCC_DbgPrintf(("%s: EP_ACTIVE_STARTED", prefix));
            break;

        case EP_PASSIVE_STARTED:
            QCC_DbgPrintf(("%s: EP_PASSIVE_STARTED", prefix));
            break;

        case EP_STARTED:
            QCC_DbgPrintf(("%s: EP_STARTED", prefix));
            break;

        case EP_STOPPING:
            QCC_DbgPrintf(("%s: EP_STOPPING", prefix));
            break;

        case EP_WAITING:
            QCC_DbgPrintf(("%s: EP_WAITING", prefix));
            break;

        case EP_JOINED:
            QCC_DbgPrintf(("%s: EP_JOINED", prefix));
            break;

        case EP_DONE:
            QCC_DbgPrintf(("%s: EP_DONE", prefix));
            break;

        default:
            QCC_DbgPrintf(("%s: Bad state", prefix));
            QCC_ASSERT(false && "_Endpoint::PrintEpState(): Bad state");
            break;
        }
    }
#endif

    /**
     * Connections can either be created as a result of incoming or outgoing
     * connection requests.  If a connection happens as a result of a Connect()
     * it is the active side of a connection.  If a connection happens because
     * of an accept of an inbound ARDP SYN it is the passive side of an ARDP
     * connection.  This is important because of reference counting of
     * bus-to-bus endpoints.  The daemon calls Connect() or ARDP calls
     * AcceptCb() to form connections.  The daemon actually never calls
     * disconnect, it removes a final reference to a remote endpoint.  ARDP
     * does, however call a disconnect callback.
     */
    enum SideState {
        SIDE_ILLEGAL = 0,
        SIDE_INITIALIZED,    /**< This endpoint structure has been allocated but don't know if active or passive yet */
        SIDE_ACTIVE,         /**< This endpoint is the active side of a connection */
        SIDE_PASSIVE         /**< This endpoint is the passive side of a connection */
    };

    /**
     * Construct a remote endpoint suitable for the UDP transport.
     */
    _UDPEndpoint(UDPTransport* transport,
                 BusAttachment& bus,
                 bool incoming) :
        _RemoteEndpoint(bus, incoming, NULL, transport->GetTransportName(), false, true),
        m_transport(transport),
        m_stream(NULL),
        m_handle(NULL),
        m_conn(NULL),
        m_id(0),
        m_ipAddr(),
        m_ipPort(0),
        m_registered(false),
        m_sideState(SIDE_INITIALIZED),
        m_epState(EP_INITIALIZED),
        m_tStart(qcc::Timespec<qcc::MonotonicTime>(0)),
        m_tStop(qcc::Timespec<qcc::MonotonicTime>(0)),
        m_tWaitStart(qcc::Timespec<qcc::MonotonicTime>(0)),
        m_tStall(qcc::Timespec<qcc::MonotonicTime>(0)),
        m_remoteExited(false),
        m_exitScheduled(false),
        m_disconnected(false),
        m_refCount(0),
        m_pushCount(0),
        m_stateLock(LOCK_LEVEL_UDPTRANSPORT_UDPENDPOINT_STATELOCK),
        m_wait(true)
    {
        QCC_DbgHLPrintf(("_UDPEndpoint::_UDPEndpoint(transport=%p, bus=%p, incoming=%d.)", transport, &bus, incoming));
    }

    /**
     * Destroy a UDP transport remote endpoint.
     */
    virtual ~_UDPEndpoint();

    /**
     * This is to absolutely, positively ensure that there are no threads
     * wandering around in an endpoint, or are about to start wandering around
     * in an endpoint as it gets destroyed.
     */
    int32_t IncrementRefs()
    {
        return IncrementAndFetch(&m_refCount);
    }

    /**
     * This is to absolutely, positively ensure that there are no threads
     * wandering around in an endpoint, or are about to start wandering around
     * in an endpoint as it gets destroyed.
     */
    int32_t DecrementRefs()
    {
        return DecrementAndFetch(&m_refCount);
    }

    /**
     * Return the number of threads currently exectuting in and under
     * PushMessage().  The endpoint management code cannot make a decision about
     * sending an ARDP disconnect with the PushMessage count nonzero, since even
     * though there are no messages in-flight, PushMessage might continue
     * running and do a send which would be lost if an ARDP disconnect was done
     * before the ARDP_Send actually acknowledged the bits.
     */
    uint32_t GetPushMessageCount()
    {
        return m_pushCount;
    }

    /**
     * Override Start() since we are not going to hook in IOdispatch or start TX and
     * RX threads or anything like that.
     */
    QStatus Start();

    /**
     * Perform the AllJoyn thread lifecycle Stop() operation.  Unlike the
     * standard method, Stop() can be called multiple times in this transport
     * since not all operations are serialized through a single RemoteEndpoint
     * ThreadExit.
     *
     * Override RemoteEndpoint::Stop() since we are not going to unhook
     * IOdispatch or stop TX and RX threads or anything like that.
     */
    QStatus Stop();

    /**
     * Perform the AllJoyn thread lifecycle Join() operation.  Join() can be called
     * multiple times.
     */
    QStatus Join();

    /*
     * Stop() and Join() are relly internal to the UDP Transport threading model.
     * We can consider ourselves free to call Stop() and Join() from everywhere
     * and anywhere just so long as we don't release our reference to the endpoint
     * until after we are sure that the daemon has no more references to the
     * endpoint.
     *
     * The last thing we need to do is to arrange for all references to the
     * endpoint to be removed by calling DaemonRouter::UnregisterEndpoint().
     * Unfortunately, the RemoteEndpoint has the idea of TX and RX threading
     * calling out into streams ingrained into it, so we can't just do this
     * shutdown ourselves.  We really have to call into the RemoteEndpoint().
     * We have an Exit() function there that does what needs to be done in the
     * case of no threads to call an exit callback, but we also have to be very
     * careful about calling it from any old thread context since
     * UnregisterEndoint() will need to take the daemon name table lock, which
     * is often held during call-outs.  To avoid deadlocks, we need to esure
     * that calls to Exit() are done on our dispatcher thread which we know will
     * not be holding any locks.
     */
    QStatus Exit()
    {
        IncrementAndFetch(&m_refCount);
        QCC_DbgHLPrintf(("_UDPEndpoint::Exit()"));

        /*
         * Whenever we change state, we need to protect against multiple threads
         * trying to do something at the same time.  We have to be careful since
         * _RemoteEndpoint can happily call out to the daemon or call back into
         * our endpoint.  Don't take any locks while the possibility exists of
         * the daemon wandering off and doing something.  Whatever it is doing
         * the endpoint management code will hold a reference to the endpoint
         * until Exit() completes so we let the daemon go and grab the locks
         * after it returns.  Note that we do increment the thread reference
         * count that indicates that a thread is wandering around and will pop
         * back up through this function sometime later.
         */

        _RemoteEndpoint::Exit();
        _RemoteEndpoint::Stop();
        m_remoteExited = true;
        m_registered = false;

        m_transport->m_endpointListLock.Lock(MUTEX_CONTEXT);
        m_stateLock.Lock(MUTEX_CONTEXT);

        /*
         * Jump to done state.  Our ManageEndpoints() will pick up on the fact
         * that this endpoint is done and deal with it by releasing any
         * references to it.
         */
        QCC_DbgPrintf(("_UDPEndpoint::Exit(): Going to EP_DONE state"));
        SetEpDone();

        /*
         * Tell the endpoint management code that something has happened that
         * it may be concerned about.
         */
        m_transport->m_manage = UDPTransport::STATE_MANAGE;
        m_transport->Alert();

        m_stateLock.Unlock(MUTEX_CONTEXT);
        m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT);
        DecrementAndFetch(&m_refCount);
        return ER_OK;
    }

    /**
     * Get a pointer to the UDP Transport that owns this Endpoint.
     */
    UDPTransport* GetTransport()
    {
        return m_transport;
    }

    /**
     * Get the boolean indication that the RemoteEndpoint exit function has been
     * called.
     */
    bool GetExited()
    {
        QCC_DbgHLPrintf(("_UDPEndpoint::GetExited(): -> %s", m_remoteExited ? "true" : "false"));
        return m_remoteExited;
    }

    /**
     * Set the boolean indication that the RemoteEndpoint exit function has been
     * scheduled.
     */
    void SetExitScheduled()
    {
        QCC_DbgHLPrintf(("_UDPEndpoint::SetExitScheduled()"));
        m_exitScheduled = true;
    }

    /**
     * Get the boolean indication that the RemoteEndpoint exit function has been
     * scheduled.
     */
    bool GetExitScheduled()
    {
        QCC_DbgHLPrintf(("_UDPEndpoint::GetExitScheduled(): -> %s", m_exitScheduled ? "true" : "false"));
        return m_exitScheduled;
    }

    /**
     * Get a boolean indication that the endpoint has been registered with the
     * daemon.
     */
    bool GetRegistered()
    {
        QCC_DbgHLPrintf(("_UDPEndpoint::GetRegistered(): -> %s", m_registered ? "true" : "false"));
        return m_registered;
    }

    /**
     * Create a skeletal stream that we'll use basically as a place to hold some
     * connection information.
     */
    void CreateStream(ArdpHandle* handle, ArdpConnRecord* conn, uint32_t dataTimeout, uint32_t dataRetries);

    /**
     * Get the ArdpStream* pointer to the skeletal stream associated with this
     * endpoint.
     */
    ArdpStream* GetStream()
    {
        QCC_DbgTrace(("_UDPEndpoint::GetStream() => %p", m_stream));
        return m_stream;
    }

    /**
     * Delete the skeletal stream that we used to stash our connection
     * information.
     */
    void DestroyStream();

    /**
     * Take a Message destined to be send over the connection represented
     * by the UDP Endpoint and ask it to Deliver() itself though this
     * remote endpoint (we are a descendent).  DeliverNonBlocking() will
     * end up calling PushBytes() on the Stream Sink associated with the
     * endpoint.  This will find its way down to the PushBytes() defined
     * in our ARDP Stream.
     *
     * We have a bit of a tricky situation in that AllJoyn likes to send
     * fire-and-forget messages -- signals.  It sometimes wants to make a
     * connection and send a bunch of signals and then disconnect.  We can't
     * just call ARDP_Disconnect with signals queued for transmission which
     * would send RST and tear down the connection before those signals get
     * sent.  Method calls are okay, since the caller needs to wait for the
     * return values, which indicates they were sent (and responded to) but
     * signals are a different beast.  We need to simulate TCP's half-close
     * behavior.  This means our version of a close needs to wait for ARDP to
     * send any queued messages before calling ARDP_Disconnect.
     *
     * A client will use JoinSession to drive the UDPTransport::Connect() that
     * we, in turn, use to drive ARDP_Connect().  When an AllJoyn client is
     * done with a connection it will call LeaveSession().  This will not call
     * a disconnect function, but will cause the associated endpoint to be
     * invalidated and will call UDPEndpoint::Stop().  This call to Stop()
     * begins the endpoint shutdown process, which must disallow any further
     * writes (enforce a SHUTDOWN_WR-like behavior) but keep the underlying
     * connection up until all data has been sent and acknowledged.  At that
     * point, the ARDP_Disconnect() can be called and the endpoint actually
     * torn down.  There is no Shutdown() on an Endpoint that causes it to
     * behave like a TCP state machine, so we get to implement that behavior
     * ourselves.
     *
     * This affects us here in that we have to respect a stopping indication on
     * the UDPEndpoint (as well as the transport).  Since the message passed to
     * us is going to wander down through the endpoint into the stream and then
     * on out ARDP, we have to admit the possibility that even though ARDP may
     * not have heard about a message passing through here, it is in our system.
     * Therefore, we have a counter that indicates how many calls to
     * PushMessage() are in process on this endpoint.  If this counter is
     * nonzero we have to treat this case as if a Message were in flight.  It
     * may turn out that down in the ARDPStream we detect that the endpoint is
     * closing, but we need to include coverage for the in-process case here.
     *
     * The Endpoint Management thread is what processes the closing of
     * connections and the disposition of endpoints, so it will have to wait
     * until the in-flight message count goes to zero and also the
     * PushMessage()s in-process goes to zero before executing a
     * ARDP_Disconnect().
     */
    QStatus PushMessage(Message& msg)
    {
        /*
         * Increment the counter indicating that another thread is running
         * inside PushMessage for the current endpoint.  THis is different from
         * the counter indicating "something is executing inside the endpoint"
         * bumped below.
         */
        IncrementAndFetch(&m_pushCount);

        IncrementAndFetch(&m_refCount);
        QCC_DbgTrace(("_UDPEndpoint::PushMessage(msg=%p)", &msg));

        /*
         * If either the transport or the endpoint is not in a state where it
         * indicates that it is ready to send, we need to return an error.
         *
         * Unfortunately, the system will try to do all kinds of things to an
         * endpoint even though it has just stopped it.  To prevent cascades of
         * error logs, we need to return a "magic" error code and not log an
         * error if we detect that either the transport or the endpoint is
         * shutting down.  Higher level code (especially AllJoynObj) will look
         * for this error and not do any logging if it is a transient error
         * during shutdown, as identified by the error return value
         * ER_BUS_ENDPOINT_CLOSING.
         */
        if (m_transport->IsRunning() == false || m_transport->m_stopping == true) {
            QStatus status = ER_BUS_ENDPOINT_CLOSING;
            DecrementAndFetch(&m_refCount);
            DecrementAndFetch(&m_pushCount);
            return status;
        }

        if (IsEpStarted() == false) {
            QStatus status = ER_BUS_ENDPOINT_CLOSING;
            DecrementAndFetch(&m_refCount);
            DecrementAndFetch(&m_pushCount);
            return status;
        }

        /*
         * We need to make sure that this endpoint stays on one of our endpoint
         * lists while we figure out what to do with it.  If we are taken off
         * the endpoint list we could actually be deleted while doing this
         * operation, so take the lock to make sure at least the UDP transport
         * holds a reference during this process.
         */
        m_transport->m_endpointListLock.Lock(MUTEX_CONTEXT);

        /*
         * Find the managed endpoint to which the connection ID of the current
         * object refers.  If the endpoint state was EP_STARTED above, and we
         * hold the endpoint lock, we should find the endpoint on the list.
         */
        uint32_t found = 0;
        for (set<UDPEndpoint>::iterator i = m_transport->m_endpointList.begin(); i != m_transport->m_endpointList.end(); ++i) {
            UDPEndpoint ep = *i;
            if (GetConnId() == ep->GetConnId()) {
                QCC_DbgPrintf(("_UDPEndpoint::PushMessage(): found endpoint with conn ID == %d. on m_endpointList", GetConnId()));
                ++found;
            }
        }

        if (found == 0) {
            QCC_LogError(ER_UDP_ENDPOINT_REMOVED, ("_UDPEndpoint::PushMessage(): Endpoint is gone"));
            m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT);
            DecrementAndFetch(&m_refCount);
            DecrementAndFetch(&m_pushCount);
            return ER_UDP_ENDPOINT_REMOVED;
        }

        /*
         * Since we know an instance of this object is on our endpoint list,
         * we'll get a reference to a valid object here.
         */
        RemoteEndpoint rep = RemoteEndpoint::wrap(this);

        /*
         * If we are going to pass the Message off to be delivered, the act of
         * delivering will change the write state of the message.  Since
         * delivering to a multipoint session is done by taking a Message and
         * sending it off to multiple endpoints for delivery, if we just use the
         * Message we are given, we will eventually change the writeState of the
         * message to MESSAGE_COMPLETE when we've pushed all of the bits.  That
         * would cause any subsequent PushMessage calls to complete before
         * actually writing any bits since they would think they are done.  This
         * means we have to do a deep copy of every message before we send it.
         */
        Message msgCopy = Message(msg, true);

        /*
         * We know we hold a reference, so now we can call out to the daemon
         * with it.  Even if we release the endpoint list lock, our thread will
         * be registered in the endpoint so it won't go away.  The message
         * handler should call right back into our stream and we should pop back
         * out in short order.
         */
        m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT);
        QCC_DbgPrintf(("_UDPEndpoint::PushMessage(): DeliverNonBlocking()"));
        QStatus status = msgCopy->DeliverNonBlocking(rep);
        QCC_DbgPrintf(("_UDPEndpoint::PushMessage(): DeliverNonBlocking() returns \"%s\"", QCC_StatusText(status)));
        DecrementAndFetch(&m_refCount);
        DecrementAndFetch(&m_pushCount);
        return status;
    }

    /**
     * Callback letting us know that our connection has been disconnected for
     * some reason.
     *
     * For deadlock avoidance purposes, this callback always comes from the
     * transport dispatcher thread.
     *
     * It is important to realize that this callback is not called in the
     * context of the ARDP thread, it is dispatched from that callback on
     * another thread.  Therefore it is possible that during the dispatch time,
     * the connection may have beome invalid.  In order to remove ourselves from
     * this possibility, we plumb through the connection ID that was given to us
     * in the original callback.  Since the dispatcher used that ID to look us
     * up via our saved connection ID they should be the same and we can treat
     * this as a unique identifier for the purposes of aligning, looking up and
     * releasing resources even if the underlying connection that corresponded
     * to this ID may have dropped out from under us.
     */
    void DisconnectCb(ArdpHandle* handle, ArdpConnRecord* conn, uint32_t connId, QStatus status);

    /**
     * Callback letting us know that we received data over our connection.  We
     * are passed responsibility for the buffer in this callback.
     *
     * For deadlock avoidance purposes, this callback always comes from the
     * transport dispatcher thread.
     *
     * It is important to realize that this callback is not called in the
     * context of the ARDP thread, it is dispatched from that callback on
     * another thread.  Therefore it is possible that during the dispatch time,
     * the connection may have beome invalid.  In order to remove ourselves from
     * this possibility, we plumb through the connection ID that was given to us
     * in the original callback.  Since the dispatcher used that ID to look us
     * up via our saved connection ID they should be the same and we can treat
     * this as a unique identifier for the purposes of aligning, looking up and
     * releasing resources even if the underlying connection that corresponded
     * to this ID may have dropped out from under us.
     */
    void RecvCb(ArdpHandle* handle, ArdpConnRecord* conn, uint32_t connId, ArdpRcvBuf* rcv, QStatus status)
    {
        QCC_UNUSED(connId);

        IncrementAndFetch(&m_refCount);
        QCC_DbgHLPrintf(("_UDPEndpoint::RecvCb(handle=%p, conn=%p, connId=%d., rcv=%p, status=%s)",
                         handle, conn, connId, rcv, QCC_StatusText(status)));

        /*
         * We need to look and see if this endpoint is on the endopint list and
         * then make sure that it stays on the list, so take the lock to make
         * sure at least the UDP transport holds a reference during this
         * process.
         */
        m_transport->m_endpointListLock.Lock(MUTEX_CONTEXT);

        /*
         * The callback dispatcher looked to see if the endpoint was on the
         * endpoint list before it made the call here, and it incremented the
         * thread reference count before calling.  We should find an endpoint
         * still on the endpoint list since the management thread should not
         * remove the endpoint with threads wandering around in it.
         */
        uint32_t found = 0;
        for (set<UDPEndpoint>::iterator i = m_transport->m_endpointList.begin(); i != m_transport->m_endpointList.end(); ++i) {
            UDPEndpoint ep = *i;
            if (GetConnId() == ep->GetConnId()) {
                QCC_ASSERT(connId == GetConnId() && "_UDPEndpoint::RecvCb(): Inconsistent connId");
                QCC_DbgPrintf(("_UDPEndpoint::RecvCb(): found endpoint with conn ID == %d. on m_endpointList", GetConnId()));
                ++found;
            }
        }

        if (found == 0) {
            QCC_DbgPrintf(("_UDPEndpoint::RecvCb(): Endpoint is gone"));
            m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT);
            return;
        }

        if (IsEpStarted() == false) {
            QCC_DbgPrintf(("_UDPEndpoint::RecvCb(): Not accepting inbound messages"));

            QCC_DbgPrintf(("_UDPEndpoint::RecvCb(): ARDP_RecvReady()"));
            m_transport->m_ardpLock.Lock(MUTEX_CONTEXT);

            /*
             * We got a receive callback that includes data destined for an
             * endpoint that is no longer accepting messages.  Most likely it is
             * shutting down.  The details of shutting down the endpoint and
             * discussing those details with ARDP is handled elsewhere, so all
             * we need to do is to return the buffer that we are ingoring.
             *
             * We're in a receive callback, but the callback function is
             * dispatched on another thread that is unrelated to the thread on
             * which the original ARDP callback was fired.  This is important
             * since if we are in the ARDP callback thread the conn is
             * guaranteed to be valid since the function is beign called from
             * ARDP.  In a thread that may be dispatched later this is no longer
             * the case.  The conn may have been torn down between the time the
             * original callback was fired and when the dipatcher has actually
             * run.  If this is the case, we can only trust that ARDP has done
             * the right thing and cleaned up its buffers.  ARDP owns the
             * disposition of the buffers and we did our best -- we called back.
             * If an error is returned, pretty much all we can do is just log or
             * print an error message.  Since we aren't in charge at all, we
             * just print a message if in debug mode.
             */
#ifndef NDEBUG
            QStatus alternateStatus =
#endif
            ARDP_RecvReady(handle, conn, rcv);
#ifndef NDEBUG
            if (alternateStatus != ER_OK) {
                QCC_DbgPrintf(("_UDPEndpoint::RecvCb(): ARDP_RecvReady() returns status==\"%s\"", QCC_StatusText(status)));
            }
#endif
            m_transport->m_ardpLock.Unlock(MUTEX_CONTEXT);

            m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT);
            DecrementAndFetch(&m_refCount);
            return;
        }

        /*
         * Our contract with ARDP says that it will provide us with valid data
         * if it calls us back.
         */
        QCC_ASSERT(rcv != NULL && rcv->data != NULL && rcv->datalen != 0 && "_UDPEndpoint::RecvCb(): No data from ARDP in RecvCb()");

        if (rcv->fcnt == 0) {
            QCC_LogError(ER_UDP_INVALID, ("_UDPEndpoint::RecvCb(): Unexpected rcv->fcnt==%d.", rcv->fcnt));

            QCC_DbgPrintf(("_UDPEndpoint::RecvCb(): ARDP_RecvReady()"));
            m_transport->m_ardpLock.Lock(MUTEX_CONTEXT);
            /*
             * We got a bogus fragment count and so we will assert this is a
             * bogus condition below.  Don't bother printing an error if ARDP
             * also doesn't take the bogus buffers back.
             */
            ARDP_RecvReady(handle, conn, rcv);
            m_transport->m_ardpLock.Unlock(MUTEX_CONTEXT);
            m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT);

            DecrementAndFetch(&m_refCount);
            QCC_ASSERT(false && "_UDPEndpoint::RecvCb(): unexpected rcv->fcnt");
            return;
        }

        /*
         * The daemon knows nothing about message fragments, so we must
         * reassemble the fragements into a contiguous buffer before doling it
         * out to the daemon router.  What we get is a singly linked list of
         * ArdpRcvBuf* that we have to walk.  There is no cumulative length, so
         * we have to do two passes through the list: one pass to calculate the
         * length so we can allocate a contiguous buffer, and one to copy the
         * data into the buffer.
         */
        uint8_t* msgbuf = NULL;
        uint32_t mlen = 0;
        if (rcv->fcnt != 1) {
            QCC_DbgPrintf(("_UDPEndpoint::RecvCb(): Calculating message length"));
            ArdpRcvBuf* tmp = rcv;
            for (uint32_t i = 0; i < rcv->fcnt; ++i) {
                QCC_DbgPrintf(("_UDPEndpoint::RecvCb(): Found fragment of %d. bytes", tmp->datalen));

                if (tmp->datalen == 0 || tmp->datalen > 65535) {
                    QCC_LogError(ER_UDP_INVALID, ("_UDPEndpoint::RecvCb(): Unexpected tmp->datalen==%d.", tmp->datalen));
                    m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT);

                    QCC_DbgPrintf(("_UDPEndpoint::RecvCb(): ARDP_RecvReady()"));
                    m_transport->m_ardpLock.Lock(MUTEX_CONTEXT);
                    /*
                     * We got a bogus fragment count and so we will assert this
                     * is a bogus condition below.  Don't bother printing an
                     * error if ARDP also doesn't take the bogus buffers back.
                     */
                    ARDP_RecvReady(handle, conn, rcv);
                    m_transport->m_ardpLock.Unlock(MUTEX_CONTEXT);

                    DecrementAndFetch(&m_refCount);
                    QCC_ASSERT(false && "_UDPEndpoint::RecvCb(): unexpected rcv->fcnt");
                    return;
                }

                mlen += tmp->datalen;
                tmp = tmp->next;
            }

            QCC_DbgPrintf(("_UDPEndpoint::RecvCb(): Found Message of %d. bytes", mlen));
#ifndef NDEBUG
            msgbuf  = new uint8_t[mlen + SEAL_SIZE];
            SealBuffer(msgbuf + mlen);
#else
            msgbuf = new uint8_t[mlen];
#endif
            uint32_t offset = 0;
            tmp = rcv;
            QCC_DbgPrintf(("_UDPEndpoint::RecvCb(): Reassembling fragements"));
            for (uint32_t i = 0; i < rcv->fcnt; ++i) {
                QCC_DbgPrintf(("_UDPEndpoint::RecvCb(): Copying fragment of %d. bytes", tmp->datalen));
                memcpy(msgbuf + offset, tmp->data, tmp->datalen);
                offset += tmp->datalen;
                tmp = tmp->next;
            }

            QCC_DbgPrintf(("_UDPEndpoint::RecvCb(): Message of %d. bytes reassembled", mlen));
        }

        uint8_t* messageBuf = msgbuf ? msgbuf : rcv->data;
        uint32_t messageLen = mlen ? mlen : rcv->datalen;

#ifndef NDEBUG
#if BYTEDUMPS
        DumpBytes(messageBuf, messageLen);
#endif
#endif

        /*
         * Since we know the callback dispatcher verified it could find an
         * intance of this object is on an endpoint lists, and it bumped the
         * thread reference count, we know we'll get a reference to a
         * still-valid object here.
         */
        RemoteEndpoint rep = RemoteEndpoint::wrap(this);
        BusEndpoint bep  = BusEndpoint::cast(rep);

        /*
         * We know we hold a reference that will stay alive until we leave this
         * function, so now we can call out to the daemon all we want.
         */
        m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT);

        /*
         * The point here is to create an AllJoyn Message from the
         * inbound bytes which we know a priori to contain exactly one
         * Message if present.  We have a back door in the Message code
         * that lets us load our bytes directly into the message.  Note
         * that this LoadBytes does a buffer copy, so we are free to
         * release ownership of the incoming buffer at any time after
         * that.
         */
        Message msg(m_transport->m_bus);
        QCC_DbgPrintf(("_UDPEndpoint::RecvCb(): LoadBytes()"));
        status = msg->LoadBytes(messageBuf, messageLen);
        if (status != ER_OK) {
            QCC_LogError(status, ("_UDPEndpoint::RecvCb(): Cannot load bytes"));

            /*
             * If there's some kind of problem, we have to give the buffer
             * back to the protocol now.
             */
            m_transport->m_ardpLock.Lock(MUTEX_CONTEXT);

#ifndef NDEBUG
            QStatus alternateStatus =
#endif
            ARDP_RecvReady(handle, conn, rcv);
#ifndef NDEBUG
            if (alternateStatus != ER_OK) {
                QCC_DbgPrintf(("_UDPEndpoint::RecvCb(): ARDP_RecvReady() returns status==\"%s\"", QCC_StatusText(alternateStatus)));
            }
#endif
            m_transport->m_ardpLock.Unlock(MUTEX_CONTEXT);

            /*
             * If we allocated a reassembly buffer, free it too.
             */
            if (msgbuf) {
#ifndef NDEBUG
                CheckSeal(msgbuf + mlen);
#endif
                delete[] msgbuf;
                msgbuf = NULL;
            }

            /*
             * If we do something that is going to bug the ARDP protocol, we
             * need to call back into ARDP ASAP to get it moving.  This is done
             * in the main thread, which we need to wake up.
             */
            m_transport->Alert();
            DecrementAndFetch(&m_refCount);
            return;
        }

        /*
         * The bytes are now loaded into what amounts to a backing buffer for
         * the Message.  With the exception of the Message header, these are
         * still the raw bytes from the wire, so we have to Unmarshal() them
         * before proceeding (remembering to free the reassembly buffer if it
         * exists.
         */
        if (msgbuf) {
#ifndef NDEBUG
            CheckSeal(msgbuf + mlen);
#endif
            delete[] msgbuf;
            msgbuf = NULL;
        }

        qcc::String endpointName(rep->GetUniqueName());
        QCC_DbgPrintf(("_UDPEndpoint::RecvCb(): Unmarshal()"));
        status = msg->Unmarshal(endpointName, false, false, true, 0);
        if (status != ER_OK) {
            QCC_DbgPrintf(("_UDPEndpoint::RecvCb(): Can't Unmarhsal() Message.  Probably duplicate signal delivery"));

            /*
             * If there's some kind of problem, we have to give the buffer
             * back to the protocol now.
             */
            m_transport->m_ardpLock.Lock(MUTEX_CONTEXT);

#ifndef NDEBUG
            QStatus alternateStatus =
#endif
            ARDP_RecvReady(handle, conn, rcv);
#ifndef NDEBUG
            if (alternateStatus != ER_OK) {
                QCC_DbgPrintf(("_UDPEndpoint::RecvCb(): ARDP_RecvReady() returns status==\"%s\"", QCC_StatusText(alternateStatus)));
            }
#endif

            m_transport->m_ardpLock.Unlock(MUTEX_CONTEXT);

            /*
             * If we do something that is going to bug the ARDP protocol, we
             * need to call back into ARDP ASAP to get it moving.  This is done
             * in the main thread, which we need to wake up.
             */
            m_transport->Alert();
            DecrementAndFetch(&m_refCount);
            return;
        }

        QCC_DbgPrintf(("_UDPEndpoint::RecvCb(): PushMessage()"));
        status = m_transport->m_bus.GetInternal().GetRouter().PushMessage(msg, bep);
        if (status != ER_OK) {
            QCC_LogError(status, ("_UDPEndpoint::RecvCb(): PushMessage failed"));
        }

        /*
         * We're all done with the message we got from ARDP, so we need to let
         * it know that it can reuse the buffer (and open its receive window).
         */
        QCC_DbgPrintf(("_UDPEndpoint::RecvCb(): ARDP_RecvReady()"));
        m_transport->m_ardpLock.Lock(MUTEX_CONTEXT);

#ifndef NDEBUG
        QStatus alternateStatus =
#endif
        ARDP_RecvReady(handle, conn, rcv);
#ifndef NDEBUG
        if (alternateStatus != ER_OK) {
            QCC_DbgPrintf(("_UDPEndpoint::RecvCb(): ARDP_RecvReady() returns status==\"%s\"", QCC_StatusText(alternateStatus)));
        }
#endif
        m_transport->m_ardpLock.Unlock(MUTEX_CONTEXT);

        /*
         * If we do something that is going to bug the ARDP protocol, we need to
         * call back into ARDP ASAP to get it moving.  This is done in the main
         * thread, which we need to wake up.
         */
        m_transport->Alert();
        DecrementAndFetch(&m_refCount);
    }

    /**
     * Callback letting us know that the remote side has acknowledged reception
     * of our data and the buffer can be recycled/freed
     *
     * For deadlock avoidance purposes, this callback always comes from the
     * transport dispatcher thread.
     *
     * It is important to realize that this callback is not called in the
     * context of the ARDP thread, it is dispatched from that callback on
     * another thread.  Therefore it is possible that during the dispatch time,
     * the connection may have beome invalid.  In order to remove ourselves from
     * this possibility, we plumb through the connection ID that was given to us
     * in the original callback.  Since the dispatcher used that ID to look us
     * up via our saved connection ID they should be the same and we can treat
     * this as a unique identifier for the purposes of aligning, looking up and
     * releasing resources even if the underlying connection that corresponded
     * to this ID may have dropped out from under us.
     */
    void SendCb(ArdpHandle* handle, ArdpConnRecord* conn, uint32_t connId, uint8_t* buf, uint32_t len, QStatus status);

    /**
     * Get the handle to the underlying ARDP protocol implementation.
     */
    ArdpHandle* GetHandle()
    {
        QCC_DbgTrace(("_UDPEndpoint::GetHandle() => %p", m_handle));
        return m_handle;
    }

    /**
     * Set the handle to the underlying ARDP protocol implementation.
     */
    void SetHandle(ArdpHandle* handle)
    {
        QCC_DbgTrace(("_UDPEndpoint::SetHandle(handle=%p)", handle));
        m_handle = handle;
    }

    /**
     * Get the pointer to the underlying ARDP protocol connection information.
     */
    ArdpConnRecord* GetConn()
    {
        QCC_DbgTrace(("_UDPEndpoint::GetConn(): => %p", m_conn));
        return m_conn;
    }

    /**
     * Set the pointer to the underlying ARDP protocol connection information.
     */
    void SetConn(ArdpConnRecord* conn)
    {
        QCC_DbgTrace(("_UDPEndpoint::SetConn(conn=%p)", conn));
        m_conn = conn;
        m_transport->m_ardpLock.Lock(MUTEX_CONTEXT);
        uint32_t cid = ARDP_GetConnId(m_handle, conn);

#ifndef NDEBUG
        if (cid == ARDP_CONN_ID_INVALID) {
            QCC_DbgPrintf(("_UDPEndpoint::SetConn(conn=%p): conn is invalid!", conn));
        }
#endif

        SetConnId(cid);
        m_transport->m_ardpLock.Unlock(MUTEX_CONTEXT);
    }

    /**
     * Get the connection ID of the original ARDP protocol connection.  We keep
     * this around for debugging purposes after the connection goes away.
     */
    uint32_t GetConnId()
    {
//      QCC_DbgTrace(("_UDPEndpoint::GetConnId(): => %d.", m_id));
        return m_id;
    }

    /**
     * Set the connection ID of the original ARDP protocol connection.  We keep
     * this around for debugging purposes after the connection goes away.
     */
    void SetConnId(uint32_t id)
    {
        QCC_DbgTrace(("_UDPEndpoint::SetConnId(id=%d.)", id));
        m_id = id;
    }

    /**
     * Get the IP address of the remote side of the connection.
     */
    qcc::IPAddress GetIpAddr()
    {
        QCC_DbgTrace(("_UDPEndpoint::GetIpAddr(): => \"%s\"", m_ipAddr.ToString().c_str()));
        return m_ipAddr;
    }

    /**
     * Set the IP address of the remote side of the connection.
     */
    void SetIpAddr(qcc::IPAddress& ipAddr)
    {
        QCC_DbgTrace(("_UDPEndpoint::SetIpAddr(ipAddr=\"%s\")", ipAddr.ToString().c_str()));
        m_ipAddr = ipAddr;
    }

    /**
     * Get the UDP/IP port of the remote side of the connection.
     */
    uint16_t GetIpPort()
    {
        QCC_DbgTrace(("_UDPEndpoint::GetIpPort(): => %d.", m_ipPort));
        return m_ipPort;
    }

    /**
     * Set the UDP/IP port of the remote side of the connection.
     */
    void SetIpPort(uint16_t ipPort)
    {
        QCC_DbgTrace(("_UDPEndpoint::SetIpPort(ipPort=%d.)", ipPort));
        m_ipPort = ipPort;
    }

    /**
     * Get the IP address of the local side of the connection.
     */
    QStatus GetLocalIp(qcc::String& ipAddrStr)
    {
        QCC_UNUSED(ipAddrStr);
        QCC_DbgTrace(("_UDPEndpoint::GetLocalIp(ipAddrStr=%0)", &ipAddrStr));

        /*
         * We are only sure about the endpoint's underlying address when it is
         * running.  It may be the case that the endpoint completes the process
         * of getting torn down between our test and the call ot get the address
         * from ARDP, but the worst thing that can happen is that we return
         * ER_OK but the IPAddress string returned is empty.
         */
        if (IsEpStarted() == false) {
            return ER_UDP_ENDPOINT_NOT_STARTED;
        }

        m_transport->m_ardpLock.Lock(MUTEX_CONTEXT);

        IPEndpoint endpoint;
        QStatus status = ARDP_GetLocalIPEndpointFromConn(GetHandle(), GetConn(), endpoint);
        if (status == ER_OK) {
            ipAddrStr = endpoint.addr.ToString();
        }

        m_transport->m_ardpLock.Unlock(MUTEX_CONTEXT);
        return status;
    };

    /**
     * Get the IP address of the remote side of the connection.
     */
    QStatus GetRemoteIp(qcc::String& ipAddrStr)
    {
        QCC_DbgTrace(("_UDPEndpoint::GetRemoteIp(ipAddrStr=%p): => \"%s\"", &ipAddrStr, m_ipAddr.ToString().c_str()));
        ipAddrStr = m_ipAddr.ToString();
        return ER_OK;
    };

    /**
     * Set the time at which authentication was started.
     */
    void SetStartTime(qcc::Timespec<qcc::MonotonicTime> tStart)
    {
        QCC_DbgTrace(("_UDPEndpoint::SetStartTime()"));
        m_tStart = tStart;
    }

    /**
     * Get the time at which authentication was started.
     */
    qcc::Timespec<qcc::MonotonicTime> GetStartTime(void)
    {
        QCC_DbgTrace(("_UDPEndpoint::GetStartTime(): => %" PRIu64 ".%03d.", m_tStart.seconds, m_tStart.mseconds));
        return m_tStart;
    }

    /**
     * Set the time at which the stop process for the endpoint was begun.
     */
    void SetStopTime(qcc::Timespec<qcc::MonotonicTime> tStop)
    {
        QCC_DbgTrace(("_UDPEndpoint::SetStopTime()"));
        m_tStop = tStop;
    }

    /**
     * Get the time at which the stop process for the endpoint was begun.
     */
    qcc::Timespec<qcc::MonotonicTime> GetStopTime(void)
    {
        QCC_DbgTrace(("_UDPEndpoint::GetStopTime(): => %" PRIu64 ".%03d.", m_tStop.seconds, m_tStop.mseconds));
        return m_tStop;
    }

    /**
     * Set the time at which the shutdown (EP_WAITING) process for the endpoint
     * was begun.
     */
    void SetWaitStartTime(qcc::Timespec<qcc::MonotonicTime> tWaitStart)
    {
        QCC_DbgTrace(("_UDPEndpoint::SetWaitStartTime()"));
        m_tWaitStart = tWaitStart;
    }

    /**
     * Get the time at which the shutdown (EP_WAITING) process for the endpoint
     * was begun.
     */
    qcc::Timespec<qcc::MonotonicTime> GetWaitStartTime(void)
    {
        QCC_DbgTrace(("_UDPEndpoint::GetWaitStartTime(): => %" PRIu64 ".%03d.", m_tWaitStart.seconds, m_tWaitStart.mseconds));
        return m_tWaitStart;
    }

    /**
     * Set the time at which the last stall warning was emitted.
     */
    void SetStallTime(qcc::Timespec<qcc::MonotonicTime> tStall)
    {
        QCC_DbgTrace(("_UDPEndpoint::SetStallTime()"));
        m_tStall = tStall;
    }

    /**
     * Get the time at which the lst stall warning was emitted.
     */
    qcc::Timespec<qcc::MonotonicTime> GetStallTime(void)
    {
        QCC_DbgTrace(("_UDPEndpoint::GetStallTime(): => %" PRIu64 ".%03d.", m_tStall.seconds, m_tStall.mseconds));
        return m_tStall;
    }

    /**
     * Which side of a connection are we -- active or passive
     */
    SideState GetSideState(void)
    {
        QCC_DbgTrace(("_UDPEndpoint::GetSideState(): => %d.", m_sideState));
        return m_sideState;
    }

    /**
     * Note that we are the active side of a connection
     */
    void SetActive(void)
    {
        QCC_DbgTrace(("_UDPEndpoint::SetActive()"));
        m_sideState = SIDE_ACTIVE;
    }

    /**
     * Note that we are the passive side of a connection
     */
    void SetPassive(void)
    {
        QCC_DbgTrace(("_UDPEndpoint::SetPassive()"));
        m_sideState = SIDE_PASSIVE;
    }

    /**
     * Get the state of the overall endpoint.  Failed, starting, stopping, etc.
     */
    EndpointState GetEpState(void)
    {
        QCC_DbgTrace(("_UDPEndpoint::GetEpState(): => %d.", m_epState));
        return m_epState;
    }

    /**
     * Check the state of the endpoint for initialized
     */
    bool IsEpInitialized(void)
    {
        QCC_DbgTrace(("_UDPEndpoint::IsEpInitialized() <= \"%s\"", m_epState == EP_INITIALIZED ? "true" : "false"));
        return m_epState == EP_INITIALIZED;
    }

    /**
     * Set the state of the endpoint to active started
     */
    void SetEpActiveStarted(void)
    {
        QCC_DbgTrace(("_UDPEndpoint::SetEpActiveStarted()"));
        QCC_ASSERT(m_epState == EP_INITIALIZED);
        m_epState = EP_ACTIVE_STARTED;
    }

    /**
     * Check the state of the endpoint for active started
     */
    bool IsEpActiveStarted(void)
    {
        QCC_DbgTrace(("_UDPEndpoint::IsEpActiveStarted() <= \"%s\"", m_epState == EP_ACTIVE_STARTED ? "true" : "false"));
        return m_epState == EP_ACTIVE_STARTED;
    }

    /**
     * Set the state of the endpoint to passive started
     */
    void SetEpPassiveStarted(void)
    {
        QCC_DbgTrace(("_UDPEndpoint::SetEpPassiveStarted()"));
        QCC_ASSERT(m_epState == EP_INITIALIZED);
        m_epState = EP_PASSIVE_STARTED;
    }

    /**
     * Check the state of the endpoint for passive started
     */
    bool IsEpPassiveStarted(void)
    {
        QCC_DbgTrace(("_UDPEndpoint::IsEpPassiveStarted() <= \"%s\"", m_epState == EP_PASSIVE_STARTED ? "true" : "false"));
        return m_epState == EP_PASSIVE_STARTED;
    }

    /**
     * Set the state of the endpoint to started
     */
    void SetEpStarted(void)
    {
        QCC_DbgTrace(("_UDPEndpoint::SetEpStarted()"));
        QCC_ASSERT(m_epState == EP_ACTIVE_STARTED || m_epState == EP_PASSIVE_STARTED);
        m_epState = EP_STARTED;
    }

    /**
     * Check the state of the endpoint for started
     */
    bool IsEpStarted(void)
    {
        QCC_DbgTrace(("_UDPEndpoint::IsEpStarted() <= \"%s\"", m_epState == EP_STARTED ? "true" : "false"));
        return m_epState == EP_STARTED;
    }


    /**
     * Enable the optional EP_WAITING state
     */
    void SetEpWaitEnable(bool wait)
    {
        QCC_DbgTrace(("_UDPEndpoint::SetEpWaitEnable(wait=\"%s\")", wait ? "true" : "false"));
        m_wait = wait;
    }

    /**
     * Check to see if the EP_WAITING state is enabled
     */
    bool IsEpWaitEnabled(void)
    {
        QCC_DbgTrace(("_UDPEndpoint::IsEpWaitEnabled() <= \"%s\"", m_wait ? "true" : "false"));
        return m_wait;
    }

    /**
     * Set the state of the endpoint to stopping.
     *
     * If wait is true, the endpoint is stopping because of a local disconnect
     * and the EP_WAITING state should follow EP_STOPPING to wait for the ARDP
     * write queue to empty before disconnecting.
     */
    void SetEpStopping()
    {
        QCC_DbgTrace(("_UDPEndpoint::SetEpStopping()"));

#ifndef NDEBUG
        PrintEpState("_UdpEndpoint::SetEpStopping()");
#endif

        /*
         * Don't allow backward progress.
         */
        QCC_ASSERT(m_epState != EP_JOINED || m_epState == EP_DONE);

        Timespec<MonotonicTime> tNow;
        GetTimeNow(&tNow);
        SetStopTime(tNow);
        SetStallTime(tNow);

        m_epState = EP_STOPPING;
    }

    /**
     * Check the state of the endpoint for stopping
     */
    bool IsEpStopping(void)
    {
        QCC_DbgTrace(("_UDPEndpoint::IsEpStopping() <= \"%s\"", m_epState == EP_STOPPING ? "true" : "false"));
        return m_epState == EP_STOPPING;
    }

    /**
     * Set the state of the endpoint to waiting
     */
    void SetEpWaiting(void)
    {
        QCC_DbgTrace(("_UDPEndpoint::SetEpWaiting()"));
        QCC_ASSERT(m_epState == EP_STOPPING);
        m_epState = EP_WAITING;
    }

    /**
     * Check the state of the endpoint for stopping
     */
    bool IsEpWaiting(void)
    {
        QCC_DbgTrace(("_UDPEndpoint::IsEpWaiting() <= \"%s\"", m_epState == EP_WAITING ? "true" : "false"));
        return m_epState == EP_WAITING;
    }

    /**
     * Set the state of the endpoint to joined
     */
    void SetEpJoined(void)
    {
        QCC_DbgTrace(("_UDPEndpoint::SetEpJoined()"));

        /*
         * It is illegal to set Join()ed directly from a started state without calling Stop() first.
         */
        QCC_ASSERT(m_epState != EP_STARTED);

        /*
         * Don't allow backward progress.
         */
        QCC_ASSERT(m_epState != EP_DONE);

        m_epState = EP_JOINED;
    }

    /**
     * Check the state of the endpoint for joined
     */
    bool IsEpJoined(void)
    {
        QCC_DbgTrace(("_UDPEndpoint::IsEpJoined() <= \"%s\"", m_epState == EP_JOINED ? "true" : "false"));
        return m_epState == EP_JOINED;
    }

    /**
     * Set the state of the endpoint to done
     */
    void SetEpDone(void)
    {
        QCC_DbgTrace(("_UDPEndpoint::SetEpDone()"));
        QCC_ASSERT(m_epState == EP_JOINED);
        m_epState = EP_DONE;
    }

    /**
     * Check the state of the endpoint for doneness
     */
    bool IsEpDone(void)
    {
        QCC_DbgTrace(("_UDPEndpoint::IsEpDone() <= \"%s\"", m_epState == EP_DONE ? "true" : "false"));
        return m_epState == EP_DONE;
    }

    /**
     * Set the disconnect status in the underlying BusEndpoint.  This is
     * provided in order to let the endpoint management code set the protected
     * status if it needs to.
     */
    void SetEpDisconnectStatus(QStatus status)
    {
        QCC_DbgTrace(("_UDPEndpoint::SetEpDisconnectStatus(status=%s)", QCC_StatusText(status)));

        /*
         * If something has previously gone wrong, leave it be.  Especially
         * don't overwrite bad status with good.
         */
        QStatus oldStatus = GetDisconnectStatus();
        if (oldStatus != ER_OK) {
            QCC_DbgTrace(("_UDPEndpoint::SetEpDisconnectStatus(): Previously set status.  Ignoring new"));
            return;
        }

        /*
         * This status is going to eventually percolate up to AllJoynObj which
         * translates it into its own version of status.  It looks for specific
         * values, so we have to be careful that we don't surprise it.
         *
         * There are three values that AllJoynObj will be looking for that
         * originate at the transport level:
         *
         *     ER_SOCK_OTHER_END_CLOSED: This is a very TCP-specific error that
         *         means the stream socket on the other side of the L4 link
         *         was closed.  There is no socket that was closed, but as it
         *         stands uers expect to see the specific session error called
         *         ALLJOYN_SESSIONLOST_REMOTE_END_CLOSED_ABRUPTLY on a control-C
         *         of the remote side.  AllJoynObj requires the specific socket
         *         error ER_SOCK_OTHER_END_CLOSED for this to happpen.  So, even
         *         though there is no socket being closed, we map all of our
         *         specific ARDP errors to this value, which effectively means
         *         link lost despite its name.
         *
         *     ER_TIMEOUT: This means a link timeout was detected.  ARDP has
         *         two separate timeouts (persist timeout corresponds to an
         *         application not pulling data, and probe timeout correcponds
         *         to a link problem).  We map both to ER_TIMEOUT since sessions
         *         only admit one kind of timeout.
         *
         *     ER_OK: This means a link went down expectedly as a result of a
         *         local action on the endpoint.  Even though we look at it as
         *         a disconnect, higher levels want to see it as nothing went
         *         wrong.
         */
        switch (status) {
        case ER_ARDP_PERSIST_TIMEOUT:
            QCC_DbgTrace(("_UDPEndpoint::SetEpDisconnectStatus(): Map \"%s\" to \"ER_TIMEOUT\"", QCC_StatusText(status)));
            status = ER_TIMEOUT;
            break;

        case ER_ARDP_PROBE_TIMEOUT:
            QCC_DbgTrace(("_UDPEndpoint::SetEpDisconnectStatus(): Map \"%s\" to \"ER_TIMEOUT\"", QCC_StatusText(status)));
            status = ER_TIMEOUT;
            break;

        case ER_UDP_LOCAL_DISCONNECT:
            QCC_DbgTrace(("_UDPEndpoint::SetEpDisconnectStatus(): Map \"%s\" to \"ER_OK\"", QCC_StatusText(status)));
            status = ER_OK;
            break;

        default:
            QCC_DbgTrace(("_UDPEndpoint::SetEpDisconnectStatus(): Map \"%s\" to \"ER_SOCK_OTHER_END_CLOSED\"", QCC_StatusText(status)));
            status = ER_SOCK_OTHER_END_CLOSED;
            break;
        }

        /*
         * Set the bus endpoint version of the disconnect status with the
         * sanitized version.
         */
        disconnectStatus = status;
        m_disconnected = true;
    }

    /**
     * Set the link timeout for this connection.
     * A call to this function will modify the timeout used
     * for this endpoint by the probe mechanism, i.e. the mechanism
     * which sends keepalive ("NUL") packets. If no response to the
     * keepalives has been received in <linktimeoutSeconds> seconds,
     * the link is considered dead and the session is lost. The set timeout will
     * also determine the interval at which the keepalives are sent:
     * interval = linkTimeout / keepaliveRetries.
     * Default linkTimeout and keepaliveRetries are read from the
     * routing node configuration XML (elements udp_linktimeout and
     * udp_keepalive_retries in the XML).
     */
    QStatus SetLinkTimeout(uint32_t& linkTimeoutSeconds)
    {
        QCC_DbgTrace(("_UDPEndpoint::SetLinkTimeout(linkTimeout=%d.)", linkTimeoutSeconds));

        QStatus status = ER_OK;
        if (!m_disconnected) {
            ArdpConnRecord* conn = GetConn();
            QCC_ASSERT(conn != nullptr);
            uint32_t linkTimeoutMilliseconds = linkTimeoutSeconds * 1000;
            m_transport->m_ardpLock.Lock(MUTEX_CONTEXT);
            ARDP_UpdateProbeTimeout(GetHandle(), conn, linkTimeoutMilliseconds);
            m_transport->m_ardpLock.Unlock(MUTEX_CONTEXT);
        } else {
            status = ER_ARDP_INVALID_STATE;
            QCC_LogError(status, ("_UDPEndpoint::SetLinkTimeout() ARDP disconnected"));
        }

        return status;
    }

    void StateLock(const char* file, uint32_t line)
    {
        m_stateLock.Lock(file, line);
    }

    void StateUnlock(const char* file, uint32_t line)
    {
        m_stateLock.Unlock(file, line);
    }

    void StateLock()
    {
        m_stateLock.Lock();
    }

    void StateUnlock()
    {
        m_stateLock.Unlock();
    }

  private:
    UDPTransport* m_transport;        /**< The server holding the connection */
    ArdpStream* m_stream;             /**< Convenient pointer to the underlying stream */
    ArdpHandle* m_handle;             /**< The handle to the underlying protocol */
    ArdpConnRecord* m_conn;           /**< The connection record for the underlying protocol */
    uint32_t m_id;                    /**< The ID of the connection record for the underlying protocol */
    qcc::IPAddress m_ipAddr;          /**< Remote IP address. */
    uint16_t m_ipPort;                /**< Remote port. */
    bool m_registered;                /**< If true, a call-out to the daemon has been made to register this endpoint */
    volatile SideState m_sideState;   /**< Is this an active or passive connection */
    volatile EndpointState m_epState; /**< The state of the endpoint itself */
    qcc::Timespec<qcc::MonotonicTime> m_tStart; /**< Timestamp indicating when the authentication process started */
    qcc::Timespec<qcc::MonotonicTime> m_tStop; /**< Timestamp indicating when the stop process for the endpoint was begun */
    qcc::Timespec<qcc::MonotonicTime> m_tWaitStart; /**< Timestamp indicating when the endpoint went into EP_WAITING state */
    qcc::Timespec<qcc::MonotonicTime> m_tStall; /**< Timestamp indicating when the last stall warning was logged */
    bool m_remoteExited;              /**< Indicates if the remote endpoint exit function has been run.  Cannot delete until true. */
    bool m_exitScheduled;             /**< Indicates if the remote endpoint exit function has been scheduled. */
    volatile bool m_disconnected;     /**< Indicates an interlocked handling of the ARDP_Disconnect has happened */
    volatile int32_t m_refCount;      /**< Incremented if a thread is wandering through the endpoint, decrememted when it leaves */
    volatile int32_t m_pushCount;     /**< Incremented if a thread is wandering through the endpoint, decrememted when it leaves */
    qcc::Mutex m_stateLock;           /**< Mutex protecting the endpoint state against multiple threads attempting changes */
    bool m_wait;                      /**< If true, follow EP_STOPPING state with EP_WAITING state */
};

/**
 * A skeletal variety of a Stream used to fake the system into believing that
 * there is a stream-based protocol at work here.  This is not intended to be
 * wired into IODispatch but is used to allow the daemon to to run in a
 * threadless, streamless environment without major changes.
 */
class ArdpStream : public qcc::Stream {
  public:

    ArdpStream()
        : m_transport(NULL),
        m_endpoint(NULL),
        m_handle(NULL),
        m_conn(NULL),
        m_connId(0),
        m_lock(LOCK_LEVEL_UDPTRANSPORT_ARDPSTREAM_LOCK),
        m_disc(false),
        m_discSent(false),
        m_discStatus(ER_OK),
        m_writeCondition(NULL),
        m_sendsOutstanding(0)
    {
        QCC_DbgTrace(("ArdpStream::ArdpStream()"));
        m_writeCondition = new qcc::Condition();
    }

    virtual ~ArdpStream()
    {
        QCC_DbgTrace(("ArdpStream::~ArdpStream()"));

        QCC_DbgPrintf(("ArdpStream::~ArdpStream(): delete events"));
        delete m_writeCondition;
        m_writeCondition = NULL;
    }

    /**
     * Get a pointer to the associated UDP transport instance.
     */
    UDPTransport* GetTransport() const
    {
        QCC_DbgTrace(("ArdpStream::GetTransport(): => %p", m_transport));
        return m_transport;
    }

    /**
     * Set the pointer to the associated UDP transport instance.
     */
    void SetTransport(UDPTransport* transport)
    {
        QCC_DbgTrace(("ArdpStream::SetTransport(transport=%p)", transport));
        m_transport = transport;
    }

    /**
     * Get a pointer to the associated UDP endpoint.
     */
    _UDPEndpoint* GetEndpoint() const
    {
        QCC_DbgTrace(("ArdpStream::GetEndpoint(): => %p", m_endpoint));
        return m_endpoint;
    }

    /**
     * Set the pointer to the associated UDP endpoint instance.
     */
    void SetEndpoint(_UDPEndpoint* endpoint)
    {
        QCC_DbgTrace(("ArdpStream::SetEndpoint(endpoint=%p)", endpoint));
        m_endpoint = endpoint;
    }

    /**
     * Get the information that describes the underlying ARDP protocol connection.
     */
    ArdpHandle* GetHandle() const
    {
        QCC_DbgTrace(("ArdpStream::GetHandle(): => %p", m_handle));
        return m_handle;
    }

    /**
     * Set the handle to the underlying ARDP protocol instance.
     */
    void SetHandle(ArdpHandle* handle)
    {
        QCC_DbgTrace(("ArdpStream::SetHandle(handle=%p)", handle));
        m_handle = handle;
    }

    /**
     * Get the information that describes the underlying ARDP protocol
     * connection.
     */
    ArdpConnRecord* GetConn() const
    {
        QCC_DbgTrace(("ArdpStream::GetConn(): => %p", m_conn));
        return m_conn;
    }

    /**
     * Set the information that describes the underlying ARDP protocol
     * connection.
     */
    void SetConn(ArdpConnRecord* conn)
    {
        QCC_DbgTrace(("ArdpStream::SetConn(conn=%p)", conn));
        m_conn = conn;
    }

    /**
     * Get the underlying ARDP protocol connection identifier.
     */
    uint32_t GetConnId() const
    {
        QCC_DbgTrace(("ArdpStream::GetConnId(): => %p", m_connId));
        return m_connId;
    }

    /**
     * Set the underlying ARDP protocol connection ID
     */
    void SetConnId(uint32_t connId)
    {
        QCC_DbgTrace(("ArdpStream::SetConnId(connId=%d.)", connId));
        m_connId = connId;
    }

    /**
     * Add the currently running thread to a set of threads that may be
     * currently referencing the internals of the stream.  We need this list to
     * make sure we don't try to delete the stream if there are threads
     * currently using the stream, and to wake those threads in case the threads
     * are blocked waiting for a send to complete when the associated endpoint
     * is shut down.
     */
    void AddCurrentThread()
    {
        QCC_DbgTrace(("ArdpStream::AddCurrentThread()"));

        ThreadEntry entry;
        entry.m_thread = qcc::Thread::GetThread();
        entry.m_stream = this;
        m_lock.Lock(MUTEX_CONTEXT);
        m_threads.insert(entry);
        m_lock.Unlock(MUTEX_CONTEXT);
    }

    /**
     * Remove the currently running thread from the set of threads that may be
     * currently referencing the internals of the stream.
     */
    void RemoveCurrentThread()
    {
        QCC_DbgTrace(("ArdpStream::RemoveCurrentThread()"));

        ThreadEntry entry;
        entry.m_thread = qcc::Thread::GetThread();
        entry.m_stream = this;

        m_lock.Lock(MUTEX_CONTEXT);
        set<ThreadEntry>::iterator i = m_threads.find(entry);
        QCC_ASSERT(i != m_threads.end() && "ArdpStream::RemoveCurrentThread(): Thread not on m_threads");
        m_threads.erase(i);
        m_lock.Unlock(MUTEX_CONTEXT);
    }

    /**
     * Wake all of the treads that may be waiting on the condition for a chance
     * to contend for the resource.  We expect this function to be used to wake
     * all of the threads in the case that the stream is shutting down.
     * Presumably they will all wake up and notice that the stream is going away
     * and exit
     */
    void WakeThreadSet()
    {
        QCC_DbgTrace(("ArdpStream::WakeThreadSet()"));
        m_lock.Lock(MUTEX_CONTEXT);
        if (m_writeCondition) {
            m_writeCondition->Broadcast();
        }
        m_lock.Unlock(MUTEX_CONTEXT);
    }

    /**
     * Determine whether or not there is a thread waiting on the stream for a write
     * operation to complete.
     */
    bool ThreadSetEmpty()
    {
        QCC_DbgTrace(("ArdpStream::ThreadSetEmpty()"));

        m_lock.Lock(MUTEX_CONTEXT);
        bool empty = m_threads.empty();
        m_lock.Unlock(MUTEX_CONTEXT);

        QCC_DbgTrace(("ArdpStream::ThreadSetEmpty(): -> %s", empty ? "true" : "false"));
        return empty;
    }

    /**
     * Get the number of outstanding send buffers -- the number of sends that have been
     * called, but have not completed and had the buffers returned by ARDP.
     */
    uint32_t GetSendsOutstanding()
    {
        QCC_DbgTrace(("ArdpStream::GetSendsOutstanding() -> %d.", m_sendsOutstanding));
        m_transport->m_cbLock.Lock(MUTEX_CONTEXT);
        uint32_t sendsOutstanding = m_sendsOutstanding;
        m_transport->m_cbLock.Unlock(MUTEX_CONTEXT);
        return sendsOutstanding;
    }

    /**
     * Set the stream's write condition if it exists.  This will wake exactly
     * one waiting thread which will then loop back around and try to do its
     * work again.
     */
    void SignalWriteCondition()
    {
        QCC_DbgTrace(("ArdpStream::SignalWriteCondition()"));
        m_lock.Lock(MUTEX_CONTEXT);
        if (m_writeCondition) {
            m_writeCondition->Signal();
        }
        m_lock.Unlock(MUTEX_CONTEXT);
    }

    /**
     * Send some bytes to the other side of the conection described by the
     * m_conn member variable.
     *
     * The caller of this function is most likely the daemon router that is
     * moving a message to a remote destination.  It was written expecting this
     * call to copy bytes into TCP or block when TCP applies backpressure.  As
     * soon as the call returns, the router expects to be able to delete the
     * message backing buffer (our buf) and go on about its business.
     *
     * That means we basically have to do the same thing here unless we start
     * ripping the guts out of the system.  That means the daemon router expects
     * to see and endpoint with a stream in it that has this PushBytes method.
     *
     * we need to copy the data in and return immediately if there is no
     * backpressure from the protocol; or copy the data in and block the caller
     * if there is backpressure.  Backpressure is indicated by the
     * ER_ARDP_BACKPRESSURE return.  If this happens, we cannot send any more
     * data until we get a send callback indicating the other side has consumed
     * some data.  In this case we need to block the calling thread until it can
     * continue.
     *
     * When a buffer is sent, the ARDP protocol takes ownership of it until it
     * is ACKed by the other side or it times out.  When the ACK happens, a send
     * callback is fired that will record the actual status of the send and free
     * the buffer.  The status of the write is not known until the next read or
     * write operation.
     */
    QStatus PushBytes(const void* buf, size_t numBytes, size_t& numSent, uint32_t ttl)
    {
        QCC_DbgTrace(("ArdpStream::PushBytes(buf=%p, numBytes=%d., numSent=%p)", buf, numBytes, &numSent));
        QStatus status = ER_OK;

        /*
         * Start out by assuming that nothing worked and we have sent nothing.
         */
        numSent = 0;

        /*
         * If either the transport or the endpoint is not in a state where it
         * indicates that it is ready to send, we need to return an error.
         *
         * Unfortunately, the system will try to do all kinds of things to an
         * endpoint even though it has just stopped it.  To prevent cascades of
         * error logs, we need to return a "magic" error code and not log an
         * error if we detect that either the transport or the endpoint is
         * shutting down.  Higher level code (especially AllJoynObj) will look
         * for this error and not do any logging if it is a transient error
         * during shutdown, as identified by the error return value
         * ER_BUS_ENDPOINT_CLOSING.
         *
         * There is a window between the start of a remote disconnect event and
         * the endpoint state change where the endpoint can think it is up and
         * started but the stream can think it has started going down.  We'll
         * catch that case before actually starting the send.
         */
        if (m_transport->IsRunning() == false || m_transport->m_stopping == true) {
            return ER_BUS_ENDPOINT_CLOSING;
        }
        if (m_endpoint->IsEpStarted() == false) {
            return ER_BUS_ENDPOINT_CLOSING;
        }

        /*
         * We can proceed, but we are a new thread that is going to be wandering
         * down into the stream code, so add ourselves to the list of threads
         * wandering around in the associated endpoint.  We need to keep track
         * of this in case the endpoint is stopped while the current thread is
         * wandering around in the stream trying to get the send done.
         */
        AddCurrentThread();

#ifndef NDEBUG
#if BYTEDUMPS
        DumpBytes((uint8_t*)buf, numBytes);
#endif
#endif
        /*
         * Copy in the bytes to preserve the buffer management approach expected by
         * higher level code.
         */
        QCC_DbgPrintf(("ArdpStream::PushBytes(): Copy in"));
#ifndef NDEBUG
        uint8_t* buffer = new uint8_t[numBytes + SEAL_SIZE];
        SealBuffer(buffer + numBytes);
#else
        uint8_t* buffer = new uint8_t[numBytes];
#endif
        memcpy(buffer, buf, numBytes);

        /*
         * Set up a timeout on the write.  If we call ARDP_Send, we expect it to
         * come back with some a send callback if it accepts the data.  As a
         * double-check, we add our own timeout that expires in twice the we
         * expect ARDP to time out.  This is effectively a watchdog that barks
         * when ARDP is not doing what we expect it to.
         */
        uint32_t timeout;
        Timespec<MonotonicTime> tStart;

        m_transport->m_ardpLock.Lock(MUTEX_CONTEXT);
        timeout = 2 * ARDP_GetDataTimeout(m_handle, m_conn);
        m_transport->m_ardpLock.Unlock(MUTEX_CONTEXT);

        GetTimeNow(&tStart);
        QCC_DbgPrintf(("ArdpStream::PushBytes(): Start time is %" PRIu64 ".%03d.", tStart.seconds, tStart.mseconds));

        /*
         * This is the point at which a classic condition vairable wait idiom
         * comes into play.  Extracted from all of the dependencies here, it
         * would look something like:
         *
         *     mutex.Lock(MUTEX_CONTEXT)
         *     while (condition != met) {
         *         condition.Wait(mutex);
         *     }
         *     mutex.Unlock(MUTEX_CONTEXT);
         *
         * The mutex in question is the cbLock, which synchronizes this thread
         * (think a consumer contending for the protected resource) with the
         * callback thread from ARDP (think producer -- making the ARDP resource
         * available).  The condition in question is whether or not are done trying
         * to write to the stream (we can either succeed or error out).
         */
        bool done = false;
        m_transport->m_cbLock.Lock(MUTEX_CONTEXT);
        while (done != true) {
            /*
             * We're in a loop here that could possibly run for many seconds
             * trying to get data out, so we need to check to make sure that the
             * transport is not shutting down each time through the loop.
             */
            if (m_transport->IsRunning() == false || m_transport->m_stopping == true) {
                status = ER_BUS_ENDPOINT_CLOSING;
                done = true;
                continue;
            }

            /*
             * Check the watchdog to make sure it has not timed out.
             */
            Timespec<MonotonicTime> tNow;
            GetTimeNow(&tNow);
            int32_t tRemaining = tStart + timeout - tNow;
            QCC_DbgPrintf(("ArdpStream::PushBytes(): tRemaining is %d.", tRemaining));
            if (tRemaining <= 0) {
                status = ER_TIMEOUT;
                QCC_LogError(status, ("ArdpStream::PushBytes(): Timed out"));
                done = true;
                continue;
            }

            /*
             * Above, we did a coarse granularity checks for whether or not the
             * endpoint was ready to accept data.  There is one case for which
             * we have to be more careful though.  That's the shutdown case.
             * When we speak about shutdown, think socket shutdown.  We have
             * queued up a bunch of data, and we want to do the equivalent of a
             * shutdown(SHUT_WR) when we stop our endpoint.  This means we want
             * to wait for existing data to be sent, and then we want to shut
             * down the endpoint.
             *
             * The equivalent of a shutdown(SHUT_WR) in our case is calling
             * Stop() on an endpoint.  If the Stop() is a result of a local
             * shutdown, the endpoint will immediately transition to the
             * EP_STOPPING state.  This change will cause the endpoint
             * management thread to run.  The management thread will notice the
             * local stop and transition immediately to EP_WAITING state.  The
             * endpoint remains in EP_WAITING until all of the in-process sends
             * complete, at which time an ARDP_Disconnect() is sent and the
             * endpoint continues the destruction process.
             *
             * We need to make sure that we are in EP_STARTED state when we make
             * the ARDP_Send() call, and that we do not allow a change of state
             * out of EP_STARTED while the call is executing, otherwise we risk
             * making a send call and queueing a write during the time at which
             * the management thread is deciding when to execute the
             * ARDP_Disconnect.
             *
             * There at least three threads that may be interested in the
             * instantaneous value of the state: there's us, who is trying to
             * send bytes to the endpoint; there's the management thread who may
             * be wanting to change the state of the endpoint; and there's a
             * LeaveSession thread that may be driving a Stop().  We take the
             * endpoint state change lock and hold it during the ARDP call to
             * prevent possible inconsistencies.
             *
             * There is a window between the start of a remote disconnect event
             * and the endpoint state change where the endpoint can think it is
             * up and started but the stream can think it has started going
             * down.  If we start a send during that time it is doomed to fail,
             * so we check for this corner case at the last possible time.
             */
            m_endpoint->StateLock(MUTEX_CONTEXT);

            if (m_endpoint->IsEpStarted()) {
                if (m_disc || m_discSent) {
                    /*
                     * The corner case mentioned above has happened, so don't
                     * bother to start the ARDP_Send since we'll just get an
                     * error.
                     *
                     * Note that there used to be a consistency checking assert
                     * right here.  It was removed since the disconnect callback
                     * doesn't update the state of the stream and the state of
                     * the endpoint atomically.  The "obvious" consistency check
                     * here failed under stress.  As discussed in a comment in
                     * DisconnectCb(), the inconsistency is harmless, but we
                     * minimize its impact here.
                     */
                    m_endpoint->StateUnlock(MUTEX_CONTEXT);
                    status = ER_BUS_ENDPOINT_CLOSING;
                    done = true;
                    continue;
                } else {
                    /*
                     * We think everything is up and ready in ARDP-land, so we
                     * can go ahead and start a send.
                     */
                    m_transport->m_ardpLock.Lock(MUTEX_CONTEXT);
                    status = ARDP_Send(m_handle, m_conn, buffer, numBytes, ttl);
                    m_transport->m_ardpLock.Unlock(MUTEX_CONTEXT);
                }
            } else {
                /*
                 * The endpoint is not in started state, which means it is
                 * disconnecting which means it is closing from the point of
                 * view of higher level code.  The AllJoynObj, for example,
                 * special-cases a return of ER_BUS_ENDPOINT_CLOSING since
                 * it is "expected."
                 */
                m_endpoint->StateUnlock(MUTEX_CONTEXT);
                status = ER_BUS_ENDPOINT_CLOSING;
                done = true;
                continue;
            }

            m_endpoint->StateUnlock(MUTEX_CONTEXT);

            /*
             * If we do something that is going to bug the ARDP protocol, we need
             * to call back into ARDP ASAP to get it moving.  This is done in the
             * main thread, which we need to wake up.  Note that we don't set
             * m_manage so we don't trigger endpoint management, we just trigger
             * ARDP_Run to happen.
             */
            m_transport->Alert();

            /*
             * If the send succeeded, then the bits are on their way off to the
             * destination.  The send callback associated with this PushBytes()
             * will take care of freeing the buffer we allocated.  We return back
             * to the caller as if we were TCP and had copied the bytes into the
             * kernel.
             */
            if (status == ER_OK) {
                /*
                 * The bytes are in flight, so as far as we are concerned they
                 * were successfully written; so indicate that to the caller.
                 *
                 * If we have successfully sent the bytes, the ARDP protocol has
                 * taken responsibility for them, so the buffer is now gone.  We
                 * can't ever touch this buffer so we need to rid ourselves of
                 * the reference to it.
                 */
                numSent = numBytes;
                ++m_sendsOutstanding;
                m_transport->m_cbLock.AssertOwnedByCurrentThread();
#if SENT_SANITY
                m_sentSet.insert(buffer);
#endif
                buffer = NULL;
                done = true;
                continue;
            }

            /*
             * If the send failed, and the failure was not due to the
             * application of backpressure by the protocol, we have a hard
             * failure and we must give up.  Since the buffer wasn't sent, the
             * callback won't happen and we need to dispose of it here and now.
             */
            if (status != ER_ARDP_BACKPRESSURE) {
                QCC_LogError(status, ("ArdpStream::PushBytes(): Hard failure"));
                done = true;
                continue;
            }

            /*
             * If backpressure has been applied by the ARDP protocol, we can't
             * send another message on this connection until the other side ACKs
             * one of the outstanding datagrams.  It communicates this to us by
             * a send callback which, in turn, signals the condition variable
             * we'll be waiting on and wakes us up. The Wait here corresponds to
             * the Wait in the condition idiom outlined above.
             *
             * What if the backpressure error happens and there are no
             * outstanding messages?  That is, what if the UDP buffer is full
             * and we cant' send even the one message.  Since there is no
             * message in process, there will never be a SendCb to bug the
             * condition to wake us up and therefore the send will time out.  We
             * assume that ARDP will allow us to send at least one message
             * before blocking us due to backpressure; so this is therefore
             * assumed to be a non-problem.
             */
            if (status == ER_ARDP_BACKPRESSURE) {
                QCC_DbgPrintf(("ArdpStream::PushBytes(): Backpressure. Condition::Wait()."));
                QCC_ASSERT(m_writeCondition && "ArdpStream::PushBytes(): m_writeCondition must be set");
                status = m_writeCondition->TimedWait(m_transport->m_cbLock, tRemaining);

                /*
                 * We expect that the wait will return either ER_OK if it
                 * succeeds, or ER_TIMEOUT.  If the Wait fails in other ways
                 * then we will stop trying and communicate the failure back to
                 * the caller since we really don't know what might have
                 * happened and whether or not this is recoverable.
                 */
                if (status != ER_OK && status != ER_TIMEOUT) {
                    QCC_LogError(status, ("ArdpStream::PushBytes(): Condition::Wait() returned unexpected error"));
                    done = true;
                    continue;
                }

                /*
                 * If there was a disconnect in the underlying connection, there's
                 * nothing we can do but return the error.
                 */
                if (m_disc) {
                    status = ER_UDP_DISCONNECT;
                    QCC_LogError(status, ("ArdpStream::PushBytes(): Stream disconnected"));
                    done = true;
                    continue;
                }

                QCC_DbgPrintf(("ArdpStream::PushBytes(): Backpressure loop"));
                QCC_ASSERT(done == false && "ArdpStream::PushBytes(): loop error");
            }

            /*
             * We are at the end of the while (condition != true) piece of the
             * condition variable wait idiom.  To get here, we must have tried
             * to send a message.  That send either did or did not work out.  If
             * it succeeded, done will have been set to true and we'll break out
             * of the while loop.  If there was a hard failure, done will have
             * also been set to true and we'll break out.  If We detected
             * backpressure, we blocked on the condition variable until it was
             * set.  This indicates that backpressure may have been relieved.
             * we need to loop back and try the ARDP_Send again, maybe
             * encountering backpressure again.
             */
        }

        /*
         * If the buffer was successfully sent off to ARDP, then we no longer
         * have ownership of the buffer and the pointer will have been set to
         * NULL.  If it is not NULL we own it and must dispose of it.
         */
        if (buffer) {
#ifndef NDEBUG
            CheckSeal(buffer + numBytes);
#endif
            delete[] buffer;
            buffer = NULL;
        }

        /*
         * This is the last unlock in the condition wait idiom outlined above.
         * We are all done here.
         */
        m_transport->m_cbLock.Unlock(MUTEX_CONTEXT);
        RemoveCurrentThread();
        return status;
    }

    /*
     * A version of PushBytes that doesn't care about TTL.
     */
    QStatus PushBytes(const void* buf, size_t numBytes, size_t& numSent)
    {
        QCC_DbgTrace(("ArdpStream::PushBytes(buf=%p, numBytes=%d., numSent=%p)", buf, numBytes, &numSent));
        return PushBytes(buf, numBytes, numSent, 0);
    }

    /**
     * Get some bytes from the other side of the conection described by the
     * m_conn member variable.  Data must be present in the message buffer
     * list since we expect that a RecvCb that added a buffer to that list is
     * what is going to be doing the read that will eventually call PullBytes.
     * In that case, since the data is expected to be present, <timeout> will
     * be zero.
     */
    QStatus PullBytes(void* buf, size_t reqBytes, size_t& actualBytes, uint32_t timeout)
    {
        QCC_UNUSED(buf);
        QCC_UNUSED(reqBytes);
        QCC_UNUSED(actualBytes);
        QCC_UNUSED(timeout);
        QCC_DbgTrace(("ArdpStream::PullBytes(buf=%p, reqBytes=%d., actualBytes=%d., timeout=%d.)",
                      buf, reqBytes, actualBytes, timeout));
        QCC_ASSERT(0 && "ArdpStream::PullBytes(): Should never be called");
        return ER_FAIL;
    }

    /**
     * Set the stram up for being torn down before going through the expected
     * lifetime state transitions.
     */
    void EarlyExit()
    {
        QCC_DbgTrace(("ArdpStream::EarlyExit()"));

        /*
         * An EarlyExit is one when a stream has been created in the expectation
         * that an endpoint will be brought up, but the system changed its mind
         * in mid-"stream" and therefore there is no disconnect processing needed
         * and there must be no threads waiting.
         */
        m_lock.Lock(MUTEX_CONTEXT);
        m_disc = true;
        m_conn = NULL;
        m_discStatus = ER_UDP_EARLY_EXIT;
        m_lock.Unlock(MUTEX_CONTEXT);
    }

    /**
     * Get the disconnected status.  If the stream has been disconnected, return
     * true otherwise false.
     */
    bool GetDisconnected()
    {
        QCC_DbgTrace(("ArdpStream::Disconnected(): -> %s", m_disc ? "true" : "false"));
        return m_disc;
    }

    /**
     * In the case of a local disconnect, disc sent means that ARDP_Disconnect()
     * has been called.  Determine if this call has been made or not.
     */
    bool GetDiscSent()
    {
        QCC_DbgTrace(("ArdpStream::GetDiscSent(): -> %s", m_discSent ? "true" : "false"));
        return m_discSent;
    }

    /**
     * In the case of a remote disconnect, disc status reflects the reason the
     * stream was disconnected.  In the local case, will be ER_OK until the
     * disconnect happens, then will be ER_UDP_LOCAL_DISCONNECT.
     */
    QStatus GetDiscStatus()
    {
        QCC_DbgTrace(("ArdpStream::GetDiscStatus(): -> \"%s\"", QCC_StatusText(m_discStatus)));
        return m_discStatus;
    }

    /**
     * Process a disconnect event, either local or remote.
     */
    void Disconnect(bool sudden, QStatus status)
    {
        QCC_DbgTrace(("ArdpStream::Disconnect(sudden==%d., status==\"%s\")", sudden, QCC_StatusText(status)));
        QCC_DbgPrintf(("ArdpStream::Disconnect(): ConnId == %d.", m_connId));

        /*
         * A "sudden" disconnect is an unexpected or unsolicited disconnect
         * initiated from the remote side.  In this case, we will have have
         * gotten an ARDP DisconnectCb() which tells us that the connection is
         * gone and we shouldn't use it again.
         *
         * If sudden is not true, then this is as a result of a local request to
         * terminate the connection.  This means we need to call ARDP and let it
         * know we are disconnecting.  We wait for the DisconnectCb() that must
         * happen as a result of the ARDP_Disconnect() to declare the connection
         * completely gone.
         *
         * The details can get very intricate becuase once a remote side has
         * disconnected, we can get a flood of disconnects from different local
         * users of the endopint as the daemon figures out what it no longer
         * needs as a result of a remote endpoint going away.  We just have to
         * harden ourselves against many duplicate calls.  There are three bits
         * to worry about (sudden, m_discSent, and m_disc) and so there are
         * eight possibile conditions/states here.  We just break them all out.
         */
#ifndef NDEBUG
        if (status == ER_OK) {
            QCC_ASSERT(sudden == false);
        }
        if (sudden) {
            QCC_ASSERT(status != ER_OK);
        }
#endif

        QCC_DbgPrintf(("ArdpStream::Disconnect(): sudden==%d., m_disc==%d., m_discSent==%d., status==\"%s\"",
                       sudden, m_disc, m_discSent, QCC_StatusText(status)));
        m_lock.Lock(MUTEX_CONTEXT);

        if (sudden == false) {
            if (m_disc == false) {
                if (m_discSent == false) {
                    /*
                     * sudden = false, m_disc = false, m_discSent == false
                     *
                     * This is a new solicited local disconnect event that is
                     * happening on a stream that has never seen a disconnect
                     * event.  We need to do an ARDP_Disconnect() to start the
                     * disconnect process.  We expect status to be
                     * ER_UDP_LOCAL_DISCONNECT by contract.  If we fail to send
                     * the ARDP_Disconnect() the disconnect status is updated
                     * to the reason we couldn't send it.
                     */
                    QCC_ASSERT(status == ER_UDP_LOCAL_DISCONNECT && "ArdpStream::Disconnect(): Unexpected status");

                    m_transport->m_ardpLock.Lock(MUTEX_CONTEXT);
                    QCC_DbgPrintf(("ArdpStream::Disconnect(): ARDP_Disconnect()"));
                    status = ARDP_Disconnect(m_handle, m_conn, m_connId);
                    m_transport->m_ardpLock.Unlock(MUTEX_CONTEXT);
                    if (status == ER_OK) {
                        m_discSent = true;
                        m_discStatus = ER_UDP_LOCAL_DISCONNECT;
                    } else {
                        QCC_LogError(status, ("ArdpStream::Disconnect(): Cannot send ARDP_Disconnect()"));
                        m_disc = true;
                        m_conn = NULL;
                        m_discSent = true;
                        m_discStatus = status;
                    }

                    /*
                     * Tell the endpoint manager that something interesting has
                     * happened
                     */
                    m_transport->m_manage = UDPTransport::STATE_MANAGE;
                    m_transport->Alert();
                } else {
                    /*
                     * sudden = false, m_disc = false, m_discSent == true
                     *
                     * This disconnect event is happening as a result of the
                     * ARDP disconnect callback.  We expect that the status
                     * passed in is ER_OK to confirm that this is the response
                     * to the ARDP_Disconnect().  This completes the locally
                     * initiated disconnect process.  If this happens, we expect
                     * status to be ER_OK by contract and we expect the
                     * disconnect status to have been set to
                     * ER_UDP_LOCAL_DISCONNECT by us.
                     */
                    QCC_ASSERT(status == ER_OK && "ArdpStream::Disconnect(): Unexpected status");
                    QCC_ASSERT(m_discStatus == ER_UDP_LOCAL_DISCONNECT && "ArdpStream::Disconnect(): Unexpected status");
                    m_disc = true;
                    m_conn = NULL;

                    /*
                     * Tell the endpoint manager that something interesting has
                     * happened
                     */
                    m_transport->m_manage = UDPTransport::STATE_MANAGE;
                    m_transport->Alert();
                }
            } else {
                if (m_discSent == false) {
                    /*
                     * sudden = false, m_disc = true, m_discSent == false
                     *
                     * This is a locally initiated disconnect that happens as a
                     * result of a previously received remote disconnect.  This
                     * can happen when the daemon begins dereferencing
                     * (Stopping) endpoints as a result of a previously reported
                     * disconnect.
                     *
                     * The connection should already be gone.
                     */
                    QCC_ASSERT(m_conn == NULL && "ArdpStream::Disconnect(): m_conn unexpectedly live");
                    QCC_ASSERT(m_disc == true && "ArdpStream::Disconnect(): unexpectedly not disconnected");
                } else {
                    /*
                     * sudden = false, m_disc = true, m_discSent == true
                     *
                     * This is a locally initiated disconnect that happens after
                     * a local disconnect that has completed (ARDP_Disconnect()
                     * has been called and its DisconnectCb() has been received.
                     * This can happen when the daemon begins dereferencing
                     * (Stopping) endpoints as a result of a previously reported
                     * disconnect but is a little slow at doing so.
                     *
                     * The connection should already be gone.
                     */
                    QCC_ASSERT(m_conn == NULL && "ArdpStream::Disconnect(): m_conn unexpectedly live");
                    QCC_ASSERT(m_disc == true && "ArdpStream::Disconnect(): unexpectedly not disconnected");
                }
            }
        } else {
            if (m_disc == false) {
                if (m_discSent == false) {
                    /*
                     * sudden = true, m_disc = false, m_discSent == false
                     *
                     * This is a new unsolicited remote disconnect event that is
                     * happening on a stream that has never seen a disconnect
                     * event.
                     */
                    m_conn = NULL;
                    m_disc = true;
                    m_discStatus = status;
                } else {
                    /*
                     * sudden = true, m_disc = false, m_discSent == true
                     *
                     * This is an unsolicited remote disconnect event that is
                     * happening on a stream that has previously gotten a local
                     * disconnect event and called ARDP_Disconnect() but has not
                     * yet received the DisconnectCb() as a result of that
                     * ARDP_Disconnect().
                     *
                     * This indicates a race between the local disconnect and a
                     * remote disconnect.  Any sudden disconnect means the
                     * connection is gone; so a remote disconnect trumps an
                     * in-process local disconnect.  This means we go right to
                     * m_disc = true.  We'll leave the original m_discStatus
                     * alone.
                     */
                    m_conn = NULL;
                    m_disc = true;
                }
            } else {
                if (m_discSent == false) {
                    /*
                     * sudden = true, m_disc = true, m_discSent == false
                     *
                     * This is a second unsolicited remote disconnect event that
                     * is happening on a stream that has previously gotten a
                     * remote disconnect event -- a duplicate in other words.
                     * We'll leave the original m_discStatus alone.
                     *
                     * The connection should already be gone.
                     */
                    QCC_ASSERT(m_conn == NULL && "ArdpStream::Disconnect(): m_conn unexpectedly live");
                    QCC_ASSERT(m_disc == true && "ArdpStream::Disconnect(): unexpectedly not disconnected");
                } else {
                    /*
                     * sudden = true, m_disc = true, m_discSent == true
                     *
                     * This is an unsolicited remote disconnect event that is
                     * happening on a stream that has previously gotten a local
                     * disconnect event that has completed.  We have already
                     * called ARDP_Disconnect() and gotten the DisconnectCb()
                     * and the connection is gone.  This can happen if both
                     * sides decide to take down connections at about the same
                     * time.  We'll leave the original m_discStatus alone.
                     *
                     * The connection should already be gone.
                     */
                    QCC_ASSERT(m_conn == NULL && "ArdpStream::Disconnect(): m_conn unexpectedly live");
                    QCC_ASSERT(m_disc == true && "ArdpStream::Disconnect(): unexpectedly not disconnected");
                }
            }
        }

#ifndef NDEBUG
        if (sudden) {
            QCC_ASSERT(m_disc == true);
        }
#endif

        m_lock.Unlock(MUTEX_CONTEXT);
    }

    /**
     * This is the data sent callback which is plumbed from the ARDP protocol up
     * to this stream.  This callback means that the buffer is no longer
     * required and may be freed.  The ARDP protocol only had temporary custody
     * of the buffer.
     */
    void SendCb(ArdpHandle* handle, ArdpConnRecord* conn, uint8_t* buf, uint32_t len, QStatus status)
    {
        QCC_UNUSED(handle);
        QCC_UNUSED(conn);
        QCC_UNUSED(len);
        QCC_UNUSED(status);

        QCC_DbgTrace(("ArdpStream::SendCb(handle=%p, conn=%p, buf=%p, len=%d.)", handle, conn, buf, len));
        m_transport->m_cbLock.Lock(MUTEX_CONTEXT);
        --m_sendsOutstanding;

#if SENT_SANITY
        set<uint8_t*>::iterator i = find(m_sentSet.begin(), m_sentSet.end(), buf);
        if (i == m_sentSet.end()) {
            QCC_LogError(ER_FAIL, ("ArdpStream::SendCb(): Callback for unexpected buffer (%p, %d.): Ignored.", buf, len));
        } else {
            m_sentSet.erase(i);
        }
#endif

        m_transport->m_cbLock.Unlock(MUTEX_CONTEXT);

#ifndef NDEBUG
        CheckSeal(buf + len);
#endif
        delete[] buf;

        /*
         * If there are any threads waiting for a chance to send bits, wake them
         * up.  They will retry their sends when this event gets set.  If the
         * send callbacks are part of normal operation, the sends may succeed
         * the next time around.  If this callback is part of disconnect
         * processing the next send will fail with an error; and PushBytes()
         * will manage the outstanding write count.
         */
        if (m_writeCondition) {
            QCC_DbgPrintf(("ArdpStream::SendCb(): Condition::Signal()"));
            m_writeCondition->Signal();
        }
    }

    class ThreadEntry {
      public:
        qcc::Thread* m_thread;
        ArdpStream* m_stream;
    };

  private:
    ArdpStream(const ArdpStream& other);
    ArdpStream operator=(const ArdpStream& other);

    UDPTransport* m_transport;         /**< The transport that created the endpoint that created the stream */
    _UDPEndpoint* m_endpoint;          /**< The endpoint that created the stream */
    ArdpHandle* m_handle;              /**< The handle to the ARDP protocol instance this stream works with */
    ArdpConnRecord* m_conn;            /**< The ARDP connection associated with this endpoint / stream combination */
    uint32_t m_connId;                 /**< The ARDP connection identifier */
    qcc::Mutex m_lock;                 /**< Mutex that protects m_threads and disconnect state */
    bool m_disc;                       /**< Set to true when ARDP fires the DisconnectCb on the associated connection */
    bool m_discSent;                   /**< Set to true when the endpoint calls ARDP_Disconnect */
    QStatus m_discStatus;              /**< The status code that was the reason for the last disconnect */
    qcc::Condition* m_writeCondition;  /**< The write event that callers are blocked on to apply backpressure */
    int32_t m_sendsOutstanding;        /**< The number of Message sends that are outstanding (in-flight) with ARDP */
    std::set<ThreadEntry> m_threads;   /**< Threads that are wandering around in the stream and possibly associated endpoint */

#if SENT_SANITY
    std::set<uint8_t*> m_sentSet;
#endif

    class BufEntry {
      public:
        BufEntry() : m_buf(NULL), m_len(0), m_pulled(0), m_rcv(NULL), m_cnt(0) { }
        uint8_t* m_buf;
        uint16_t m_len;
        uint16_t m_pulled;
        ArdpRcvBuf* m_rcv;
        uint16_t m_cnt;
    };
};

bool operator<(const ArdpStream::ThreadEntry& lhs, const ArdpStream::ThreadEntry& rhs)
{
    return lhs.m_thread < rhs.m_thread;
}

/*
 * A class to encapsulate a queue of messages to be dispatched and an associated
 * thread to pump the messages.
 *
 * Whevever we have an AllJoyn Message that is ready for delivery, ideally we
 * would just hand it off to the daemon router by calling PushMessage and the
 * router would just deliver it.  There is a problem though.  What the router
 * does is to look up the destination endpoint(s) -- there may be more than one
 * if we have a signal -- and it will stick the messages on the receive queue
 * for the endpoint(s).  The catch is that if the endpoint receive queue is full
 * (because the endpoint is not consuming messages fast enough) the router will
 * block the calling thread.  If we were to allow the UDP Transport message
 * dispatcher thread itselfto block, it would essentially stop the entire UDP
 * Transport until the destination endpoint in question got around to doing
 * something about its messages.  We cannot allow that to happen.
 *
 * We want to apply backpressure directly to the source if a message cannot be
 * delivered.  The way to do that is to avoid calling ARDP_RecvReady() until the
 * message is delivered.  Backpressure will not be applied at the other side
 * until the maximum number of in-flight messages are queued.  This means that
 * we need to be able to accommodate ardpConfig.segmax messages queued up for
 * each endpoint.
 *
 * The phenomenon of the destination queue filling up has been called the "slow
 * reader problem."  Daemon Router-based solutions are being considered, but we
 * have to do something now; so we solve the problem by having a thread other
 * than the message dispatcher thread dispatch the PushMessage to the router.
 * The RemoteEndpoint has a pool of up to 100 threads available, but they are
 * deeply wired down into the concept of a stream socket, which we don't use.
 * So the thread in question lives here.
 *
 * It is relatively cheap to spin up a thread, but this behavior is highly
 * platform dependent so we don't want to do this arbitrarily frequently.  Since
 * our threads consume at least one qcc::Event which, in turn, consumes one or
 * two FDs, we need to be careful about leaving lots of them around.  This leads
 * to a design wjere we associate a thread with an endpoint in an on-demand
 * basis, with the thread exiting after some relatively short period of non-use,
 * but hanging around for bursts of messages.
 */
class MessagePump {
  public:
    MessagePump(UDPTransport* transport)
        : m_transport(transport), m_lock(LOCK_LEVEL_UDPTRANSPORT_MESSAGEPUMP_LOCK),
        m_activeThread(NULL), m_pastThreads(), m_queue(), m_condition(), m_spawnedThreads(0), m_stopping(false)
    {
        QCC_DbgTrace(("MessagePump::MessagePump()"));
    }

    virtual ~MessagePump()
    {
        QCC_DbgTrace(("MessagePump::~MessagePump()"));
        QCC_DbgTrace(("MessagePump::~MessagePump(): Dealing with threads"));
        Stop();
        Join();

        QCC_DbgTrace(("MessagePump::~MessagePump(): Dealing with remaining queued messages"));
        while (m_queue.empty() == false) {
            QueueEntry entry = m_queue.front();
            m_queue.pop();
            m_transport->m_ardpLock.Lock(MUTEX_CONTEXT);
            ARDP_RecvReady(entry.m_handle, entry.m_conn, entry.m_rcv);
            m_transport->m_ardpLock.Unlock(MUTEX_CONTEXT);
        }

        QCC_ASSERT(m_queue.empty() && "MessagePump::~MessagePump(): Message queue must be empty here");
        QCC_ASSERT(m_activeThread == NULL && "MessagePump::~MessagePump(): Active thread must be gone here");
        QCC_ASSERT(m_pastThreads.empty() && "MessagePump::~MessagePump(): Past threads must be gone here");

        QCC_DbgTrace(("MessagePump::~MessagePump(): Done"));
    }

    /*
     * Determine whether or not there is an active pump thread that may be wanting to
     * call out to the daemon.
     */
    bool IsActive()
    {
        QCC_DbgTrace(("MessagePump::IsActive()"));
        bool ret = m_activeThread != NULL;
        QCC_DbgPrintf(("MessagePump::IsActive() => \"%s\"", ret ? "true" : "false"));
        return ret;
    }

    /*
     * The Message Pump doesn't inherit from qcc::Thread so it isn't going to
     * Start(), Stop() and Join() direcly.  It HASA Thread That is Start()ed
     * on-demand.  We do implement Stop() to allow us to do something when we
     * need to cause the pump thread to stop.
     */
    QStatus Stop()
    {
        QCC_DbgTrace(("MessagePump::Stop()"));
        QStatus status = ER_OK;

        /*
         * There may be at most one m_activeThread running.  We need to set its
         * state to STOPPING.  This thread isn't going to be waiting on its stop
         * event though.  In order to minimize the number of events we create,
         * it will be waiting on a condition variable and then test for stopping
         * whenever it wakes up.  So we have to call Stop() to set the state and
         * then Signal() our condition variable to wake up the thread.
         */
        m_lock.Lock(MUTEX_CONTEXT);
        m_stopping = true;
        if (m_activeThread) {
            QCC_DbgPrintf(("MessagePump::Stop(): m_activeThread->Stop()"));
            m_activeThread->Stop();
            QCC_DbgPrintf(("MessagePump::Stop(): m_condition.Signal()"));
            m_condition.Signal();
        }
#ifndef NDEBUG
        else {
            QCC_DbgPrintf(("MessagePump::Stop(): m_activeThread is NULL"));
        }
#endif
        m_lock.Unlock(MUTEX_CONTEXT);

        QCC_DbgTrace(("MessagePump::Stop() => \"%s\"", QCC_StatusText(status)));
        return status;
    }

    /*
     * The Message Pump doesn't inherit from qcc::Thread so it isn't going to
     * Start(), Stop() and Join() direcly.  It HASA Thread That is Start()ed
     * on-demand and can be Stop()ped.  It also HASA list of threads that have
     * decided to shut down.  We implement Join() to allow us to join *all* of
     * those threads when we need the pump to shut down
     */
    QStatus Join()
    {
        QCC_DbgTrace(("MessagePump::Join()"));
        return DoJoin(true);
    }

    /*
     * The Message Pump doesn't inherit from qcc::Thread so it isn't going to
     * Start(), Stop() and Join() direcly.  It HASA Thread That is Start()ed
     * on-demand and can be Stop()ped.  It also HASA list of threads that have
     * decided to shut down.  We implement JoinPast() to allow the endpoint
     * management thread to join those shutdown threads but allow an active
     * thread to continue running.
     */
    QStatus JoinPast()
    {
        QCC_DbgTrace(("MessagePump::JoinPast()"));
        return DoJoin(false);
    }

    /*
     * Common internal method implementing both flavors of join.
     */
    QStatus DoJoin(bool both)
    {
        QCC_DbgTrace(("MessagePump::DoJoin(both=\"%s\")", both ? "true" : "false"));
        QStatus status = ER_OK;

        /*
         * There may be at most one m_activeThread running and there may be a
         * set of past threads that need Join()ing.  We expect that the active
         * thread will stop and put itself on the past threads queue.  So we
         * need to join all of the threads on the past threads queue until the
         * spawned thread count goes to zero.  We also expect that pump threads
         * will time out and exit if unused and the endpoint manager will have
         * periodically joined any past threads so this may not happen much in
         * practice.
         */
        m_lock.Lock(MUTEX_CONTEXT);
        while (m_spawnedThreads) {
            QCC_DbgPrintf(("MessagePump::DoJoin(): m_spawnedThreads=%d.", m_spawnedThreads));
            QCC_ASSERT((m_activeThread ? 1 : 0) + m_pastThreads.size() == m_spawnedThreads && "MessagePump::DoJoin(): m_spawnedThreads count inconsistent");

            if (m_pastThreads.size()) {
                PumpThread* pt = m_pastThreads.front();
                m_pastThreads.pop();
                --m_spawnedThreads;
                m_lock.Unlock(MUTEX_CONTEXT);
                status = pt->Join();
                if (status != ER_OK) {
                    QCC_LogError(status, ("MessagePump::DoJoin: PumpThread Join() error"));
                }
                delete pt;
                pt = NULL;
                m_lock.Lock(MUTEX_CONTEXT);
            } else {
                /*
                 * If there is a spawned thread left and no threads on the
                 * past threads list, it means that there is an acive thread
                 * that has not yet stopped.  Since the endpoint manager wants
                 * to clean up zombies periodically, it needs to be able to
                 * Join() past threads but not the active thread.  It calls
                 * JoinPast() to do this, and JoinPast() calls DoJoin(both=false)
                 * which sets both to false.  The endpoint Join() needs to
                 * wait for all threads to be joined so it calls Join() which
                 * calls DoJoin(both=true).
                 */
                if (both) {

                    /*
                     * We need to wait for the active thread to put itself on
                     * the past threads queue.
                     *
                     * TODO: use condition variable and thread exit routine
                     * instead of sleeping/polling.
                     */
                    QCC_ASSERT(m_stopping == true && "MessagePump::DoJoin(): m_stopping must be true if both=true)");

                    m_lock.Unlock(MUTEX_CONTEXT);
                    qcc::Sleep(10);
                    m_lock.Lock(MUTEX_CONTEXT);

                    /*
                     * We are taking and giving the mutex lock constantly in
                     * order to call out to Join() in particular which might
                     * block.  Since we are turning loose of the lock, it could
                     * be the case that there are race conditions between the
                     * Stop() and condition Signal that is going to drive the
                     * active thread to exit, and the spinning up of new active
                     * threads.  In order to prevent waiting around forever, we
                     * keep poking the active thread as we wait for it to go
                     * away.
                     */
                    if (m_activeThread) {
                        m_activeThread->Stop();
                        m_condition.Signal();
                    }
                } else {
                    /*
                     * Okay to leave the m_activeThread unJoin()ed.
                     */
                    break;
                }
            }
        }
#ifndef NDEBUG
        if (both) {
            QCC_ASSERT(m_spawnedThreads == 0 && "MessagePump::DoJoin(): m_spawnedThreads must be 0 after DoJoin(true)");
        } else {
            QCC_ASSERT(m_spawnedThreads <= 1 && "MessagePump::DoJoin(): m_spawnedThreads must be 0 or 1 after DoJoin(false)");
        }
#endif
        m_lock.Unlock(MUTEX_CONTEXT);

        QCC_DbgPrintf(("MessagePump::DoJoin(): m_spawnedThreads=%d. at return", m_spawnedThreads));
        QCC_DbgPrintf(("MessagePump::DoJoin() => \"%s\"", QCC_StatusText(status)));
        return status;
    }

    void RecvCb(ArdpHandle* handle, ArdpConnRecord* conn, uint32_t connId, ArdpRcvBuf* rcv, QStatus status)
    {
        QCC_DbgTrace(("MessagePump::RecvCb(handle=%p, conn=%p, connId=%d., rcv=%p, status=%s)", handle, conn, connId, rcv, QCC_StatusText(status)));

        QCC_ASSERT(status == ER_OK && "MessagePump::RecvCb(): Asked to dispatch an error!?");

        /*
         * We always want to pump the message in the callback so create a queue
         * entry and push it onto the queue.  If we start a thread, the first
         * thing it will do is to check the condition (queue is not empty) so it
         * will handle this entry.  If it turns out that there is a thread that
         * has stopped we don't want to spin up a new thread, but we can queue
         * up the message which will be handled when the pump is cleaned up.
         */
        m_lock.Lock(MUTEX_CONTEXT);
        QueueEntry entry(handle, conn, connId, rcv, status);
        m_queue.push(entry);

        /*
         * RecvCb() callbacks can continue to happen after we have stopped the
         * active thread, so make sure we don't spin up a new thread that might
         * after we acknowledge a Stop() request.
         */
        if (m_stopping) {
            QCC_DbgPrintf(("MessagePump::RecvCb(): Stopping"));
            m_lock.Unlock(MUTEX_CONTEXT);
            return;
        }

        /*
         * The thread rules: If there is no pump thread in existence, create one
         * and start it running.  Put the PumpThread* into m_activeThread.  If
         * there is a PumpThread* in m_activeThread, it must be running.  If you
         * want to stop a pump thread you must remove it from m_activeThread
         * before you do the stop.  If a thread detects it is no longer needed
         * (the wait times out) it will remove itself as the active thread and
         * put itself on the past threads list so it can be Join()ed.
         *
         * Here's a tricky question: what happens if we can allocate a pump
         * thread object but we can't start the pump thread?  We need the thread
         * to do something with the data, but we have no thread.  We could sit
         * in a loop trying to spawn a thread here. but that would block ARDP
         * that is trying to get rid of incoming messages.  We can wait for a
         * next incoming message to try again, but since the thread is going to
         * open the receive window we will only get SEGMAX tries and then the
         * process stalls.  If no new connection happens to start driving the
         * process again, the messages simply remain on the input queue.  We
         * choose bailing and waiting for a new message to drive the process
         * since if we cannot spin up a thread, we have bigger problems than
         * a temporarily stalled message.  The bytes aren't lost, they are
         * temporarily stashed until things maybe get better.  We hope ARDP
         * is understanding.
         */
        if (m_activeThread == NULL) {
            QCC_DbgPrintf(("MessagePump::RecvCb(): Spin up new PumpThread"));
            m_activeThread = new PumpThread(this);
            status = m_activeThread->Start(NULL, NULL);

            /*
             * The choice described in the above comment.
             */
            if (status != ER_OK) {
                delete m_activeThread;
                m_activeThread = NULL;
                m_lock.Unlock(MUTEX_CONTEXT);
                return;
            } else {
                ++m_spawnedThreads;
            }
        }

        QCC_DbgPrintf(("MessagePump::RecvCb(): m_spawnedThreads=%d.", m_spawnedThreads));
        QCC_ASSERT(m_activeThread && "MessagePump::RecvCb(): Expecting an active thread at this time.");

        /*
         * It may be the case that the active thread is stopping but it has not
         * yet moved its pointer m_activeThread to the list of past threads.  In
         * this case, there will be nobody to read and dispatch the queue entry
         * correcponding to the RecvCb.  We expect that if the thread
         * IsStopping() it must be because someone has called Stop() on the
         * message pump, and the place where this is done is in the endpoint
         * Stop() method.  This means that the endpoint is in the process of
         * being torn down.  When the message pump is eventually deleted, the
         * queued messages will be pulled off the queue and returned to ARDP.
         * The upshot is that it is okay that the thread is stopping.  We return
         * any queued messages in the order that we received them in the
         * destructor.  We just print a message that this is happening in debug
         * mode.
         */
#ifndef NDEBUG
        if (m_activeThread->IsStopping()) {
            QCC_DbgPrintf(("MessagePump::RecvCb(): Thread stopping."));
        }
#endif

        /*
         * Signal the condition to wake up an existing thread that may be asleep
         * waiting for something to do.
         */
        m_condition.Signal();
        m_lock.Unlock(MUTEX_CONTEXT);
    }

  private:
    class QueueEntry {
      public:
        QueueEntry(ArdpHandle* handle, ArdpConnRecord* conn, uint32_t connId, ArdpRcvBuf* rcv, QStatus status)
            : m_handle(handle), m_conn(conn), m_connId(connId), m_rcv(rcv), m_status(status) { }

        ArdpHandle* m_handle;
        ArdpConnRecord* m_conn;
        uint32_t m_connId;
        ArdpRcvBuf* m_rcv;
        QStatus m_status;
    };

    class PumpThread : public qcc::Thread {
      public:
        PumpThread(MessagePump* pump) : qcc::Thread(qcc::String("PumpThread")), m_pump(pump) { }
        void ThreadExit(Thread* thread);

      protected:
        qcc::ThreadReturn STDCALL Run(void* arg);

      private:
        MessagePump* m_pump;
    };

    UDPTransport* m_transport;              /**< The UDP Transport instance associated with this pump */
    qcc::Mutex m_lock;                      /**< Mutex that protects multithread access to the queue */
    PumpThread* m_activeThread;             /**< Thread doing the actual work */
    std::queue<PumpThread*> m_pastThreads;  /**< Queue of transient threads have shut down or are shutting and need to be joined */
    std::queue<QueueEntry> m_queue;         /**< Queue of received messages and associated data to dispatch to the router */
    qcc::Condition m_condition;             /**< Condition variable coordinating consumption of queue entries by the pump thread */
    uint32_t m_spawnedThreads;              /**< The number of threads that have been spawned but not joined */
    bool m_stopping;                        /**< True if Stop() has been called and we shouldn't spin up new threads */
};

_UDPEndpoint::~_UDPEndpoint()
{
    QCC_DbgHLPrintf(("_UDPEndpoint::~_UDPEndpoint()"));
    QCC_DbgHLPrintf(("_UDPEndpoint::~_UDPEndpoint(): m_refCount==%d.", m_refCount));
    QCC_DbgHLPrintf(("_UDPEndpoint::~_UDPEndpoint(): m_pushCount==%d.", m_pushCount));

    /*
     * Double check that the remote endpoint is sure that its threads are gone,
     * since our destructor is going to call its Stop() and Join() anyway.
     * before deleting it.
     */
    _RemoteEndpoint::Stop();
    _RemoteEndpoint::Exited();
    _RemoteEndpoint::Join();

    QCC_ASSERT(IncrementAndFetch(&m_refCount) == 1 && "_UDPEndpoint::~_UDPEndpoint(): non-zero reference count");
    QCC_ASSERT(IncrementAndFetch(&m_pushCount) == 1 && "_UDPEndpoint::~_UDPEndpoint(): non-zero PushMessage count");

    /*
     * Make sure that the endpoint isn't in a condition where a thread might
     * conceivably be wandering around in it.  At this point, if everything
     * is working as expected there should be no reason for taking a lock,
     * but then again, if everything is working there also should be no
     * reason for an assert.
     */
    if (m_stream) {
        /*
         * If we have gotten to this point, there certainly must have been a
         * call to Stop() which must have called the stream Disconnect().  This
         * means that it is safe to call delete the stream.  We double-check
         * that there are no threads waiting on completions of send operations
         * and the ARDP connection is/was disconnected.
         */

        QCC_ASSERT(m_stream->ThreadSetEmpty() != false && "_UDPEndpoint::~_UDPEndpoint(): Threads present during destruction");
        QCC_ASSERT(m_stream->GetDisconnected() && "_UDPEndpoint::~_UDPEndpoint(): Not disconnected");
    }

    DestroyStream();
}

QStatus _UDPEndpoint::Start()
{
    IncrementAndFetch(&m_refCount);

    /*
     * Whenever we change state, we need to protect against multiple threads
     * trying to do something at the same time.  Since state changes may be
     * initiated on threads that know nothing about our endpionts and what
     * state they are really in, we need to lock the endpoint list to make
     * sure nothing is changed out from under us.  We are careful to keep
     * this lock order the same "everywhere."  Since we are often called
     * from endpoint management code that holds the endpoint list lock, we
     * take that one first (reentrancy is enabled so we get it if we already
     * hold it).
     */
    m_transport->m_endpointListLock.Lock(MUTEX_CONTEXT);
    m_stateLock.Lock(MUTEX_CONTEXT);

    /*
     * What state are are we coming from?
     */
#ifndef NDEBUG
    PrintEpState("_UdpEndpoint::Start()");
#endif

    QCC_DbgHLPrintf(("_UDPEndpoint::Start()"));
    QCC_DbgPrintf(("_UDPEndpoint::Start(): isBusToBus = %s, allowRemote = %s)",
                   GetFeatures().isBusToBus ? "true" : "false",
                   GetFeatures().allowRemote ? "true" : "false"));

    if (m_stream) {
        bool empty = m_stream->ThreadSetEmpty();
        QCC_ASSERT(empty && "_UDPEndpoint::Start(): Threads present during Start()");
        if (empty == false) {
            QCC_LogError(ER_FAIL, ("_UDPEndpoint::Start(): Threads present during Start()"));
            m_stateLock.Unlock(MUTEX_CONTEXT);
            m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT);
            DecrementAndFetch(&m_refCount);
            return ER_FAIL;
        }
    }

    if (GetFeatures().isBusToBus) {
        QCC_DbgPrintf(("_UDPEndpoint::Start(): endpoint switching to ENDPOINT_TYPE_BUS2BUS"));
        SetEndpointType(ENDPOINT_TYPE_BUS2BUS);
    }

#ifndef NDEBUG
    /*
     * Debug consistency check.  If we are starting an endpoint it must be
     * on either the m_authList or the m_endpointList exactly once, and it
     * must be associated with an ARDP connection.
     */
    uint32_t found = 0;
    for (set<UDPEndpoint>::iterator i = m_transport->m_authList.begin(); i != m_transport->m_authList.end(); ++i) {
        UDPEndpoint ep = *i;
        if (GetConnId() == ep->GetConnId()) {
            QCC_DbgPrintf(("_UDPEndpoint::Start(): found endpoint with conn ID == %d. on m_authList", GetConnId()));
            ++found;
        }
    }
    for (set<UDPEndpoint>::iterator i = m_transport->m_endpointList.begin(); i != m_transport->m_endpointList.end(); ++i) {
        UDPEndpoint ep = *i;
        if (GetConnId() == ep->GetConnId()) {
            QCC_DbgPrintf(("_UDPEndpoint::Start(): found endpoint with conn ID == %d. on m_endpointList", GetConnId()));
            ++found;
        }
    }

    QCC_ASSERT(found == 1 && "_UDPEndpoint::Start(): Endpoint not on exactly one pending list");
#endif

    /*
     * No threads to Start(), so we jump right to started state.
     */
    QCC_ASSERT((IsEpPassiveStarted() || IsEpActiveStarted()) && "_UDPEndpoint::Start(): Endpoint not pre-started corrrectly");
    SetEpStarted();

    /*
     * We need to hook back into the router and do what RemoteEndpoint would have
     * done had we really started RX and TX threads.  Since we know an instance of
     * this object is on exactly one of our endpoint lists, we'll get a reference
     * to a valid object here.
     */
    SetStarted();
    BusEndpoint bep = BusEndpoint::wrap(this);

    /*
     * We know we hold a reference, so now we can call out to the daemon
     * with it.  We also never call back out to the daemon with a lock held
     * since you really never know what it might do.  We do keep the thread
     * reference count bumped since there is a thread that will wander back
     * out through here eventually.
     */
    m_stateLock.Unlock(MUTEX_CONTEXT);
    m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT);

    QCC_DbgPrintf(("_UDPEndpoint::Start(): RegisterEndpoint()"));
    QStatus status = m_transport->m_bus.GetInternal().GetRouter().RegisterEndpoint(bep);
    if (status == ER_OK) {
        m_registered = true;
    }

    DecrementAndFetch(&m_refCount);
    return status;
}

QStatus _UDPEndpoint::Stop()
{
    IncrementAndFetch(&m_refCount);
    QCC_DbgHLPrintf(("_UDPEndpoint::Stop()"));
    QCC_DbgPrintf(("_UDPEndpoint::Stop(): Unique name == %s, connId == %d.", GetUniqueName().c_str(), GetConnId()));
    /*
     * Whenever we change state, we need to protect against multiple threads
     * trying to do something at the same time.  Since state changes may be
     * initiated on threads that know nothing about our endpionts and what
     * state they are really in, we need to lock the endpoint list to make
     * sure nothing is changed out from under us.  We are careful to keep
     * this lock order the same "everywhere."  Since we are often called
     * from endpoint management code that holds the endpoint list lock, we
     * take that one first (reentrancy is enabled so we get it if we already
     * hold it).
     */
    m_transport->m_endpointListLock.Lock(MUTEX_CONTEXT);
    m_stateLock.Lock(MUTEX_CONTEXT);

    /*
     * What state are are we coming from?
     */
#ifndef NDEBUG
    PrintEpState("_UdpEndpoint::Stop()");
#endif

    /*
     * If we've never been completely started, there are not threads running
     * around inside us so all we have to do is to perform an EarlyExit() to
     * ensure that disconnect status is correct and wake up the endpoint
     * management thread whose resposibility it is for actually dealing with
     * Stop()ped endpoints.  If we're doing an early exit we do not expect
     * there to be any threads waiting to be stopped.
     */
    if (IsEpInitialized() || IsEpActiveStarted() || IsEpPassiveStarted()) {
        QCC_DbgPrintf(("_UDPEndpoint::Stop(): Never Start()ed"));
        if (m_stream) {
            QCC_ASSERT(m_stream->ThreadSetEmpty() == true && "_UDPEndpoint::Stop(): Inactive endpoint with threads?");
            m_stream->EarlyExit();
        }

        /*
         * We were never started, so presumably there is no data buffered
         * and waiting to be sent.  Disable the EP_WAITING state since it is
         * completely unnecessary.
         */
        SetEpWaitEnable(false);
        SetEpStopping();
        m_stateLock.Unlock(MUTEX_CONTEXT);
        m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT);

        m_transport->m_manage = UDPTransport::STATE_MANAGE;
        m_transport->Alert();

        DecrementAndFetch(&m_refCount);
        return ER_OK;
    }

    /*
     * If we're already on the way toward being shut down or are actually
     * shut down, there's nothing to do since this function has already been
     * called at some earlier time.  We will bug the endpoint managment
     * thread again to make sure it knows about us.  Don't set the state to
     * EP_STOPPING here or it will possibly overwrite other completed work
     * if Stop() is called multiple times.
     */
    if (IsEpStopping() || IsEpWaiting() || IsEpJoined() || IsEpDone()) {
        QCC_DbgPrintf(("_UDPEndpoint::Stop(): Already stopping, waiting, joined or done"));
        m_stateLock.Unlock(MUTEX_CONTEXT);
        m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT);
        DecrementAndFetch(&m_refCount);
        return ER_OK;
    }

    /*
     * By a process of elimination, the only possible state we could be in
     * is EP_STARTED.  Did someone add a state and forget to handle it here?
     */
    QCC_ASSERT(IsEpStarted() == true && "_UDPEndpoint::Stop(): Endpoint expected to be in EP_STARTED state at this point");
    QCC_DbgPrintf(("_UDPEndpoint::Stop(): Stopping while IsEpStarted()"));

#ifndef NDEBUG
    /*
     * Debug consistency check.  If we are stopping an endpoint it must be
     * on either the m_authList or the m_endpointList exactly once, and it
     * must be associated with an ARDP connection.
     */
    uint32_t found = 0;
    for (set<UDPEndpoint>::iterator i = m_transport->m_authList.begin(); i != m_transport->m_authList.end(); ++i) {
        UDPEndpoint ep = *i;
        if (GetConnId() == ep->GetConnId()) {
            QCC_DbgPrintf(("_UDPEndpoint::Stop(): found endpoint with conn ID == %d. on m_authList", GetConnId()));
            ++found;
        }
    }
    for (set<UDPEndpoint>::iterator i = m_transport->m_endpointList.begin(); i != m_transport->m_endpointList.end(); ++i) {
        UDPEndpoint ep = *i;
        if (GetConnId() == ep->GetConnId()) {
            QCC_DbgPrintf(("_UDPEndpoint::Stop(): found endpoint with conn ID == %d. on m_endpointList", GetConnId()));
            ++found;
        }
    }

    QCC_ASSERT(found == 1 && "_UDPEndpoint::Stop(): Endpoint not on exactly one pending list");
#endif
    /*
     * Set the state of the endpoint to stopping.  This will prevent any
     * more PushMessage calls from starting operations in the endpoint and
     * will prevent any additional inbound data from being dispatched to the
     * Daemon Router.
     */
    SetEpStopping();

    m_transport->m_manage = UDPTransport::STATE_MANAGE;
    m_transport->Alert();

    m_stateLock.Unlock(MUTEX_CONTEXT);
    m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT);

    DecrementAndFetch(&m_refCount);
    return ER_OK;
}

QStatus _UDPEndpoint::Join()
{
    IncrementAndFetch(&m_refCount);
    QCC_DbgHLPrintf(("_UDPEndpoint::Join()"));
    QCC_DbgPrintf(("_UDPEndpoint::Join(): Unique name == %s", GetUniqueName().c_str()));

    /*
     * Whenever we change state, we need to protect against multiple threads
     * trying to do something at the same time.  Since state changes may be
     * initiated on threads that know nothing about our endpionts and what
     * state they are really in, we need to lock the endpoint list to make
     * sure nothing is changed out from under us.  We are careful to keep
     * this lock order the same "everywhere."  Since we are often called
     * from endpoint management code that holds the endpoint list lock, we
     * take that one first (reentrancy is enabled so we get it if we already
     * hold it).
     */
    m_transport->m_endpointListLock.Lock(MUTEX_CONTEXT);
    m_stateLock.Lock(MUTEX_CONTEXT);

    /*
     * What state are are we coming from?
     */
#ifndef NDEBUG
    PrintEpState("_UdpEndpoint::Join()");
#endif

    /*
     * If we've never been completely started, there are not threads running
     * around inside us so all we have to do is to perform an (actually
     * redundant) EarlyExit() to ensure that disconnect status is correct and
     * wake up the endpoint management thread whose resposibility it is for
     * actually dealing with Join()ed endpoints.  If we're doing an early exit
     * we do not expect there to be any threads waiting to be stopped.
     */
    if (IsEpInitialized() || IsEpActiveStarted() | IsEpPassiveStarted()) {
        QCC_DbgPrintf(("_UDPEndpoint::Join(): Never Start()ed"));
        if (m_stream) {
            m_stream->EarlyExit();
            QCC_ASSERT(m_stream->ThreadSetEmpty() == true && "_UDPEndpoint::Join(): Inactive endpoint with threads?");
        }
        SetEpJoined();

        /*
         * Tell the endpoint management code that something has happened
         * that it may be concerned about.
         */
        m_transport->m_manage = UDPTransport::STATE_MANAGE;
        m_transport->Alert();

        m_stateLock.Unlock(MUTEX_CONTEXT);
        m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT);
        DecrementAndFetch(&m_refCount);
        return ER_OK;
    }

    /*
     * The AllJoyn threading model requires that we allow multiple calls to
     * Join().  We expect that the first time through the state will be
     * EP_STOPPING, in which case we may have things to do.  Once we have
     * done a successful Join(), the state will be EP_JOINED or eventually
     * EP_DONE all of which mean we have nothing left to do.  Don't update
     * state here or we may overwrite other work that has previously taken
     * us to EP_DONE.
     */
    if (IsEpJoined() || IsEpDone()) {
        QCC_DbgPrintf(("_UDPEndpoint::Join(): Already Join()ed"));
        m_stateLock.Unlock(MUTEX_CONTEXT);
        m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT);
        DecrementAndFetch(&m_refCount);
        return ER_OK;
    }

    /*
     * By a process of elimination, we are either in EP_STARTED, EP_WAITING
     * or EP_STOPPING state.  It is a programming error to call Join()
     * without first calling Stop().  Calling Stop() will put us in either
     * EP_STOPPING or EP_WAITING state.
     */
    QCC_ASSERT((IsEpStopping() || IsEpWaiting()) && "_UDPEndpoint::Join(): Stop() not previously called or unexpected state");
    QCC_DbgPrintf(("_UDPEndpoint::Join(): Join() from IsEpStopping() or IsEpWaiting()"));

    /*
     * The only way Join() will be called while we are in EP_WAITING state
     * is if the Transport itself starts shutting down.  In this case, it is
     * pointless to wait until any outstanding writes are finished, but we
     * do need to do the disconnect and switch to EP_STOPPED.  Calling
     * Disconnect will deal with causing ARDP to abort any outstanding
     * transactions.  This last minute change of plans may cause us to poll
     * for completion of this cleanup in the sleep loop below.
     */
    if (IsEpWaiting()) {
        QCC_DbgPrintf(("_UDPEndpoint::Join(): Join() from IsEpWaiting()"));
        ArdpStream* stream = GetStream();
        if (stream) {
            QCC_DbgPrintf(("_UDPEndpoint::Join(): Local stream->Disconnect()"));
            stream->Disconnect(false, ER_UDP_LOCAL_DISCONNECT);
        }

        /*
         * Set the disconnect status of our underlying BusEndpoint so that
         * higher levels can determine what to do in response.  ER_OK means
         * voluntary here, and we are presumably voluntarily shutting down.
         * Note that SetEpDisconnectStatus() may rewrite status code.
         */
        SetEpDisconnectStatus(ER_OK);

        SetEpWaitEnable(false);
        SetEpStopping();
    }

    /*
     * If there were any threads blocked waiting to get bytes through to a
     * remote host, they should have been woken up in Stop() and in the
     * normal course of events they should have woken up and left of their
     * own accord.  ManageEndpoints should have waited for that to happen
     * before calling Join().  If we happen to get caught with active
     * endpoints alive when the TRANSPORT is shutting down, however, we may
     * have to wait for that to happen here.  We can't do anything until
     * there are no threads wandering around in the endpoint or risk
     * crashing the daemon.  We just have to trust that they will cooperate.
     */
    int32_t timewait = m_transport->m_ardpConfig.timewait;
    while (m_stream && m_stream->ThreadSetEmpty() == false) {
        QCC_DbgPrintf(("_UDPEndpoint::Join(): Waiting for threads to exit"));

        /*
         * Make sure the threads are "poked" to wake them up.
         */
        m_stream->WakeThreadSet();

        /*
         * Note that we are calling Sleep() with both the endpoint list lock
         * and the state lock taken.  This is dangerous from a deadlock
         * point of view, but the threads that we want to wake up are
         * waiting on an event in the ArdpStream associated with the
         * endpoint.  They will never ask for one of our locks, so they
         * won't deadlock.  What can happen is that we block either the
         * maintenance thread or the dispatcher for timwait milliseconds
         * (typically one second).  This sounds bad, but we have added code
         * in the maintenance theread to wait until these threads are gone
         * beore calling Join() so in the normal course of events, this code
         * should never be executed.  It is here to make sure threads are
         * gone before deleting the endpoint in the case of the UDP
         * Transport being torn down unexpectedly.  In that case, it will
         * not be a problem to bock other threads, since they are going away
         * or are already gone.
         */
        qcc::Sleep(10);

        timewait -= 10;
        if (timewait <= 0) {
            QCC_DbgPrintf(("_UDPEndpoint::Join(): TIMWAIT expired with threads pending"));
            break;
        }
    }

    /*
     * The same story as in the comment above applies to the disconnect callback.
     * We expect that in the normal course of events, the endpoint management
     * thread will wait until the disconnection process is complete before
     * actually calling Join.
     */
    if (m_stream && m_stream->GetDisconnected() == false) {
        QCC_LogError(ER_UDP_NOT_DISCONNECTED, ("_UDPEndpoint::Join(): Not disconnected"));
        m_stream->EarlyExit();
    }

    QCC_DbgPrintf(("_UDPEndpoint::Join(): Going to EP_JOINED"));
    SetEpJoined();

    /*
     * Tell the endpoint management code that something has happened that
     * it may be concerned about.
     */
    m_transport->m_manage = UDPTransport::STATE_MANAGE;
    m_transport->Alert();

    m_stateLock.Unlock(MUTEX_CONTEXT);
    m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT);
    DecrementAndFetch(&m_refCount);
    return ER_OK;
}

void _UDPEndpoint::CreateStream(ArdpHandle* handle, ArdpConnRecord* conn, uint32_t dataTimeout, uint32_t dataRetries)
{
    QCC_UNUSED(dataTimeout);
    QCC_UNUSED(dataRetries);

    IncrementAndFetch(&m_refCount);
    QCC_DbgHLPrintf(("_UDPEndpoint::CreateStream(handle=%p, conn=%p)", handle, conn));

    m_transport->m_ardpLock.Lock(MUTEX_CONTEXT);
    QCC_ASSERT(m_stream == NULL && "_UDPEndpoint::CreateStream(): stream already exists");

    /*
     * The stream for a UDP endpoint is basically just a convenient place to
     * stick the connection identifier.  For the TCP transport it is a real
     * stream that connects to an underlying socket stream.
     */
    m_stream = new ArdpStream();
    m_stream->SetTransport(m_transport);
    m_stream->SetEndpoint(this);
    m_stream->SetHandle(handle);
    m_stream->SetConn(conn);
    m_stream->SetConnId(ARDP_GetConnId(handle, conn));

    /*
     * This is actually a call to the underlying endpoint that provides the
     * stream for Marshaling and unmarshaling.  This is what hooks our
     * PushMessage() back into the ArdpStream PushBytes().
     */
    SetStream(m_stream);
    m_transport->m_ardpLock.Unlock(MUTEX_CONTEXT);
    DecrementAndFetch(&m_refCount);
}

void _UDPEndpoint::DestroyStream()
{
    IncrementAndFetch(&m_refCount);
    QCC_DbgHLPrintf(("_UDPEndpoint::DestroyStream()"));
    if (m_stream) {
        QCC_ASSERT(m_stream->GetConn() == NULL && "_UDPEndpoint::DestroyStream(): Cannot destroy stream unless stream's m_conn is NULL");
        m_stream->SetHandle(NULL);
        delete m_stream;
    }
    m_stream = NULL;
    m_conn = NULL;
    DecrementAndFetch(&m_refCount);
}

void _UDPEndpoint::DisconnectCb(ArdpHandle* handle, ArdpConnRecord* conn, uint32_t connId, QStatus status)
{
    QCC_UNUSED(handle);
    QCC_UNUSED(conn);
    QCC_UNUSED(connId);

    IncrementAndFetch(&m_refCount);
    QCC_DbgHLPrintf(("_UDPEndpoint::DisconnectCb(handle=%p, conn=%p, connId=%d.)", handle, conn, connId));

    /*
     * We need to look and see if this endpoint is on the endopint list
     * and then make sure that it stays on the list, so take the lock to make sure
     * at least the UDP transport holds a reference during this process.
     */
    m_transport->m_endpointListLock.Lock(MUTEX_CONTEXT);

    if (!GetFeatures().isBusToBus) {
        m_transport->m_connLock.Lock(MUTEX_CONTEXT);
        --m_transport->m_numUntrustedClients;
        m_transport->m_connLock.Unlock(MUTEX_CONTEXT);
    }

    /*
     * The callback dispatcher looked to see if the endpoint was on the
     * endpoint list before it made the call here, and it incremented the
     * thread reference count before calling.  We should find an endpoint
     * still on the endpoint list since the management thread should not
     * remove the endpoint with threads wandering around in it.
     */
    uint32_t found = 0;
    for (set<UDPEndpoint>::iterator i = m_transport->m_endpointList.begin(); i != m_transport->m_endpointList.end(); ++i) {
        UDPEndpoint ep = *i;
        if (GetConnId() == ep->GetConnId()) {
            QCC_ASSERT(connId == GetConnId() && "_UDPEndpoint::DisconnectCb(): Inconsistent connId");
            QCC_DbgPrintf(("_UDPEndpoint::DisconnectCb(): found endpoint with conn ID == %d. on m_endpointList", GetConnId()));
            ++found;
        }
    }

    /*
     * In case when there are simultaneous local and remote disconnect requests queued up for the came connection ID,
     * we may find ourselves in a situation when the endpoint is not present. If this is the case, there is nothing for us to do, just return.
     */
    //QCC_ASSERT(found == 1 && "_UDPEndpoint::DisconnectCb(): Endpoint is gone");
    if (found == 0) {
        QCC_DbgHLPrintf(("_UDPEndpoint::DisconnectCb(): endpoint with conn ID == %d. not found on on m_endpointList", connId));
        m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT);
        return;
    }

    /*
     * We need to figure out if this disconnect callback is due to an
     * unforeseen event on the network (coming out of the protocol) or if it
     * is a callback in response to a local disconnect.  The key is the
     * reported status will only be ER_OK if the callback is in response to
     * a local disconnect that has already begun through a call to
     * _UDPEndpoint::Stop().  We turn the fact that this is a part of a
     * local disconnect in to the fact that it is not a "sudden" or
     * unexpected callback and give it to the stream Disconnect() function
     * that is going to handle the details of managing the state of the
     * connection.
     */
    bool sudden = (status != ER_OK);
    QCC_DbgPrintf(("_UDPEndpoint::DisconnectCb(): sudden==\"%s\"", sudden ? "true" : "false"));

    /*
     * Always let the stream see the disconnect event.  It is the piece of
     * code that is really dealing with the hard details.
     *
     * Note that calling Disconnect() here and Stop() at the bottom of the
     * function creates a transient situation in which the stream thinks it
     * is disconnected and the endpoint thinks it is connected in the sudden
     * (remote) disconnect case.  These two calls, m_stream->Disconnect()
     * and Stop() should really be done "together" and with the stream lock
     * and state lock held.  This was noticed very late in the game, and is
     * now special-cased (checked for) in ArdpStream::PushBytes().  This is
     * harmless since ARDP_Send() will return an error since we are trying
     * to send to a disconnected connection.  The point is, though, that the
     * state of the endoint and the state of the stream will be transiently
     * incoherent, so consistency checks will probably fail under stress.
     */
    if (m_stream) {
        QCC_DbgPrintf(("_UDPEndpoint::DisconnectCb(): Disconnect(): m_stream=%p", m_stream));
        QCC_DbgPrintf(("_UDPEndpoint::DisconnectCb(): m_stream->Disconnect() on endpoint with conn ID == %d.", GetConnId()));
        m_stream->Disconnect(sudden, status);
    }

    /*
     * Set the disconnect status in the underlying BusEndpoint so that
     * higher levels can determine what to do in response to the endpoint
     * stopping.  Note that SetEpDisconnectStatus() may rewrite status code.
     */
    SetEpDisconnectStatus(status);

    /*
     * We believe that the connection must go away here since this is either
     * an unsolicited remote disconnection which always results in the
     * connection going away or a confirmation of a local disconnect that
     * also results in the connection going away.
     */
    m_conn = NULL;

#ifndef NDEBUG
    /*
     * If there is no connection, we expect the stream to report that it is
     * disconnected.  If it does not now, there is no way for it to ever
     * become "more disconnected."
     */
    if (m_stream) {
        QCC_ASSERT(m_stream->GetDisconnected() && "_UDPEndpoint::DisconnectCb(): Stream not playing by the rules of the game");
    }
#endif

    /*
     * Since we know an instance of this object is on exactly one of our
     * endpoint lists we'll get a reference to a valid object here.  The
     * thread reference count being non-zero means we will not be deleted
     * out from under the call.
     */
    RemoteEndpoint rep = RemoteEndpoint::wrap(this);
    /*
     * Since this is a disconnect it will eventually require endpoint
     * management, so we make a note to run the endpoint management code.
     */
    m_transport->m_manage = UDPTransport::STATE_MANAGE;
    m_transport->Alert();

    /*
     * Never, ever call out to the daemon with a lock taken.  You will
     * eventually regret it.
     */
    m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT);

    /*
     * The connection is gone, so Stop() so it can continue being torn down
     * by the daemon router (and us).  This may have already been done in
     * the case of a local disconnect callback.  It was the original Stop()
     * that must have happened that precipitated the confirmation callback
     * from ARDP -- the DisconnectCb that we are running now.
     */
    Stop();

    DecrementAndFetch(&m_refCount);
}

void _UDPEndpoint::SendCb(ArdpHandle* handle, ArdpConnRecord* conn, uint32_t connId, uint8_t* buf, uint32_t len, QStatus status)
{
    QCC_UNUSED(connId);

    IncrementAndFetch(&m_refCount);
    QCC_DbgHLPrintf(("_UDPEndpoint::SendCb(handle=%p, conn=%p, buf=%p, len=%d.)", handle, conn, buf, len));

    /*
     * We need to look and see if this endpoint is on the endopint list
     * and then make sure that it stays on the list, so take the lock to make sure
     * at least the UDP transport holds a reference during this process.
     */
    m_transport->m_endpointListLock.Lock(MUTEX_CONTEXT);

#ifndef NDEBUG
    /*
     * The callback dispatcher looked to see if the endpoint was on the
     * endpoint list before it made the call here, and it incremented the
     * thread reference count before calling.  We should find an endpoint
     * still on the endpoint list since the management thread should not
     * remove the endpoint with threads wandering around in it.
     */
    uint32_t found = 0;
    for (set<UDPEndpoint>::iterator i = m_transport->m_endpointList.begin(); i != m_transport->m_endpointList.end(); ++i) {
        UDPEndpoint ep = *i;
        if (GetConnId() == ep->GetConnId()) {
            QCC_ASSERT(connId == GetConnId() && "_UDPEndpoint::SendCb(): Inconsistent connId");
            QCC_DbgPrintf(("_UDPEndpoint::SendCb(): found endpoint with conn ID == %d. on m_endpointList", GetConnId()));
            ++found;
        }
    }
    QCC_ASSERT(found == 1 && "_UDPEndpoint::SendCb(): Endpoint is gone");
#endif

    /*
     * We know we are still on the endpoint list and we know we have the
     * thread reference count bumped so it is safe to release the lock.
     */
    m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT);

    /*
     * If there is a thread trying to send bytes in this in this endpoint,
     * it first calls into PushMessage() and this indirectly calls into the
     * underlying stream's PushBytes().  If there is a pending PushBytes() a
     * thread will be blocked waiting for its ARDP send to complete.  In
     * that case, we must call back into the stream to unblock that pending
     * thread.  The stream actually does some more involved checking of the
     * returned buffers, so we let it do the free unless it is gone.
     *
     * If there is no stream, we are guaranteed there is no thread waiting
     * for something and so we can just proceed to free the memory since the
     * failure will have already been communicated up to the caller by
     * another mechanism, e.g., DisconnectCb().
     */
    if (m_stream) {
        m_stream->SendCb(handle, conn, buf, len, status);
    } else {
#ifndef NDEBUG
        CheckSeal(buf + len);
#endif
        delete[] buf;
    }

    DecrementAndFetch(&m_refCount);
}

/*
 * A thread function to dispatch all of the callbacks from the ARDP protocol.
 */
ThreadReturn STDCALL MessagePump::PumpThread::Run(void* arg)
{
    QCC_UNUSED(arg);

    QCC_DbgTrace(("MessagePump::PumpThread::Run()"));
    QCC_ASSERT(m_pump && "MessagePump::PumpThread::Run(): pointer to enclosing pump must be specified");

    /*
     * We need to implement a classic condition variable idiom.  Here the mutex
     * is the m_lock mutex member variable and the condition that needs to be
     * met is "something in the queue."  This is complicated a bit (but not
     * much) since we need to live inside a while loop and execute until we are
     * asked to stop or have hung around for some time without something useful
     * to do (see the class doxygen for more description).
     *
     * Note that IsStopping() is a call to the thread base class that indicates
     * the underlying thread has received a Stop() request.  The member variable
     * m_stopping is a boolean we use to synchronize the run thread and any
     * RecvCb() callbacks we might get from the UDP Transport dispatcher thread.
     * We don't want to have to understand the details of how and when the
     * internal stopping member of a thread is set, so we use our own with know
     * semantics for synchronization up here.
     */
    QStatus status = ER_OK;
    m_pump->m_lock.Lock(MUTEX_CONTEXT);
    while (!m_pump->m_stopping && !IsStopping() && status != ER_TIMEOUT) {
        QCC_DbgPrintf(("MessagePump::PumpThread::Run(): Top."));
        IncrementPerfCounter(PERF_COUNTER_UDP_TRANSPORT_PUMP_OUTER_LOOP);

        /*
         * Note that if the condition returns an unexpected status we loop in
         * the hope that it is recoverable.
         */
        while (m_pump->m_queue.empty() && !m_pump->m_stopping && !IsStopping() && status != ER_TIMEOUT) {
            QCC_DbgPrintf(("MessagePump::PumpThread::Run(): TimedWait for condition"));
            status = m_pump->m_condition.TimedWait(m_pump->m_lock, UDP_MESSAGE_PUMP_TIMEOUT);
            QCC_DbgPrintf(("MessagePump::PumpThread::Run(): TimedWait returns \"%s\"", QCC_StatusText(status)));
        }

        QCC_DbgPrintf(("MessagePump::PumpThread::Run(): Done with wait."));

        /*
         * One of three things has happened: 1) the condition has been signaled
         * because there is something on the queue; 2) the condition has been
         * signaled because we have been asked to stop; 3) the timed wait has
         * timed out and we have had nothing to do for that amount of time.  If
         * we've been asked to stop, or we time out, we just loop back to the
         * top and break out of the while loop -- we just need to work if the
         * queue is not empty.
         */
        if (m_pump->m_stopping || IsStopping() || status == ER_TIMEOUT) {
            continue;
        } else if (m_pump->m_queue.empty() == false) {
            QCC_DbgTrace(("MessagePump::PumpThread::Run(): Have work."));

            /*
             * Pull the entry describing the message off the work queue.
             */
            QueueEntry entry = m_pump->m_queue.front();
            m_pump->m_queue.pop();

            /*
             * We need to call out to the daemon to have it go ahead and push
             * the message off to the destination.  This gets tricky since we
             * have several threads that need to deal with the endpoint
             * including those that may want to delete it.
             *
             * While we hold the endpoint lock we are going to call
             * IncrementRefs() on the endpoint to ensure it isn't deleted before
             * the call out to the endpoint is made.  Then we call out to the
             * RecvCb() ahd then finally we DecrementRefs() to allow deletion.
             */
            bool handled = false;
            m_pump->m_transport->m_endpointListLock.Lock(MUTEX_CONTEXT);
            for (set<UDPEndpoint>::iterator i = m_pump->m_transport->m_endpointList.begin(); i != m_pump->m_transport->m_endpointList.end(); ++i) {
                UDPEndpoint ep = *i;
                if (entry.m_connId == ep->GetConnId()) {
                    QCC_DbgPrintf(("MessagePump::PumpThread::Run(): found endpoint with conn ID == %d. on m_endpointList", entry.m_connId));
                    /*
                     * We have a managed object reference to ep, but also
                     * increment the endpoint reference count (different from
                     * the managed object reference count) to make sure the
                     * endpoint manager doesn't try to delete the endpoint
                     * before our call actually makes it there.
                     */
                    ep->IncrementRefs();
                    m_pump->m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT);
                    m_pump->m_lock.Unlock(MUTEX_CONTEXT);

                    QCC_DbgPrintf(("MessagePump::PumpThread::Run(): Call out to endopint with connId=%d.", entry.m_connId));
                    IncrementPerfCounter(PERF_COUNTER_UDP_TRANSPORT_PUMP_RECVCB);
                    ep->RecvCb(entry.m_handle, entry.m_conn, entry.m_connId, entry.m_rcv, entry.m_status);
                    QCC_DbgPrintf(("MessagePump::PumpThread::Run(): Back from endpoint RecvCb()"));
                    handled = true;

                    m_pump->m_lock.Lock(MUTEX_CONTEXT);
                    m_pump->m_transport->m_endpointListLock.Lock(MUTEX_CONTEXT);
                    /*
                     * Since we held a reference to ep and we incremented the
                     * reference count, we expect this reference to remain
                     * valid.  We use it to decrement the refs and then forget
                     * it.  We can never use the iterator again since the moment
                     * we released the lock it could have become invalid.
                     */
                    ep->DecrementRefs();
                    break;
                }
            }
            m_pump->m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT);

            /*
             * If we were able to find an endpoint on which to dispatch this
             * callback then the endpoint RecvCb() took responsibility for the
             * message.
             *
             * If we were unable to find an endpoint to dispatch this callback
             * to we still need to do something about the message we were given.
             * This means returning the bytes back to ARDP.
             */
            if (handled == false) {
#if RETURN_ORPHAN_BUFS

                QCC_DbgPrintf(("MessagePump::PumpThread::Run(): Unable to find endpoint with conn ID == %d. on m_endpointList", entry.m_connId));
                m_pump->m_transport->m_ardpLock.Lock(MUTEX_CONTEXT);
                ARDP_RecvReady(entry.m_handle, entry.m_conn, entry.m_rcv);
                m_pump->m_transport->m_ardpLock.Unlock(MUTEX_CONTEXT);

#else // not RETURN_ORPHAN_BUFS

                QCC_DbgPrintf(("MessagePump::PumpThread::Run(): Unable to find endpoint with conn ID == %d. on m_endpointList. Ignore message", entry.m_connId));

#endif // not RETURN_ORPHAN_BUFS
            }
        }
    }


    /*
     * If we are exiting, we need to make sure that there are no race conditions
     * between our decision to exit and a RecvCb() decision to use an existing
     * active thread.  We also need to recognize that if we are returning because
     * of an inactivity timeout we need to allow RecvCb() to spin up a new thread.
     *
     * We hold the pump lock here, and RecvCb() must also hold the lock thread
     * when it makes its decisions.  If we know RecvCb() will run after we are
     * done.  If we are exiting because of a Stop(), then IsStopping() will be
     * true and our version (m_stopping) will also be true.  RecvCb() will not
     * spin up a new thread if m_stopping is true.  If we are exiting because of
     * inactivity at this point IsStopping() and m_stopping may or may not be
     * true depending on races.  We don't care, since m_stopping is going to
     * determine what happens after we are gone.  We just exit.
     *
     * If we are exiting, we must be the active thread.  The rules say we are
     * the one who must remove our own pointer from the activeThread, zero it
     * out and add ourselves to the pastThread queue.  If we do this atomically
     * with the pump lock held, then RecvCb() can do what it needs to do also
     * atomically.
     */
    QCC_DbgPrintf(("MessagePump::PumpThread::Run(): Exiting"));
    PumpThread* i = (PumpThread*)GetThread();
    QCC_ASSERT(m_pump->m_activeThread == i && "MessagePump::PumpThread::Run(): I should be the active thread");
    m_pump->m_pastThreads.push(i);
    m_pump->m_activeThread = NULL;
    m_pump->m_lock.Unlock(MUTEX_CONTEXT);
    QCC_DbgPrintf(("MessagePump::PumpThread::Run(): Return"));

    /*
     * The last thing we need to do is to bug the endpoint so its endpoint
     * management function will run and Join() our thread.  We've pushed our
     * thread ID onto the list of past threads, and the endpoint will assume
     * that we have exited and join us if our ID is on pastThreads.  This will
     * happen even if we get swapped out "between" the Alert() and the return
     * (especially during the closing printfs in debug mode).
     */
    QCC_DbgPrintf(("MessagePump::PumpThread::Run(): Alert()"));
    m_pump->m_transport->Alert();
    QCC_DbgPrintf(("MessagePump::PumpThread::Run(): Return"));
    return 0;
}

/**
 * Construct a UDP Transport object.
 */
UDPTransport::UDPTransport(BusAttachment& bus) :
    Thread("UDPTransport"),
    m_bus(bus), m_stopping(false), m_routerNameAdvertised(false), m_listener(nullptr),
    m_preListLock(LOCK_LEVEL_UDPTRANSPORT_PRELISTLOCK),
    /*
     * Work around the fact that m_endpointListLock and m_preListLock can get acquired
     * in reverse order by UDPTransport::Join and UDPTransport::Stop. Joining before
     * Stop is enough to avoid a circular wait between these two code paths.
     */
    m_endpointListLock(LOCK_LEVEL_CHECKING_DISABLED),
    m_listenFdsLock(LOCK_LEVEL_UDPTRANSPORT_LISTENFDSLOCK),
    m_listenRequestsLock(LOCK_LEVEL_UDPTRANSPORT_MLISTENREQUESTSLOCK),
    m_foundCallback(m_listener), m_networkEventCallback(*this),
    m_isAdvertising(false), m_isDiscovering(false), m_isListening(false),
    m_isNsEnabled(false),
    m_connecting(0),
    m_reload(STATE_RELOADING),
    m_manage(STATE_MANAGE),
    m_nsReleaseCount(0),
    m_wildcardIfaceProcessed(false), m_wildcardAddressProcessed(false),
    m_routerName(), m_maxRemoteClientsUdp(0), m_numUntrustedClients(0),
    m_authTimeout(0), m_sessionSetupTimeout(0),
    m_maxAuth(0), m_maxConn(0), m_currAuth(0), m_currConn(0),
    m_connLock(LOCK_LEVEL_UDPTRANSPORT_CONNLOCK), m_dynamicScoreUpdater(*this),
    /* Workaround for known deadlock prediction break ASACORE-2678 */
    m_ardpLock(LOCK_LEVEL_CHECKING_DISABLED),
    m_cbLock(LOCK_LEVEL_UDPTRANSPORT_CBLOCK),
    m_handle(NULL), m_dispatcher(NULL), m_exitDispatcher(NULL),
    m_workerCommandQueue(), m_workerCommandQueueLock(LOCK_LEVEL_UDPTRANSPORT_WORKERCOMMANDQUEUELOCK),
    m_exitWorkerCommandQueue(), m_exitWorkerCommandQueueLock(LOCK_LEVEL_UDPTRANSPORT_EXITWORKERCOMMANDQUEUELOCK)
#if WORKAROUND_1298
    , m_done1298(false)
#endif
{
    QCC_DbgTrace(("UDPTransport::UDPTransport()"));

    /*
     * We know we are daemon code, so we'd better be running with a daemon
     * router.  This is assumed elsewhere.
     */
    QCC_ASSERT(m_bus.GetInternal().GetRouter().IsDaemon());

    /*
     * We need to find the defaults for our connection limits.  These limits
     * can be specified in the configuration database with corresponding limits
     * used for DBus.  If any of those are present, we use them, otherwise we
     * provide some hopefully reasonable defaults.
     */
    ConfigDB* config = ConfigDB::GetConfigDB();

    m_authTimeout = config->GetLimit("auth_timeout", ALLJOYN_AUTH_TIMEOUT_DEFAULT);
    m_sessionSetupTimeout = config->GetLimit("session_setup_timeout", ALLJOYN_SESSION_SETUP_TIMEOUT_DEFAULT);
    m_maxAuth = config->GetLimit("max_incomplete_connections", ALLJOYN_MAX_INCOMPLETE_CONNECTIONS_UDP_DEFAULT);
    m_maxConn = config->GetLimit("max_completed_connections", ALLJOYN_MAX_COMPLETED_CONNECTIONS_UDP_DEFAULT);

    ArdpGlobalConfig ardpConfig;
    ardpConfig.connectTimeout = config->GetLimit("udp_connect_timeout", UDP_CONNECT_TIMEOUT);
    ardpConfig.connectRetries = config->GetLimit("udp_connect_retries", UDP_CONNECT_RETRIES);
    ardpConfig.initialDataTimeout = config->GetLimit("udp_initial_data_timeout", UDP_INITIAL_DATA_TIMEOUT);
    ardpConfig.totalDataRetryTimeout = config->GetLimit("udp_total_data_retry_timeout", UDP_TOTAL_DATA_RETRY_TIMEOUT);
    ardpConfig.minDataRetries = config->GetLimit("udp_min_data_retries", UDP_MIN_DATA_RETRIES);
    ardpConfig.persistInterval = config->GetLimit("udp_persist_interval", UDP_PERSIST_INTERVAL);
    ardpConfig.totalAppTimeout = config->GetLimit("udp_total_app_timeout", UDP_TOTAL_APP_TIMEOUT);
    ardpConfig.linkTimeout = config->GetLimit("udp_link_timeout", UDP_LINK_TIMEOUT);
    ardpConfig.keepaliveRetries = config->GetLimit("udp_keepalive_retries", UDP_KEEPALIVE_RETRIES);
    ARDP_AdjustProbeTimeoutSettings(ardpConfig.linkTimeout, ardpConfig.keepaliveRetries);
    ardpConfig.fastRetransmitAckCounter = config->GetLimit("udp_fast_retransmit_ack_counter", UDP_FAST_RETRANSMIT_ACK_COUNTER);
    ardpConfig.delayedAckTimeout = config->GetLimit("udp_delayed_ack_timeout", UDP_DELAYED_ACK_TIMEOUT);
    ardpConfig.timewait = config->GetLimit("udp_timewait", UDP_TIMEWAIT);
    ardpConfig.segbmax = config->GetLimit("udp_segbmax", UDP_SEGBMAX);
    ardpConfig.segmax = config->GetLimit("udp_segmax", UDP_SEGMAX);
    if (ardpConfig.segmax * ardpConfig.segbmax < ALLJOYN_MAX_PACKET_LEN) {
        QCC_LogError(ER_INVALID_CONFIG, ("UDPTransport::UDPTransport(): udp_segmax (%d) * udp_segbmax (%d) < ALLJOYN_MAX_PACKET_LEN (%d) ignored", ardpConfig.segbmax, ardpConfig.segmax, ALLJOYN_MAX_PACKET_LEN));
        ardpConfig.segbmax = UDP_SEGBMAX;
        ardpConfig.segmax = UDP_SEGMAX;
    }
    memcpy(&m_ardpConfig, &ardpConfig, sizeof(ArdpGlobalConfig));

    for (uint32_t i = 0; i < N_PUMPS; ++i) {
        m_messagePumps[i] = new MessagePump(this);
    }

    /*
     * User configured UDP-specific values trump defaults if longer.
     */
    uint32_t t = ardpConfig.connectTimeout * ardpConfig.connectRetries;
    if (m_authTimeout < t) {
        m_authTimeout = m_sessionSetupTimeout = t;
    }

    /*
     * Initialize the hooks to and from the ARDP protocol.  Note that
     * ARDP_AllocHandle is expected to "never fail."
     */
    m_ardpLock.Lock(MUTEX_CONTEXT);
    m_handle = ARDP_AllocHandle(&ardpConfig);
    ARDP_SetHandleContext(m_handle, this);
    ARDP_SetAcceptCb(m_handle, ArdpAcceptCb);
    ARDP_SetConnectCb(m_handle, ArdpConnectCb);
    ARDP_SetDisconnectCb(m_handle, ArdpDisconnectCb);
    ARDP_SetRecvCb(m_handle, ArdpRecvCb);
    ARDP_SetSendCb(m_handle, ArdpSendCb);
    ARDP_SetSendWindowCb(m_handle, ArdpSendWindowCb);

#if ARDP_TESTHOOKS
    /*
     * Initialize some testhooks as an example of how to do this.
     */
    ARDP_HookSendToSG(m_handle, ArdpSendToSGHook);
    ARDP_HookSendTo(m_handle, ArdpSendToHook);
    ARDP_HookRecvFrom(m_handle, ArdpRecvFromHook);
#endif

    /*
     * Call into ARDP and ask it to start accepting connections passively.
     * Since we are running in a constructor, there's not much we can do if it
     * fails.
     */
#ifndef NDEBUG
    QStatus status =
#endif
    ARDP_StartPassive(m_handle);

#ifndef NDEBUG
    if (status != ER_OK) {
        QCC_DbgPrintf(("UDPTransport::UDPTransport(): ARDP_StartPassive() returns status==\"%s\"", QCC_StatusText(status)));
    }
#endif

    m_ardpLock.Unlock(MUTEX_CONTEXT);
}

/**
 * Destroy a UDP Transport object.
 */
UDPTransport::~UDPTransport()
{
    QCC_DbgTrace(("UDPTransport::~UDPTransport()"));

    Stop();
    Join();

    for (uint32_t i = 0; i < N_PUMPS; ++i) {
        QCC_ASSERT(m_messagePumps[i]->IsActive() == false && "UDPTransport::~UDPTransport(): Destroying with active message pump");
        delete m_messagePumps[i];
        m_messagePumps[i] = NULL;
    }

    ARDP_FreeHandle(m_handle);
    m_handle = NULL;

    QCC_DbgPrintf(("UDPTransport::~UDPTransport(): m_mAuthList.size() == %d", m_authList.size()));
    QCC_DbgPrintf(("UDPTransport::~UDPTransport(): m_mEndpointList.size() == %d", m_endpointList.size()));
    QCC_ASSERT(m_preList.size() + m_authList.size() + m_endpointList.size() == 0 &&
               "UDPTransport::~UDPTransport(): Destroying with enlisted endpoints");
    //QCC_ASSERT(IncrementAndFetch(&m_refCount) == 1 && "UDPTransport::~UDPTransport(): non-zero reference count");
}

/**
 * Define an EndpointExit function even though it is not used in the UDP
 * Transport.  This virtual function is expected by the daemon and must be
 * defined even though we will not use it.  We short-circuit the EndpointExit
 * functionality by defining a new RemoteEndpoint::Stop() function that doesn't
 * require the functionality.
 */
void UDPTransport::EndpointExit(RemoteEndpoint& ep)
{
    QCC_UNUSED(ep);
    QCC_DbgTrace(("UDPTransport::EndpointExit()"));
}

/*
 * A thread to dispatch all of the callbacks from the ARDP protocol.
 */
ThreadReturn STDCALL UDPTransport::DispatcherThread::Run(void* arg)
{
    QCC_UNUSED(arg);

    IncrementAndFetch(&m_transport->m_refCount);
    QCC_DbgTrace(("UDPTransport::DispatcherThread::Run()"));

    vector<Event*> checkEvents, signaledEvents;
    checkEvents.push_back(&stopEvent);

    while (!IsStopping()) {
        QCC_DbgTrace(("UDPTransport::DispatcherThread::Run(): Wait for some action"));
        IncrementPerfCounter(PERF_COUNTER_UDP_TRANSPORT_DISPATCHER_OUTER_LOOP);

        signaledEvents.clear();

        /*
         * We should never have a status returned from Event::Wait other than
         * ER_OK since we don't set a timeout.  It is, however, the case that
         * Windows Event implementations may return ER_TIEMOUT even though no
         * timeout was set, and Posix systems may return ER_TIMER_NOT_ALLOWED.
         * If we were to exit in the face of such errors, the whole transport
         * would go down since the dispatcher thread would exit.  All we can do
         * is to hope that any errors are transient and try again.  In that
         * case, we will recover if the system does.  We'll log an error, but
         * there's not really much we can do here.
         */
        QStatus status = Event::Wait(checkEvents, signaledEvents);
        if (status != ER_OK) {
            QCC_LogError(status, ("UDPTransport::DispatcherThread::Run(): Event::Wait failed"));
            continue;
        }

        for (vector<Event*>::iterator i = signaledEvents.begin(); i != signaledEvents.end(); ++i) {
            if (*i == &stopEvent) {
                QCC_DbgTrace(("UDPTransport::DispatcherThread::Run(): Reset stopEvent"));
                stopEvent.ResetEvent();
            }
        }

        bool drained = false;
        do {
            WorkerCommandQueueEntry entry;

            /*
             * Pull an entry that describes what it is we need to do from the
             * queue.
             */
            m_transport->m_workerCommandQueueLock.Lock(MUTEX_CONTEXT);

            QCC_DbgTrace(("UDPTransport::DispatcherThread::Run(): m_workerCommandQueue.size()=%d.", m_transport->m_workerCommandQueue.size()));

            if (m_transport->m_workerCommandQueue.empty()) {
                drained = true;
            } else {
                entry = m_transport->m_workerCommandQueue.front();
                m_transport->m_workerCommandQueue.pop();
            }
            m_transport->m_workerCommandQueueLock.Unlock(MUTEX_CONTEXT);

            /*
             * We keep at it until we completely drain this queue every time we
             * wake up.
             */
            if (drained == false) {
                QCC_DbgTrace(("UDPTransport::DispatcherThread::Run(): command=%d., handle=%p, conn=%p., connId=%d.,"
                              "rcv=%p, passive=%d., buf=%p, len=%d., status=\"%s\"",
                              entry.m_command, entry.m_handle, entry.m_conn, entry.m_connId,
                              entry.m_rcv, entry.m_passive, entry.m_buf, entry.m_len, QCC_StatusText(entry.m_status)));

                /*
                 * If the command is a connect callback, we may not have an
                 * endpoint created yet.  Otherwise we have a connection ID in
                 * our command entry, and we expect it to refer to an endpoint
                 * that is on the endpoint list.  If it has been deleted out
                 * from under us we shouldn't use it.  Use the connection ID to
                 * make the connection between ArdpConnRecord* and UDPEndpoint
                 * (which also serves as our protocol demux functionality).
                 */
                if (entry.m_command == WorkerCommandQueueEntry::CONNECT_CB) {
                    /*
                     * We can't call out to some possibly windy code path out
                     * through the daemon router with the m_endpointListLock
                     * taken.
                     */
                    QCC_DbgPrintf(("UDPTransport::DispatcherThread::Run(): CONNECT_CB: DoConnectCb()"));
                    m_transport->DoConnectCb(entry.m_handle, entry.m_conn, entry.m_connId, entry.m_passive, entry.m_buf, entry.m_len, entry.m_status);

                    /*
                     * The UDPTransport::ConnectCb() handler allocated a copy of
                     * the data buffer from ARDP since ARDP expected its buffer
                     * back immediately.  We need to delete this copy now that
                     * we're done with it.
                     */
#ifndef NDEBUG
                    CheckSeal(entry.m_buf + entry.m_len);
#endif
                    delete[] entry.m_buf;
                    entry.m_buf = NULL;
                    entry.m_len = 0;
                } else {
                    bool haveLock = true;
                    m_transport->m_endpointListLock.Lock(MUTEX_CONTEXT);
                    for (set<UDPEndpoint>::iterator i = m_transport->m_endpointList.begin(); i != m_transport->m_endpointList.end(); ++i) {
                        UDPEndpoint ep = *i;
                        if (entry.m_connId == ep->GetConnId()) {
                            /*
                             * We can't call out to some possibly windy code path
                             * out through the daemon router with the
                             * m_endpointListLock taken.  But since we are going to
                             * call into the endpoint, we'll bump the reference
                             * count to indicate a thread is coming.  If the ref
                             * count bumped, the endpoint management code will not
                             * kill the endpoint out from under us.
                             */
                            ep->IncrementRefs();
                            m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT);
                            haveLock = false;

                            /*
                             * This probably seems like a lot of trouble to make a
                             * single method call.  The problem is that if we don't
                             * go through the trouble, we do the calls in an ARDP
                             * callback.  If we do it in a callback, that callback
                             * must have been driven by a call to ARDP_Run() which
                             * must have been called with the ardpLock taken.  When
                             * Start() (for example) does its RegisterEndpoint() the
                             * daemon wants to take the name table lock to add the
                             * endpoint to the name table.
                             *
                             * If another thread is sending a message through the
                             * daemon, it wants to call into daemon router which
                             * takes the nameTableLock to figure out which endpoint
                             * to send to.  If that destination endpoint happens to
                             * be a UDP endpoint, it will need to take the ardpLock
                             * to actually send the bits using ARDP_send.
                             *
                             * In once case the lock order is ardpLock, then
                             * nameTableLock; in the other case the lock order is
                             * nameTableLock, then ardpLock. Deadlock.
                             *
                             * Similar situations abound if we call out to the
                             * daemon, so we cannot call into the daemon directly
                             * from a callback which would imply the ardpLock is
                             * taken.  Instead of playing with fire, we route
                             * callbacks to this thread to get the one call done.
                             *
                             * This approach does have the benefit of keeping all of
                             * the call-outs from the ARDP protocol very quick,
                             * amounting to usually a push onto a message queue.
                             */
                            switch (entry.m_command) {
                            case WorkerCommandQueueEntry::EXIT:
                                {
                                    QCC_DbgPrintf(("UDPTransport::DispatcherThread::Run(): EXIT: Exit()"));
                                    ep->Exit();
                                    break;
                                }

                            case WorkerCommandQueueEntry::SEND_CB:
                                {
                                    QCC_DbgPrintf(("UDPTransport::DispatcherThread::Run(): SEND_CB: SendCb()"));
                                    ep->SendCb(entry.m_handle, entry.m_conn, entry.m_connId, entry.m_buf, entry.m_len, entry.m_status);
                                    break;
                                }

                            case WorkerCommandQueueEntry::RECV_CB:
                                {
                                    QCC_DbgPrintf(("UDPTransport::DispatcherThread::Run(): RECV_CB: Call RecvCb() on endpoint message pump"));
                                    /*
                                     * We have N_PUMPS worth of what amounts to
                                     * worker threads to handle making the calls
                                     * out to the daemon router.  This is to
                                     * handle cases where the reader of the
                                     * messages is slow, that then leads to the
                                     * callout to the PushMessage to block.
                                     *
                                     * We assume entry.connId to be selected
                                     * from a uniform distribution and so simply
                                     * selecting a message pump based on a mod
                                     * operation on the connection ID will
                                     * uniformly distribute the load among the
                                     * threads.
                                     *
                                     * We always select the same pump for a
                                     * given connection ID since that preserves
                                     * message ordering at the destination.
                                     *
                                     * There are complications here because
                                     * there is a possibility that the endpoint
                                     * we recently verified to exist may
                                     * actually not exist anymore as soon as we
                                     * let go of the endpoint list lock above.
                                     * The MessagePump deals with the
                                     * possibility that things are disappearing
                                     * out from underneath it.
                                     *
                                     * We assume that the message pumps array
                                     * will not be changed out from underneath
                                     * us while we are running at least.
                                     */
                                    MessagePump* mp = m_transport->m_messagePumps[entry.m_connId % N_PUMPS];
                                    QCC_ASSERT(mp != NULL && "UDPTransport::DispatcherThread::Run(): Pumps array not initialized");
                                    mp->RecvCb(entry.m_handle, entry.m_conn, entry.m_connId, entry.m_rcv, entry.m_status);
                                    break;
                                }

                            case WorkerCommandQueueEntry::DISCONNECT_CB:
                                {
                                    QCC_DbgPrintf(("UDPTransport::DispatcherThread::Run(): DISCONNECT_CB: DisconnectCb(): connId=%d.", entry.m_connId));
                                    ep->DisconnectCb(entry.m_handle, entry.m_conn, entry.m_connId, entry.m_status);
                                    break;
                                }

                            default:
                                {
                                    QCC_ASSERT(false && "UDPTransport::DispatcherThread::Run(): Unexpected command");
                                    break;
                                }

                            } // switch(entry.m_command)

                            /*
                             * At this point, we assume that we have given the
                             * m_endpointListLock and decremented the thread count
                             * in the endpoint; and our iterator can no longer be
                             * trusted (or is not there in the case of a CONNECT_CB
                             * request.
                             */
                            ep->DecrementRefs();
                            QCC_ASSERT(haveLock == false && "UDPTransport::DispatcherThread::Run(): Should not have m_endpointListLock here");
                            break;
                        } // if (entry.m_connId == ep->GetConnId())
                    } // for (set<UDPEndpoint>::iterator i ...

                    /*
                     * If we found an endpoint, we gave the lock, did the
                     * operation and broke out of the iterator loop assuming the
                     * iterator was no good any more.  If we did not find the
                     * endpoint, we still have the lock and we need to give it
                     * up.  Also, if we did not find an endpoint, we may have
                     * a receive buffer we have to dispose of.  We assume that
                     * when the endpoint bailed, any callers waiting to write
                     * were ejected and so there are no transmit buffers to
                     * deal with.
                     */
                    if (haveLock) {
                        m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT);

                        switch (entry.m_command) {
                        case WorkerCommandQueueEntry::RECV_CB:
                            {
#if RETURN_ORPHAN_BUFS
                                /*
                                 * If we get here, we have a receive callback
                                 * from ARDP but we don't have an endpoint to
                                 * route the message to.  This is expected if
                                 * the endpoint has gone down but there are
                                 * messages queued up to be delivered to it.
                                 * Since there's nowhere to send such messages,
                                 * we just have to drop them.  It is also
                                 * possible that ARDP has closed down the
                                 * connection under the sheets, so it may
                                 * consider the connection invalid.  In that
                                 * case, we try to give it back, but if ARDP
                                 * doesn't take it back, we have to assume that
                                 * it has disposed of the buffers on its own.
                                 * We'll print a message if we are in debug mode
                                 * if that happens.
                                 */
                                QCC_DbgPrintf(("UDPTransport::DispatcherThread::Run(): Orphaned RECV_CB: ARDP_RecvReady()"));
                                m_transport->m_ardpLock.Lock(MUTEX_CONTEXT);

#ifndef NDEBUG
                                QStatus alternateStatus =
#endif
                                ARDP_RecvReady(entry.m_handle, entry.m_conn, entry.m_rcv);
#ifndef NDEBUG
                                if (alternateStatus != ER_OK) {
                                    QCC_DbgPrintf(("UDPTransport::DispatcherThread::Run(): ARDP_RecvReady() returns status==\"%s\"", QCC_StatusText(alternateStatus)));
                                }
#endif
                                m_transport->m_ardpLock.Unlock(MUTEX_CONTEXT);
#else // not RETURN_ORPHAN_BUFS
                                /*
                                 * If we get here, we have a receive callback
                                 * from ARDP but we don't have an endpoint to
                                 * route the message to.  This is expected if
                                 * the endpoint has gone down but there are
                                 * messages queued up to be delivered to it.
                                 * Since there's nowhere to send such messages,
                                 * we just have to drop them.  Since the
                                 * endpoint has been destroyed, we assume that
                                 * ARDP has closed down the connection and
                                 * released any pending buffers.  This means
                                 * that we can just ignore the buffer.
                                 */
                                QCC_DbgPrintf(("UDPTransport::DispatcherThread::Run(): Orphaned RECV_CB for conn ID == %d. ignored",
                                               entry.m_connId));
#endif // not RETURN_ORPHAN_BUFS
                                break;
                            }

                        default:
                            break;
                        }
                    }
                } // else not CONNECT_CB
            } // if (drained == false)
        } while (drained == false);
    }

    QCC_DbgTrace(("UDPTransport::DispatcherThread::Run(): Exiting"));
    DecrementAndFetch(&m_transport->m_refCount);
    return 0;
}

/*
 * A thread dedicated to dispatching endpoint exit functions to avoid deadlock
 * and as a handy place to dispatch endpoint deleted events.
 */
ThreadReturn STDCALL UDPTransport::ExitDispatcherThread::Run(void* arg)
{
    QCC_UNUSED(arg);
    IncrementAndFetch(&m_transport->m_refCount);
    QCC_DbgTrace(("UDPTransport::ExitDispatcherThread::Run()"));

    vector<Event*> checkEvents, signaledEvents;
    checkEvents.push_back(&stopEvent);

    while (!IsStopping()) {
        QCC_DbgTrace(("UDPTransport::ExitDispatcherThread::Run(): Wait for some action"));

        signaledEvents.clear();

        /*
         * We should never have a status returned from Event::Wait other than
         * ER_OK since we don't set a timeout.  It is, however, the case that
         * Windows Event implementations may return ER_TIMEOUT even though no
         * timeout was set, and Posix systems may return ER_TIMER_NOT_ALLOWED.
         * If we were to exit in the face of such errors, the whole transport
         * would go down since the dispatcher thread would exit.  All we can do
         * is to hope that any errors are transient and try again.  In that
         * case, we will recover if the system does.  We'll log an error, but
         * there's not really much we can do here.
         */
        QStatus status = Event::Wait(checkEvents, signaledEvents);
        if (status != ER_OK) {
            QCC_LogError(status, ("UDPTransport::ExitDispatcherThread::Run(): Event::Wait failed"));
            continue;
        }

        for (vector<Event*>::iterator i = signaledEvents.begin(); i != signaledEvents.end(); ++i) {
            if (*i == &stopEvent) {
                QCC_DbgTrace(("UDPTransport::ExitDispatcherThread::Run(): Reset stopEvent"));
                stopEvent.ResetEvent();
            }
        }

        bool drained = false;
        do {
            WorkerCommandQueueEntry entry;

            /*
             * Pull an entry that describes what it is we need to do from the
             * queue.
             */
            m_transport->m_exitWorkerCommandQueueLock.Lock(MUTEX_CONTEXT);

            QCC_DbgTrace(("UDPTransport::ExitDispatcherThread::Run(): m_exitWorkerCommandQueue.size()=%d.", m_transport->m_exitWorkerCommandQueue.size()));

            if (m_transport->m_exitWorkerCommandQueue.empty()) {
                drained = true;
            } else {
                entry = m_transport->m_exitWorkerCommandQueue.front();
                m_transport->m_exitWorkerCommandQueue.pop();
            }
            m_transport->m_exitWorkerCommandQueueLock.Unlock(MUTEX_CONTEXT);

            /*
             * We keep at it until we completely drain this queue every time we
             * wake up.
             */
            if (drained == false) {
                QCC_DbgTrace(("UDPTransport::ExitDispatcherThread::Run(): command=%d., handle=%p, conn=%p., connId=%d.,"
                              "rcv=%p, passive=%d., buf=%p, len=%d., status=\"%s\"",
                              entry.m_command, entry.m_handle, entry.m_conn, entry.m_connId,
                              entry.m_rcv, entry.m_passive, entry.m_buf, entry.m_len, QCC_StatusText(entry.m_status)));

                /*
                 * Two possibilities for commands: ENDPOINT_DELETED or EXIT.  If
                 * ENDPOINT_DELETED just call the hook, otherwise we need to
                 * correlate connection ID to endpoint which is a bit more
                 * complicated.
                 */
                if (entry.m_command == WorkerCommandQueueEntry::ENDPOINT_DELETED) {
                    QCC_DbgPrintf(("UDPTransport::ExitDispatcherThread::Run(): ENDPOINT_DELETED: EndpointDeletedHook()"));
                    m_transport->EndpointDeletedHook();
                } else {
                    bool haveLock = true;
                    m_transport->m_endpointListLock.Lock(MUTEX_CONTEXT);
                    for (set<UDPEndpoint>::iterator i = m_transport->m_endpointList.begin(); i != m_transport->m_endpointList.end(); ++i) {
                        UDPEndpoint ep = *i;
                        if (entry.m_connId == ep->GetConnId()) {
                            /*
                             * We can't call out to some possibly windy code path
                             * out through the daemon router with the
                             * m_endpointListLock taken.  But since we are going to
                             * call into the endpoint, we'll bump the reference
                             * count to indicate a thread is coming.  If the ref
                             * count bumped, the endpoint management code will not
                             * kill the endpoint out from under us.
                             */
                            ep->IncrementRefs();
                            m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT);
                            haveLock = false;

                            switch (entry.m_command) {
                            case WorkerCommandQueueEntry::EXIT:
                                {
                                    QCC_DbgPrintf(("UDPTransport::ExitDispatcherThread::Run(): Call ep->Exit().  connId == %d.", ep->GetConnId()));
                                    ep->Exit();
                                    break;
                                }

                            default:
                                {
                                    QCC_ASSERT(false && "UDPTransport::ExitDispatcherThread::Run(): Unexpected command");
                                    break;
                                }
                            }

                            /*
                             * At this point, we assume that we have given the
                             * m_endpointListLock and decremented the thread count
                             * in the endpoint; and our iterator can no longer be
                             * trusted.
                             */
                            ep->DecrementRefs();
                            QCC_ASSERT(haveLock == false && "UDPTransport::ExitDispatcherThread::Run(): Should not have m_endpointListLock here");
                            break;
                        } // if (entry.m_connId == ep->GetConnId())
                    } // for (set<UDPEndpoint>::iterator i ...

                    /*
                     * If we found an endpoint, we gave the lock, did the operation
                     * and broke out of the iterator loop assuming the iterator was
                     * no good any more.  If we did not find the endpoint, we still
                     * have the lock and we need to give it up.
                     */
                    if (haveLock) {
                        m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT);
                    }
                } // else not ENDPOINT_DELETED
            } // if (drained == false)
        } while (drained == false);
    } // while not stoppping

    QCC_DbgTrace(("UDPTransport::ExitDispatcherThread::Run(): Exiting"));
    DecrementAndFetch(&m_transport->m_refCount);
    return 0;
}

/**
 * Start the UDP Transport and prepare it for accepting inbound connections or
 * forming outbound connections.
 */
QStatus UDPTransport::Start()
{
    IncrementAndFetch(&m_refCount);
    QCC_DbgHLPrintf(("UDPTransport::Start()"));

    /*
     * The AllJoyn threading model says exactly one Start() can be done.
     */
    if (IsRunning()) {
        QCC_LogError(ER_BUS_BUS_ALREADY_STARTED, ("UDPTransport::Start(): Already started"));
        DecrementAndFetch(&m_refCount);
        return ER_BUS_BUS_ALREADY_STARTED;
    }

    m_stopping = false;

    /*
     * Get the guid from the bus attachment which will act as the globally unique
     * ID of the daemon.
     */
    qcc::String guidStr = m_bus.GetInternal().GetGlobalGUID().ToString();

    /*
     * We're a UDP transport, and UDP is an IP protocol, so we want to use the IP
     * name service for our advertisement and discovery work.  When we acquire
     * the name service, we are basically bumping a reference count and starting
     * it if required.
     *
     * Start() will legally be called exactly once, but Stop() and Join() may be called
     * multiple times.  Since we are essentially reference counting the name service
     * singleton, we can only call Release() on it once.  So we have a release count
     * variable that allows us to only release the singleton on the first transport
     * Join()
     */
    QCC_DbgPrintf(("UDPTransport::Start(): Acquire instance of NS"));
    m_nsReleaseCount = 0;
    IpNameService::Instance().Acquire(guidStr);

    /*
     * Tell the name service to call us back on our FoundCallback method when
     * we hear about a new well-known bus name.
     */
    QCC_DbgPrintf(("UDPTransport::Start(): Set NS callback"));
    IpNameService::Instance().SetCallback(TRANSPORT_UDP,
                                          new CallbackImpl<FoundCallback, void, const qcc::String&, const qcc::String&, std::vector<qcc::String>&, uint32_t>
                                              (&m_foundCallback, &FoundCallback::Found));

    IpNameService::Instance().SetNetworkEventCallback(TRANSPORT_UDP,
                                                      new CallbackImpl<NetworkEventCallback, void, const std::multimap<qcc::String, qcc::IPAddress>&, bool>
                                                          (&m_networkEventCallback, &NetworkEventCallback::Handler));
    uint32_t availConn = m_maxConn -  m_currConn;
    uint32_t availRemoteClientsUdp = m_maxRemoteClientsUdp - m_numUntrustedClients;
    availRemoteClientsUdp = std::min(availRemoteClientsUdp, availConn);
    IpNameService::Instance().UpdateDynamicScore(TRANSPORT_UDP, availConn, m_maxConn, availRemoteClientsUdp, m_maxRemoteClientsUdp);
    QCC_DbgPrintf(("UDPTransport::Start(): Spin up message dispatcher thread"));
    m_dispatcher = new DispatcherThread(this);
    QStatus status = m_dispatcher->Start(NULL, NULL);
    if (status != ER_OK) {
        QCC_LogError(status, ("UDPTransport::Start(): Failed to Start() message dispatcher thread"));
        DecrementAndFetch(&m_refCount);
        return status;
    }

    QCC_DbgPrintf(("UDPTransport::Start(): Spin up exit dispatcher thread"));
    m_exitDispatcher = new ExitDispatcherThread(this);
    status = m_exitDispatcher->Start(NULL, NULL);
    if (status != ER_OK) {
        QCC_LogError(status, ("UDPTransport::Start(): Failed to Start() exit dispatcher thread"));
        DecrementAndFetch(&m_refCount);
        return status;
    }

    /*
     * Start the maintenance loop through the thread base class.  This will
     * close or open the IsRunning() gate we use to control access to our public
     * API.
     */
    QCC_DbgPrintf(("UDPTransport::Start(): Spin up main thread"));
    status = Thread::Start();
    m_dynamicScoreUpdater.Start();
    DecrementAndFetch(&m_refCount);
    return status;
}

bool operator<(const UDPTransport::ConnectEntry& lhs, const UDPTransport::ConnectEntry& rhs)
{
    return lhs.m_connId < rhs.m_connId;
}

/**
 * Ask all of the threads that may be wandering around in the UDP Transport or
 * its associated endpoints to begin leaving.
 */
QStatus UDPTransport::Stop(void)
{
    IncrementAndFetch(&m_refCount);
    QCC_DbgTrace(("UDPTransport::Stop()"));

    /*
     * It is legal to call Stop() more than once, so it must be possible to
     * call Stop() on a stopped transport.
     */
    m_preListLock.Lock(MUTEX_CONTEXT);
    m_stopping = true;
    m_preListLock.Unlock(MUTEX_CONTEXT);
    /*
     * Tell the name service to disregard all our prior advertisements and
     * discoveries. The internal state will shortly be discarded as well.
     */
    m_listenRequestsLock.Lock(MUTEX_CONTEXT);
    QCC_DbgPrintf(("UDPTransport::Stop(): Gratuitously clean out advertisements."));
    for (list<AdvEntry>::iterator i = m_advertising.begin(); i != m_advertising.end(); ++i) {
        IpNameService::Instance().CancelAdvertiseName(TRANSPORT_UDP, (*i).name, (*i).quietly, TRANSPORT_UDP);
    }
    m_advertising.clear();
    m_routerNameAdvertised = false;
    m_isAdvertising = false;
    QCC_DbgPrintf(("UDPTransport::Stop(): Gratuitously clean out discoveries."));
    for (list<qcc::String>::iterator i = m_discovering.begin(); i != m_discovering.end(); ++i) {
        IpNameService::Instance().CancelFindAdvertisement(TRANSPORT_UDP, *i, TRANSPORT_UDP);
    }
    m_discovering.clear();
    m_isDiscovering = false;
    m_listenRequestsLock.Unlock(MUTEX_CONTEXT);

    /*
     * Tell the name service to stop calling us back if it's there (we may get
     * called more than once in the chain of destruction) so the pointer is not
     * required to be non-NULL.
     */
    QCC_DbgPrintf(("UDPTransport::Stop(): Clear NS callback"));
    IpNameService::Instance().SetCallback(TRANSPORT_UDP, NULL);

    IpNameService::Instance().SetNetworkEventCallback(TRANSPORT_UDP, NULL);

    IpNameService::Instance().UpdateDynamicScore(TRANSPORT_UDP, 0, 0, 0, 0);

    /*
     * Ask any running endpoints to shut down and stop allowing routing to
     * happen through this transport.  The endpoint needs to wake any threads
     * that may be waiting for I/O and arrange for itself to be cleaned up by
     * the maintenance thread.
     */
    QCC_DbgPrintf(("UDPTransport::Stop(): Stop endpoints"));
    m_preListLock.Lock(MUTEX_CONTEXT);
    set<UDPEndpoint>::iterator i = m_preList.begin();
    while (i != m_preList.end()) {
        UDPEndpoint ep = *i;
        m_preListLock.Unlock(MUTEX_CONTEXT);
        /*
         * Since the UDP Transport is going down, we assume the entire routing
         * node is going down for a reason, and we should not be waiting for
         * queued data to make its way out to the remote side.  We don't delay
         * the shutdown process for this reason at all.
         */
        ep->SetEpWaitEnable(false);
        ep->Stop();
        m_preListLock.Lock(MUTEX_CONTEXT);
        i = m_preList.upper_bound(ep);
    }
    m_preListLock.Unlock(MUTEX_CONTEXT);

    m_endpointListLock.Lock(MUTEX_CONTEXT);
    for (set<UDPEndpoint>::iterator i = m_authList.begin(); i != m_authList.end(); ++i) {
        UDPEndpoint ep = *i;
        ep->SetEpWaitEnable(false);
        ep->Stop();
    }
    for (set<UDPEndpoint>::iterator i = m_endpointList.begin(); i != m_endpointList.end(); ++i) {
        UDPEndpoint ep = *i;
        ep->SetEpWaitEnable(false);
        ep->Stop();
    }

    /*
     * If there are any threads blocked trying to connect to a remote host, we
     * need to wake them up so they leave before we actually go away.  We are
     * guaranteed by contract that if there is an entry in the connect threads
     * set, the thread is still there and the event has not been destroyed.
     * This is critical since the event was created on the stack of the
     * connecting thread.  These entries will be verified as being gone in
     * Join().
     */
    QCC_DbgPrintf(("UDPTransport::Stop(): Alert connectThreads"));
    for (set<ConnectEntry>::const_iterator i = m_connectThreads.begin(); i != m_connectThreads.end(); ++i) {
        i->m_event->SetEvent();
    }

    m_endpointListLock.Unlock(MUTEX_CONTEXT);

    m_dynamicScoreUpdater.Stop();
    /*
     * This is the logical place to stop the dispatcher thread and the main
     * server thread, but we might have outstanding writes queued up with ARDP
     * at this point.  The writes come back through callbacks which are driven
     * by the main thread and picked up and executed by the dispatcher thread.
     * We need to keep those puppies running until the number of outstanding
     * writes for all streams drop to zero -- so we do the stop in Join() where
     * we can block until this all happens.  The endpoint Stop() calls above
     * will start the process.
     */
    DecrementAndFetch(&m_refCount);
    return ER_OK;
}

/**
 * Wait for all of the threads that may be wandering around in the UDP Transport
 * or its associated endpoints to complete their cleanup process and leave the
 * transport.  When this method completes, it must be safe to delete the object.
 * Note that this method may be called multiple times.
 */
QStatus UDPTransport::Join(void)
{
    IncrementAndFetch(&m_refCount);
    QCC_DbgTrace(("UDPTransport::Join()"));

    /*
     * The logical place to stop the dispatcher thread and the main server
     * thread would be in Stop(), but we might have outstanding writes queued up
     * with ARDP at that point.  The writes come back through callbacks which
     * are driven by the main thread and picked up and executed by the
     * dispatcher thread.  We need to keep those puppies running until the
     * number of outstanding writes for all streams drop to zero -- so we do the
     * stop here in Join() where we can block until this all happens.  The
     * endpoint Stop() calls in UDPTransport::Stop() will begin the process.  We
     * need to wait for it to complete here.  Since the endpoint manager will be
     * taking care of all of that and then deleting the endpoints, the most
     * straightforward thing to do here is to wait for the endpoints to go away
     * before proceeding with the transport takedown.
     */
    m_endpointListLock.Lock(MUTEX_CONTEXT);
    m_preListLock.Lock(MUTEX_CONTEXT);

    bool passive;
    do {
        passive = m_preList.empty() && m_authList.empty() && m_endpointList.empty();

        if (!passive) {
            m_preListLock.Unlock(MUTEX_CONTEXT);
            m_endpointListLock.Unlock(MUTEX_CONTEXT);
            qcc::Sleep(10);
            m_endpointListLock.Lock(MUTEX_CONTEXT);
            m_preListLock.Lock(MUTEX_CONTEXT);
        }
    } while (!passive);

    m_preListLock.Unlock(MUTEX_CONTEXT);

    m_endpointListLock.Unlock(MUTEX_CONTEXT);

    /*
     * Now that there are no enpoints needin them, we can go ahead and
     * take down the message pumps and dispatcher threads since thre
     * is no more work for them.
     */
    QCC_DbgPrintf(("UDPTransport::Stop(): Stop() message pumps"));
    for (uint32_t i = 0; i < N_PUMPS; ++i) {
        m_messagePumps[i]->Stop();
    }

    QCC_DbgPrintf(("UDPTransport::Join(): Stop message dispatcher thread"));
    if (m_dispatcher) {
        m_dispatcher->Stop();
    }

    QCC_DbgPrintf(("UDPTransport::Join(): Stop exit dispatcher thread"));
    if (m_exitDispatcher) {
        m_exitDispatcher->Stop();
    }

    /*
     * Tell the main server loop thread to shut down.  We'll wait for it to do
     * so below.
     */
    QCC_DbgPrintf(("UDPTransport::Join(): Stop main thread"));
    QStatus status = Thread::Stop();
    if (status != ER_OK) {
        QCC_LogError(status, ("UDPTransport::Join(): Failed to Stop() server thread"));
        DecrementAndFetch(&m_refCount);
        return status;
    }

    /*
     * Join() all of the message pumps.
     */
    QCC_DbgPrintf(("UDPTransport::Join(): Join() message pumps"));
    for (uint32_t i = 0; i < N_PUMPS; ++i) {
        m_messagePumps[i]->Join();
    }

    /*
     * We waited for the dispatcher thread to finish dispatching all in-process
     * sends above, so it has nothing to do now and we can get rid of it.
     */
    QCC_DbgPrintf(("UDPTransport::Join(): Join and delete message dispatcher thread"));
    if (m_dispatcher) {
        m_dispatcher->Join();
        delete m_dispatcher;
        m_dispatcher = NULL;
    }

    QCC_DbgPrintf(("UDPTransport::Join(): Join and delete exit dispatcher thread"));
    if (m_exitDispatcher) {
        m_exitDispatcher->Join();
        delete m_exitDispatcher;
        m_exitDispatcher = NULL;
    }

    /*
     * Now, if we have any message buffers queued up in our own internals it is
     * time to get rid of them.
     */
    QCC_DbgPrintf(("UDPTransport::Join(): Return unused message buffers to ARDP"));
    while (m_workerCommandQueue.empty() == false) {
        WorkerCommandQueueEntry entry = m_workerCommandQueue.front();
        m_workerCommandQueue.pop();
        /*
         * The ARDP module will have allocated memory (in some private way) for
         * any messages that are waiting to be routed.  We can't just ignore
         * that situation or we may leak memory.  Give any buffers back to the
         * protocol before leaving.  The assumption here is that ARDP will do
         * the right think in ARDP_REcvReady() and not require a subsequent
         * call to ARDP_Run() which will not happen since the main thread is
         * Stop()ped.
         */
        if (entry.m_command == WorkerCommandQueueEntry::RECV_CB) {
            m_ardpLock.Lock(MUTEX_CONTEXT);

#ifndef NDEBUG
            QStatus alternateStatus =
#endif
            ARDP_RecvReady(entry.m_handle, entry.m_conn, entry.m_rcv);
#ifndef NDEBUG