aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/ApplicationPlugins/RemoteController/RemoteAdminPlugin.cs
blob: 2e128a708adf2e4b9b1aeca51ee2c628b7519531 (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
/*
 * Copyright (c) Contributors, http://opensimulator.org/
 * See CONTRIBUTORS.TXT for a full list of copyright holders.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the OpenSimulator Project nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Xml;
using System.Net;
using System.Reflection;
using System.Timers;
using System.Threading;
using log4net;
using Nini.Config;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenSim;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Console;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.CoreModules.World.Terrain;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using PermissionMask = OpenSim.Framework.PermissionMask;
using RegionInfo = OpenSim.Framework.RegionInfo;

namespace OpenSim.ApplicationPlugins.RemoteController
{
    public class RemoteAdminPlugin : IApplicationPlugin
    {
        private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        private static bool m_defaultAvatarsLoaded = false;
        private static Object   m_requestLock = new Object();
        private static Object   m_saveOarLock = new Object();

        private OpenSimBase m_application;
        private IHttpServer m_httpServer;
        private IConfig m_config;
        private IConfigSource m_configSource;
        private string m_requiredPassword = String.Empty;
        private HashSet<string> m_accessIP;

        private string m_name = "RemoteAdminPlugin";
        private string m_version = "0.0";
        private string m_openSimVersion;

        public string Version
        {
            get { return m_version; }
        }

        public string Name
        {
            get { return m_name; }
        }

        public void Initialise()
        {
            m_log.Error("[RADMIN]: " + Name + " cannot be default-initialized!");
            throw new PluginNotInitialisedException(Name);
        }

        public void Initialise(OpenSimBase openSim)
        {
            m_openSimVersion = openSim.GetVersionText();

            m_configSource = openSim.ConfigSource.Source;
            try
            {
                if (m_configSource.Configs["RemoteAdmin"] == null ||
                    !m_configSource.Configs["RemoteAdmin"].GetBoolean("enabled", false))
                {
                    // No config or disabled
                }
                else
                {
                    m_config = m_configSource.Configs["RemoteAdmin"];
                    m_log.Debug("[RADMIN]: Remote Admin Plugin Enabled");
                    m_requiredPassword = m_config.GetString("access_password", String.Empty);
                    int port = m_config.GetInt("port", 0);

                    string accessIP = m_config.GetString("access_ip_addresses", String.Empty);
                    m_accessIP = new HashSet<string>();
                    if (accessIP != String.Empty)
                    {
                        string[] ips = accessIP.Split(new char[] { ',' });
                        foreach (string ip in ips)
                        {
                            string current = ip.Trim();

                            if (current != String.Empty)
                                m_accessIP.Add(current);
                        }
                    }

                    m_application = openSim;
                    string bind_ip_address = m_config.GetString("bind_ip_address", "0.0.0.0");
                    IPAddress ipaddr = IPAddress.Parse(bind_ip_address);
                    m_httpServer = MainServer.GetHttpServer((uint)port,ipaddr);

                    Dictionary<string, XmlRpcMethod> availableMethods = new Dictionary<string, XmlRpcMethod>();
                    availableMethods["admin_create_region"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcCreateRegionMethod);
                    availableMethods["admin_delete_region"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcDeleteRegionMethod);
                    availableMethods["admin_close_region"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcCloseRegionMethod);
                    availableMethods["admin_modify_region"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcModifyRegionMethod);
                    availableMethods["admin_region_query"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcRegionQueryMethod);
                    availableMethods["admin_shutdown"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcShutdownMethod);
                    availableMethods["admin_broadcast"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcAlertMethod);
                    availableMethods["admin_dialog"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcDialogMethod);
                    availableMethods["admin_restart"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcRestartMethod);
                    availableMethods["admin_load_heightmap"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcLoadHeightmapMethod);
                    availableMethods["admin_save_heightmap"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcSaveHeightmapMethod);

                    // Agent management
                    availableMethods["admin_get_agents"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcGetAgentsMethod);
                    availableMethods["admin_teleport_agent"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcTeleportAgentMethod);

                    // User management
                    availableMethods["admin_create_user"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcCreateUserMethod);
                    availableMethods["admin_create_user_email"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcCreateUserMethod);
                    availableMethods["admin_exists_user"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcUserExistsMethod);
                    availableMethods["admin_update_user"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcUpdateUserAccountMethod);
                    availableMethods["admin_authenticate_user"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcAuthenticateUserMethod);

                    // Region state management
                    availableMethods["admin_load_xml"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcLoadXMLMethod);
                    availableMethods["admin_save_xml"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcSaveXMLMethod);
                    availableMethods["admin_load_oar"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcLoadOARMethod);
                    availableMethods["admin_save_oar"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcSaveOARMethod);

                    // Estate access list management
                    availableMethods["admin_acl_clear"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcAccessListClear);
                    availableMethods["admin_acl_add"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcAccessListAdd);
                    availableMethods["admin_acl_remove"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcAccessListRemove);
                    availableMethods["admin_acl_list"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcAccessListList);
                    availableMethods["admin_estate_reload"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcEstateReload);

                    // Misc
                    availableMethods["admin_refresh_search"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcRefreshSearch);
                    availableMethods["admin_refresh_map"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcRefreshMap);
                    availableMethods["admin_get_opensim_version"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcGetOpenSimVersion);
                    availableMethods["admin_get_agent_count"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcGetAgentCount);

                    // Either enable full remote functionality or just selected features
                    string enabledMethods = m_config.GetString("enabled_methods", "all");

                    // To get this, you must explicitly specify "all" or
                    // mention it in a whitelist. It won't be available
                    // If you just leave the option out!
                    //
                    if (!String.IsNullOrEmpty(enabledMethods))
                        availableMethods["admin_console_command"] = (req, ep) => InvokeXmlRpcMethod(req, ep, XmlRpcConsoleCommandMethod);

                    // The assumption here is that simply enabling Remote Admin as before will produce the same
                    // behavior - enable all methods unless the whitelist is in place for backward-compatibility.
                    if (enabledMethods.ToLower() == "all" || String.IsNullOrEmpty(enabledMethods))
                    {
                        foreach (string method in availableMethods.Keys)
                        {
                            m_httpServer.AddXmlRPCHandler(method, availableMethods[method], false);
                        }
                    }
                    else
                    {
                        foreach (string enabledMethod in enabledMethods.Split('|'))
                        {
                            m_httpServer.AddXmlRPCHandler(enabledMethod, availableMethods[enabledMethod], false);
                        }
                    }
                }
            }
            catch (NullReferenceException)
            {
                // Ignore.
            }
        }

        public void PostInitialise()
        {
            if (!CreateDefaultAvatars())
            {
                m_log.Info("[RADMIN]: Default avatars not loaded");
            }
        }

        /// <summary>
        /// Invoke an XmlRpc method with the standard actions (password check, etc.)
        /// </summary>
        /// <param name="method"></param>
        private XmlRpcResponse InvokeXmlRpcMethod(
            XmlRpcRequest request, IPEndPoint remoteClient, Action<XmlRpcRequest, XmlRpcResponse, IPEndPoint> method)
        {
            XmlRpcResponse response = new XmlRpcResponse();
            Hashtable responseData = new Hashtable();
            response.Value = responseData;

            try
            {
                Hashtable requestData = (Hashtable) request.Params[0];

                CheckStringParameters(requestData, responseData, new string[] {"password"});

                FailIfRemoteAdminNotAllowed((string)requestData["password"], responseData, remoteClient.Address.ToString());

                method(request, response, remoteClient);
            }
            catch (Exception e)
            {
                m_log.ErrorFormat(
                    "[RADMIN]: Method {0} failed.  Exception {1}{2}", request.MethodName, e.Message, e.StackTrace);

                responseData["success"] = false;
                responseData["error"] = e.Message;
            }

            return response;
        }

        private void FailIfRemoteAdminNotAllowed(string password, Hashtable responseData, string check_ip_address)
        {
            if (m_accessIP.Count > 0 && !m_accessIP.Contains(check_ip_address))
            {
                m_log.WarnFormat("[RADMIN]: Unauthorized access blocked from IP {0}", check_ip_address);
                responseData["accepted"] = false;
                throw new Exception("not authorized");
            }

            if (m_requiredPassword != String.Empty && password != m_requiredPassword)
            {
                m_log.WarnFormat("[RADMIN]: Wrong password, blocked access from IP {0}", check_ip_address);
                responseData["accepted"] = false;
                throw new Exception("wrong password");
            }
        }

        private void XmlRpcRestartMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
        {
            Hashtable responseData = (Hashtable)response.Value;
            Hashtable requestData = (Hashtable)request.Params[0];

            try
            {
                Scene rebootedScene = null;
                bool restartAll = false;

                IConfig startupConfig = m_configSource.Configs["Startup"];
                if (startupConfig != null)
                {
                    if (startupConfig.GetBoolean("InworldRestartShutsDown", false))
                    {
                        rebootedScene = m_application.SceneManager.CurrentOrFirstScene;
                        restartAll = true;
                    }
                }

                if (rebootedScene == null)
                {
                    CheckRegionParams(requestData, responseData);

                    GetSceneFromRegionParams(requestData, responseData, out rebootedScene);
                }

                IRestartModule restartModule = rebootedScene.RequestModuleInterface<IRestartModule>();

                responseData["success"] = false;
                responseData["accepted"] = true;
                responseData["rebooting"] = true;

                string message;
                List<int> times = new List<int>();

                if (requestData.ContainsKey("alerts"))
                {
                    string[] alertTimes = requestData["alerts"].ToString().Split( new char[] {','});
                    if (alertTimes.Length == 1 && Convert.ToInt32(alertTimes[0]) == -1)
                    {
                        m_log.Info("[RADMIN]: Request to cancel restart.");

                        if (restartModule != null)
                        {
                            message = "Restart has been cancelled";

                            if (requestData.ContainsKey("message"))
                                message = requestData["message"].ToString();

                            restartModule.AbortRestart(message);

                            responseData["success"] = true;
                            responseData["rebooting"] = false;

                            return;
                        }
                    }
                    foreach (string a in alertTimes)
                        times.Add(Convert.ToInt32(a));
                }
                else
                {
                    int timeout = 30;
                    if (requestData.ContainsKey("milliseconds"))
                        timeout = Int32.Parse(requestData["milliseconds"].ToString()) / 1000;
                    while (timeout > 0)
                    {
                        times.Add(timeout);
                        if (timeout > 300)
                            timeout -= 120;
                        else if (timeout > 30)
                            timeout -= 30;
                        else
                            timeout -= 15;
                    }
                }

                m_log.Info("[RADMIN]: Request to restart Region.");

                message = "Region is restarting in {0}. Please save what you are doing and log out.";

                if (requestData.ContainsKey("message"))
                    message = requestData["message"].ToString();

                bool notice = true;
                if (requestData.ContainsKey("noticetype")
                    && ((string)requestData["noticetype"] == "dialog"))
                {
                    notice = false;
                }

                List<Scene> restartList;

                if (restartAll)
                    restartList = m_application.SceneManager.Scenes;
                else
                    restartList = new List<Scene>() { rebootedScene };

                foreach (Scene s in m_application.SceneManager.Scenes)
                {
                    restartModule = s.RequestModuleInterface<IRestartModule>();
                    if (restartModule != null)
                        restartModule.ScheduleRestart(UUID.Zero, message, times.ToArray(), notice);
                }
                responseData["success"] = true;
            }
            catch (Exception e)
            {
//                m_log.ErrorFormat("[RADMIN]: Restart region: failed: {0} {1}", e.Message, e.StackTrace);
                responseData["rebooting"] = false;

                throw e;
            }

            m_log.Info("[RADMIN]: Restart Region request complete");
        }

        private void XmlRpcAlertMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
        {
            m_log.Info("[RADMIN]: Alert request started");

            Hashtable responseData = (Hashtable)response.Value;
            Hashtable requestData = (Hashtable)request.Params[0];

            string message = (string) requestData["message"];
            m_log.InfoFormat("[RADMIN]: Broadcasting: {0}", message);

            responseData["accepted"] = true;
            responseData["success"] = true;

            m_application.SceneManager.ForEachScene(
                delegate(Scene scene)
                    {
                        IDialogModule dialogModule = scene.RequestModuleInterface<IDialogModule>();
                        if (dialogModule != null)
                            dialogModule.SendGeneralAlert(message);
                    });

            m_log.Info("[RADMIN]: Alert request complete");
        }

        public void XmlRpcDialogMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
        {
            Hashtable responseData = (Hashtable)response.Value;

            m_log.Info("[RADMIN]: Dialog request started");

            Hashtable requestData = (Hashtable)request.Params[0];

            string message = (string)requestData["message"];
            string fromuuid = (string)requestData["from"];
            m_log.InfoFormat("[RADMIN]: Broadcasting: {0}", message);

            responseData["accepted"] = true;
            responseData["success"] = true;

            m_application.SceneManager.ForEachScene(
                delegate(Scene scene)
                {
                    IDialogModule dialogModule = scene.RequestModuleInterface<IDialogModule>();
                    if (dialogModule != null)
                        dialogModule.SendNotificationToUsersInRegion(UUID.Zero, fromuuid, message);
                });

            m_log.Info("[RADMIN]: Dialog request complete");
        }

        private void XmlRpcLoadHeightmapMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
        {
            m_log.Info("[RADMIN]: Load height maps request started");

            Hashtable responseData = (Hashtable)response.Value;
            Hashtable requestData = (Hashtable)request.Params[0];

//                m_log.DebugFormat("[RADMIN]: Load Terrain: XmlRpc {0}", request);
            // foreach (string k in requestData.Keys)
            // {
            //     m_log.DebugFormat("[RADMIN]: Load Terrain: XmlRpc {0}: >{1}< {2}",
            //                       k, (string)requestData[k], ((string)requestData[k]).Length);
            // }

            CheckStringParameters(requestData, responseData, new string[] { "filename" });
            CheckRegionParams(requestData, responseData);

            Scene scene = null;
            GetSceneFromRegionParams(requestData, responseData, out scene);

            if (scene != null)
            {
                string file = (string)requestData["filename"];

                responseData["accepted"] = true;

                LoadHeightmap(file, scene.RegionInfo.RegionID);

                responseData["success"] = true;
            }
            else
            {
                responseData["success"] = false;
            }

            m_log.Info("[RADMIN]: Load height maps request complete");
        }

        private void XmlRpcSaveHeightmapMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
        {
            m_log.Info("[RADMIN]: Save height maps request started");

            Hashtable responseData = (Hashtable)response.Value;
            Hashtable requestData = (Hashtable)request.Params[0];

//                m_log.DebugFormat("[RADMIN]: Save Terrain: XmlRpc {0}", request.ToString());

            CheckStringParameters(requestData, responseData, new string[] { "filename" });
            CheckRegionParams(requestData, responseData);

            Scene scene = null;
            GetSceneFromRegionParams(requestData, responseData, out scene);

            if (scene != null)
            {
                string file = (string)requestData["filename"];
                m_log.InfoFormat("[RADMIN]: Terrain Saving: {0}", file);

                responseData["accepted"] = true;

                ITerrainModule terrainModule = scene.RequestModuleInterface<ITerrainModule>();
                if (null == terrainModule) throw new Exception("terrain module not available");

                terrainModule.SaveToFile(file);

                responseData["success"] = true;
            }
            else
            {
                responseData["success"] = false;
            }

            m_log.Info("[RADMIN]: Save height maps request complete");
        }

        private void XmlRpcShutdownMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
        {
            m_log.Info("[RADMIN]: Received Shutdown Administrator Request");

            Hashtable responseData = (Hashtable)response.Value;
            Hashtable requestData = (Hashtable)request.Params[0];

            responseData["accepted"] = true;
            response.Value = responseData;

            int timeout = 2000;
            string message;

            if (requestData.ContainsKey("shutdown")
                && ((string) requestData["shutdown"] == "delayed")
                && requestData.ContainsKey("milliseconds"))
            {
                timeout = Int32.Parse(requestData["milliseconds"].ToString());

                message
                    = "Region is going down in " + ((int) (timeout/1000)).ToString()
                      + " second(s). Please save what you are doing and log out.";
            }
            else
            {
                message = "Region is going down now.";
            }

            if (requestData.ContainsKey("noticetype")
                && ((string) requestData["noticetype"] == "dialog"))
            {
                m_application.SceneManager.ForEachScene(

                delegate(Scene scene)
                {
                    IDialogModule dialogModule = scene.RequestModuleInterface<IDialogModule>();
                    if (dialogModule != null)
                            dialogModule.SendNotificationToUsersInRegion(UUID.Zero, "System", message);
                });
            }
            else
            {
                if (!requestData.ContainsKey("noticetype")
                    || ((string)requestData["noticetype"] != "none"))
                {
                    m_application.SceneManager.ForEachScene(
                    delegate(Scene scene)
                    {
                        IDialogModule dialogModule = scene.RequestModuleInterface<IDialogModule>();
                        if (dialogModule != null)
                            dialogModule.SendGeneralAlert(message);
                    });
                }
            }

            // Perform shutdown
            System.Timers.Timer shutdownTimer = new System.Timers.Timer(timeout); // Wait before firing
            shutdownTimer.AutoReset = false;
            shutdownTimer.Elapsed += new ElapsedEventHandler(shutdownTimer_Elapsed);
            lock (shutdownTimer)
            {
                shutdownTimer.Start();
            }

            responseData["success"] = true;
            
            m_log.Info("[RADMIN]: Shutdown Administrator Request complete");
        }

        private void shutdownTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            m_application.Shutdown();
        }

        /// <summary>
        /// Create a new region.
        /// <summary>
        /// <param name="request">incoming XML RPC request</param>
        /// <remarks>
        /// XmlRpcCreateRegionMethod takes the following XMLRPC
        /// parameters
        /// <list type="table">
        /// <listheader><term>parameter name</term><description>description</description></listheader>
        /// <item><term>password</term>
        ///       <description>admin password as set in OpenSim.ini</description></item>
        /// <item><term>region_name</term>
        ///       <description>desired region name</description></item>
        /// <item><term>region_id</term>
        ///       <description>(optional) desired region UUID</description></item>
        /// <item><term>region_x</term>
        ///       <description>desired region X coordinate (integer)</description></item>
        /// <item><term>region_y</term>
        ///       <description>desired region Y coordinate (integer)</description></item>
        /// <item><term>estate_owner_first</term>
        ///       <description>firstname of estate owner (formerly region master)
        ///       (required if new estate is being created, optional otherwise)</description></item>
        /// <item><term>estate_owner_last</term>
        ///       <description>lastname of estate owner (formerly region master)
        ///       (required if new estate is being created, optional otherwise)</description></item>
        /// <item><term>estate_owner_uuid</term>
        ///       <description>explicit UUID to use for estate owner (optional)</description></item>
        /// <item><term>listen_ip</term>
        ///       <description>internal IP address (dotted quad)</description></item>
        /// <item><term>listen_port</term>
        ///       <description>internal port (integer)</description></item>
        /// <item><term>external_address</term>
        ///       <description>external IP address</description></item>
        /// <item><term>persist</term>
        ///       <description>if true, persist the region info
        ///       ('true' or 'false')</description></item>
        /// <item><term>public</term>
        ///       <description>if true, the region is public
        ///       ('true' or 'false') (optional, default: true)</description></item>
        /// <item><term>enable_voice</term>
        ///       <description>if true, enable voice on all parcels,
        ///       ('true' or 'false') (optional, default: false)</description></item>
        /// <item><term>estate_name</term>
        ///       <description>the name of the estate to join (or to create if it doesn't
        ///       already exist)</description></item>
        /// <item><term>region_file</term>
        ///       <description>The name of the file to persist the region specifications to.
        /// If omitted, the region_file_template setting from OpenSim.ini will be used. (optional)</description></item>
        /// </list>
        ///
        /// XmlRpcCreateRegionMethod returns
        /// <list type="table">
        /// <listheader><term>name</term><description>description</description></listheader>
        /// <item><term>success</term>
        ///       <description>true or false</description></item>
        /// <item><term>error</term>
        ///       <description>error message if success is false</description></item>
        /// <item><term>region_uuid</term>
        ///       <description>UUID of the newly created region</description></item>
        /// <item><term>region_name</term>
        ///       <description>name of the newly created region</description></item>
        /// </list>
        /// </remarks>
        private void XmlRpcCreateRegionMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
        {
            m_log.Info("[RADMIN]: CreateRegion: new request");

            Hashtable responseData = (Hashtable)response.Value;
            Hashtable requestData = (Hashtable)request.Params[0];

            lock (m_requestLock)
            {
                int  m_regionLimit = m_config.GetInt("region_limit", 0);
                bool m_enableVoiceForNewRegions = m_config.GetBoolean("create_region_enable_voice", false);
                bool m_publicAccess = m_config.GetBoolean("create_region_public", true);

                CheckStringParameters(requestData, responseData, new string[]
                                                   {
                                                       "region_name",
                                                       "listen_ip", "external_address",
                                                       "estate_name"
                                                   });
                CheckIntegerParams(requestData, responseData, new string[] {"region_x", "region_y", "listen_port"});

                // check whether we still have space left (iff we are using limits)
                if (m_regionLimit != 0 && m_application.SceneManager.Scenes.Count >= m_regionLimit)
                    throw new Exception(String.Format("cannot instantiate new region, server capacity {0} already reached; delete regions first",
                                                      m_regionLimit));
                // extract or generate region ID now
                Scene scene = null;
                UUID regionID = UUID.Zero;
                if (requestData.ContainsKey("region_id") &&
                    !String.IsNullOrEmpty((string) requestData["region_id"]))
                {
                    regionID = (UUID) (string) requestData["region_id"];
                    if (m_application.SceneManager.TryGetScene(regionID, out scene))
                        throw new Exception(
                            String.Format("region UUID already in use by region {0}, UUID {1}, <{2},{3}>",
                                          scene.RegionInfo.RegionName, scene.RegionInfo.RegionID,
                                          scene.RegionInfo.RegionLocX, scene.RegionInfo.RegionLocY));
                }
                else
                {
                    regionID = UUID.Random();
                    m_log.DebugFormat("[RADMIN] CreateRegion: new region UUID {0}", regionID);
                }

                // create volatile or persistent region info
                RegionInfo region = new RegionInfo();

                region.RegionID = regionID;
                region.originRegionID = regionID;
                region.RegionName = (string) requestData["region_name"];
                region.RegionLocX = Convert.ToUInt32(requestData["region_x"]);
                region.RegionLocY = Convert.ToUInt32(requestData["region_y"]);

                // check for collisions: region name, region UUID,
                // region location
                if (m_application.SceneManager.TryGetScene(region.RegionName, out scene))
                    throw new Exception(
                        String.Format("region name already in use by region {0}, UUID {1}, <{2},{3}>",
                                      scene.RegionInfo.RegionName, scene.RegionInfo.RegionID,
                                      scene.RegionInfo.RegionLocX, scene.RegionInfo.RegionLocY));

                if (m_application.SceneManager.TryGetScene(region.RegionLocX, region.RegionLocY, out scene))
                    throw new Exception(
                        String.Format("region location <{0},{1}> already in use by region {2}, UUID {3}, <{4},{5}>",
                                      region.RegionLocX, region.RegionLocY,
                                      scene.RegionInfo.RegionName, scene.RegionInfo.RegionID,
                                      scene.RegionInfo.RegionLocX, scene.RegionInfo.RegionLocY));

                region.InternalEndPoint =
                    new IPEndPoint(IPAddress.Parse((string) requestData["listen_ip"]), 0);

                region.InternalEndPoint.Port = Convert.ToInt32(requestData["listen_port"]);
                if (0 == region.InternalEndPoint.Port) throw new Exception("listen_port is 0");
                if (m_application.SceneManager.TryGetScene(region.InternalEndPoint, out scene))
                    throw new Exception(
                        String.Format(
                            "region internal IP {0} and port {1} already in use by region {2}, UUID {3}, <{4},{5}>",
                            region.InternalEndPoint.Address,
                            region.InternalEndPoint.Port,
                            scene.RegionInfo.RegionName, scene.RegionInfo.RegionID,
                            scene.RegionInfo.RegionLocX, scene.RegionInfo.RegionLocY));

                region.ExternalHostName = (string) requestData["external_address"];

                bool persist = Convert.ToBoolean(requestData["persist"]);
                if (persist)
                {
                    // default place for region configuration files is in the
                    // Regions directory of the config dir (aka /bin)
                    string regionConfigPath = Path.Combine(Util.configDir(), "Regions");
                    try
                    {
                        // OpenSim.ini can specify a different regions dir
                        IConfig startupConfig = (IConfig) m_configSource.Configs["Startup"];
                        regionConfigPath = startupConfig.GetString("regionload_regionsdir", regionConfigPath).Trim();
                    }
                    catch (Exception)
                    {
                        // No INI setting recorded.
                    }
                    
                    string regionIniPath;
                    
                    if (requestData.Contains("region_file"))
                    {
                        // Make sure that the file to be created is in a subdirectory of the region storage directory.
                        string requestedFilePath = Path.Combine(regionConfigPath, (string) requestData["region_file"]);
                        string requestedDirectory = Path.GetDirectoryName(Path.GetFullPath(requestedFilePath));
                        if (requestedDirectory.StartsWith(Path.GetFullPath(regionConfigPath)))
                            regionIniPath = requestedFilePath;
                        else
                            throw new Exception("Invalid location for region file.");
                    }
                    else
                    {
                        regionIniPath = Path.Combine(regionConfigPath,
                                                        String.Format(
                                                            m_config.GetString("region_file_template",
                                                                               "{0}x{1}-{2}.ini"),
                                                            region.RegionLocX.ToString(),
                                                            region.RegionLocY.ToString(),
                                                            regionID.ToString(),
                                                            region.InternalEndPoint.Port.ToString(),
                                                            region.RegionName.Replace(" ", "_").Replace(":", "_").
                                                                Replace("/", "_")));
                    }
                    
                    m_log.DebugFormat("[RADMIN] CreateRegion: persisting region {0} to {1}",
                                      region.RegionID, regionIniPath);
                    region.SaveRegionToFile("dynamic region", regionIniPath);
                }
                else
                {
                    region.Persistent = false;
                }
                    
                // Set the estate
                
                // Check for an existing estate
                List<int> estateIDs = m_application.EstateDataService.GetEstates((string) requestData["estate_name"]);
                if (estateIDs.Count < 1)
                {
                    UUID userID = UUID.Zero;
                    if (requestData.ContainsKey("estate_owner_uuid"))
                    {
                        // ok, client wants us to use an explicit UUID
                        // regardless of what the avatar name provided
                        userID = new UUID((string) requestData["estate_owner_uuid"]);
                        
                        // Check that the specified user exists
                        Scene currentOrFirst = m_application.SceneManager.CurrentOrFirstScene;
                        IUserAccountService accountService = currentOrFirst.UserAccountService;
                        UserAccount user = accountService.GetUserAccount(currentOrFirst.RegionInfo.ScopeID, userID);
                        
                        if (user == null)
                            throw new Exception("Specified user was not found.");
                    }
                    else if (requestData.ContainsKey("estate_owner_first") & requestData.ContainsKey("estate_owner_last"))
                    {
                        // We need to look up the UUID for the avatar with the provided name.
                        string ownerFirst = (string) requestData["estate_owner_first"];
                        string ownerLast = (string) requestData["estate_owner_last"];
                        
                        Scene currentOrFirst = m_application.SceneManager.CurrentOrFirstScene;
                        IUserAccountService accountService = currentOrFirst.UserAccountService;
                        UserAccount user = accountService.GetUserAccount(currentOrFirst.RegionInfo.ScopeID,
                                                                           ownerFirst, ownerLast);
                        
                        // Check that the specified user exists
                        if (user == null)
                            throw new Exception("Specified user was not found.");
                        
                        userID = user.PrincipalID;
                    }
                    else
                    {
                        throw new Exception("Estate owner details not provided.");
                    }
                    
                    // Create a new estate with the name provided
                    region.EstateSettings = m_application.EstateDataService.CreateNewEstate();

                    region.EstateSettings.EstateName = (string) requestData["estate_name"];
                    region.EstateSettings.EstateOwner = userID;
                    // Persistence does not seem to effect the need to save a new estate
                    region.EstateSettings.Save();

                    if (!m_application.EstateDataService.LinkRegion(region.RegionID, (int) region.EstateSettings.EstateID))
                        throw new Exception("Failed to join estate.");
                }
                else
                {
                    int estateID = estateIDs[0];

                    region.EstateSettings = m_application.EstateDataService.LoadEstateSettings(region.RegionID, false);

                    if (region.EstateSettings.EstateID != estateID)
                    {
                        // The region is already part of an estate, but not the one we want.
                        region.EstateSettings = m_application.EstateDataService.LoadEstateSettings(estateID);

                        if (!m_application.EstateDataService.LinkRegion(region.RegionID, estateID))
                            throw new Exception("Failed to join estate.");
                    }
                }
                
                // Create the region and perform any initial initialization

                IScene newScene;
                m_application.CreateRegion(region, out newScene);
                newScene.Start();

                // If an access specification was provided, use it.
                // Otherwise accept the default.
                newScene.RegionInfo.EstateSettings.PublicAccess = GetBoolean(requestData, "public", m_publicAccess);
                newScene.RegionInfo.EstateSettings.Save();

                // enable voice on newly created region if
                // requested by either the XmlRpc request or the
                // configuration
                if (GetBoolean(requestData, "enable_voice", m_enableVoiceForNewRegions))
                {
                    List<ILandObject> parcels = ((Scene)newScene).LandChannel.AllParcels();

                    foreach (ILandObject parcel in parcels)
                    {
                        parcel.LandData.Flags |= (uint) ParcelFlags.AllowVoiceChat;
                        parcel.LandData.Flags |= (uint) ParcelFlags.UseEstateVoiceChan;
                        ((Scene)newScene).LandChannel.UpdateLandObject(parcel.LandData.LocalID, parcel.LandData);
                    }
                }

                //Load Heightmap if specified to new region
                if (requestData.Contains("heightmap_file"))
                {
                    LoadHeightmap((string)requestData["heightmap_file"], region.RegionID);
                }

                responseData["success"] = true;
                responseData["region_name"] = region.RegionName;
                responseData["region_id"] = region.RegionID.ToString();

                m_log.Info("[RADMIN]: CreateRegion: request complete");
            }
        }

        /// <summary>
        /// Delete a new region.
        /// <summary>
        /// <param name="request">incoming XML RPC request</param>
        /// <remarks>
        /// XmlRpcDeleteRegionMethod takes the following XMLRPC
        /// parameters
        /// <list type="table">
        /// <listheader><term>parameter name</term><description>description</description></listheader>
        /// <item><term>password</term>
        ///       <description>admin password as set in OpenSim.ini</description></item>
        /// <item><term>region_name</term>
        ///       <description>desired region name</description></item>
        /// <item><term>region_id</term>
        ///       <description>(optional) desired region UUID</description></item>
        /// </list>
        ///
        /// XmlRpcDeleteRegionMethod returns
        /// <list type="table">
        /// <listheader><term>name</term><description>description</description></listheader>
        /// <item><term>success</term>
        ///       <description>true or false</description></item>
        /// <item><term>error</term>
        ///       <description>error message if success is false</description></item>
        /// </list>
        /// </remarks>
        private void XmlRpcDeleteRegionMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
        {
            m_log.Info("[RADMIN]: DeleteRegion: new request");

            Hashtable responseData = (Hashtable)response.Value;
            Hashtable requestData = (Hashtable)request.Params[0];

            lock (m_requestLock)
            {
                CheckStringParameters(requestData, responseData, new string[] {"region_name"});
                CheckRegionParams(requestData, responseData);

                Scene scene = null;
                GetSceneFromRegionParams(requestData, responseData, out scene);

                m_application.RemoveRegion(scene, true);

                responseData["success"] = true;
                responseData["region_name"] = scene.RegionInfo.RegionName;
                responseData["region_id"] = scene.RegionInfo.RegionID;

                m_log.Info("[RADMIN]: DeleteRegion: request complete");
            }
        }

        /// <summary>
        /// Close a region.
        /// <summary>
        /// <param name="request">incoming XML RPC request</param>
        /// <remarks>
        /// XmlRpcCloseRegionMethod takes the following XMLRPC
        /// parameters
        /// <list type="table">
        /// <listheader><term>parameter name</term><description>description</description></listheader>
        /// <item><term>password</term>
        ///       <description>admin password as set in OpenSim.ini</description></item>
        /// <item><term>region_name</term>
        ///       <description>desired region name</description></item>
        /// <item><term>region_id</term>
        ///       <description>(optional) desired region UUID</description></item>
        /// </list>
        ///
        /// XmlRpcShutdownRegionMethod returns
        /// <list type="table">
        /// <listheader><term>name</term><description>description</description></listheader>
        /// <item><term>success</term>
        ///       <description>true or false</description></item>
        /// <item><term>region_name</term>
        ///       <description>the region name if success is true</description></item>
        /// <item><term>error</term>
        ///       <description>error message if success is false</description></item>
        /// </list>
        /// </remarks>
        private void XmlRpcCloseRegionMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
        {
            m_log.Info("[RADMIN]: CloseRegion: new request");

            Hashtable responseData = (Hashtable)response.Value;
            Hashtable requestData = (Hashtable)request.Params[0];

            lock (m_requestLock)
            {
                CheckRegionParams(requestData, responseData);

                Scene scene = null;
                GetSceneFromRegionParams(requestData, responseData, out scene);

                m_application.CloseRegion(scene);

                responseData["success"] = true;
                responseData["region_name"] = scene.RegionInfo.RegionName;
                responseData["region_id"] = scene.RegionInfo.RegionID;

                response.Value = responseData;

                m_log.Info("[RADMIN]: CloseRegion: request complete");
            }
        }

        /// <summary>
        /// Change characteristics of an existing region.
        /// <summary>
        /// <param name="request">incoming XML RPC request</param>
        /// <remarks>
        /// XmlRpcModifyRegionMethod takes the following XMLRPC
        /// parameters
        /// <list type="table">
        /// <listheader><term>parameter name</term><description>description</description></listheader>
        /// <item><term>password</term>
        ///       <description>admin password as set in OpenSim.ini</description></item>
        /// <item><term>region_name</term>
        ///       <description>desired region name</description></item>
        /// <item><term>region_id</term>
        ///       <description>(optional) desired region UUID</description></item>
        /// <item><term>public</term>
        ///       <description>if true, set the region to public
        ///       ('true' or 'false'), else to private</description></item>
        /// <item><term>enable_voice</term>
        ///       <description>if true, enable voice on all parcels of
        ///       the region, else disable</description></item>
        /// </list>
        ///
        /// XmlRpcModifyRegionMethod returns
        /// <list type="table">
        /// <listheader><term>name</term><description>description</description></listheader>
        /// <item><term>success</term>
        ///       <description>true or false</description></item>
        /// <item><term>error</term>
        ///       <description>error message if success is false</description></item>
        /// </list>
        /// </remarks>
        private void XmlRpcModifyRegionMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
        {
            m_log.Info("[RADMIN]: ModifyRegion: new request");

            Hashtable responseData = (Hashtable)response.Value;
            Hashtable requestData = (Hashtable)request.Params[0];

            lock (m_requestLock)
            {
                CheckRegionParams(requestData, responseData);

                Scene scene = null;
                GetSceneFromRegionParams(requestData, responseData, out scene);

                // Modify access
                scene.RegionInfo.EstateSettings.PublicAccess =
                    GetBoolean(requestData,"public", scene.RegionInfo.EstateSettings.PublicAccess);
                if (scene.RegionInfo.Persistent)
                    scene.RegionInfo.EstateSettings.Save();

                if (requestData.ContainsKey("enable_voice"))
                {
                    bool enableVoice = GetBoolean(requestData, "enable_voice", true);
                    List<ILandObject> parcels = ((Scene)scene).LandChannel.AllParcels();

                    foreach (ILandObject parcel in parcels)
                    {
                        if (enableVoice)
                        {
                            parcel.LandData.Flags |= (uint)ParcelFlags.AllowVoiceChat;
                            parcel.LandData.Flags |= (uint)ParcelFlags.UseEstateVoiceChan;
                        }
                        else
                        {
                            parcel.LandData.Flags &= ~(uint)ParcelFlags.AllowVoiceChat;
                            parcel.LandData.Flags &= ~(uint)ParcelFlags.UseEstateVoiceChan;
                        }
                        scene.LandChannel.UpdateLandObject(parcel.LandData.LocalID, parcel.LandData);
                    }
                }

                responseData["success"] = true;
                responseData["region_name"] = scene.RegionInfo.RegionName;
                responseData["region_id"] = scene.RegionInfo.RegionID;

                m_log.Info("[RADMIN]: ModifyRegion: request complete");
            }
        }

        /// <summary>
        /// Create a new user account.
        /// <summary>
        /// <param name="request">incoming XML RPC request</param>
        /// <remarks>
        /// XmlRpcCreateUserMethod takes the following XMLRPC
        /// parameters
        /// <list type="table">
        /// <listheader><term>parameter name</term><description>description</description></listheader>
        /// <item><term>password</term>
        ///       <description>admin password as set in OpenSim.ini</description></item>
        /// <item><term>user_firstname</term>
        ///       <description>avatar's first name</description></item>
        /// <item><term>user_lastname</term>
        ///       <description>avatar's last name</description></item>
        /// <item><term>user_password</term>
        ///       <description>avatar's password</description></item>
        /// <item><term>user_email</term>
        ///       <description>email of the avatar's owner (optional)</description></item>
        /// <item><term>start_region_x</term>
        ///       <description>avatar's start region coordinates, X value</description></item>
        /// <item><term>start_region_y</term>
        ///       <description>avatar's start region coordinates, Y value</description></item>
        /// </list>
        ///
        /// XmlRpcCreateUserMethod returns
        /// <list type="table">
        /// <listheader><term>name</term><description>description</description></listheader>
        /// <item><term>success</term>
        ///       <description>true or false</description></item>
        /// <item><term>error</term>
        ///       <description>error message if success is false</description></item>
        /// <item><term>avatar_uuid</term>
        ///       <description>UUID of the newly created avatar
        ///                    account; UUID.Zero if failed.
        ///       </description></item>
        /// </list>
        /// </remarks>
        private void XmlRpcCreateUserMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
        {
            m_log.Info("[RADMIN]: CreateUser: new request");

            Hashtable responseData = (Hashtable)response.Value;
            Hashtable requestData = (Hashtable)request.Params[0];

            lock (m_requestLock)
            {
                try
                {
                    // check completeness
                    CheckStringParameters(requestData, responseData, new string[]
                                                       {
                                                           "user_firstname",
                                                           "user_lastname", "user_password",
                                                       });
                    CheckIntegerParams(requestData, responseData, new string[] {"start_region_x", "start_region_y"});

                    // do the job
                    string firstName = (string) requestData["user_firstname"];
                    string lastName = (string) requestData["user_lastname"];
                    string password = (string) requestData["user_password"];

                    uint regionXLocation = Convert.ToUInt32(requestData["start_region_x"]);
                    uint regionYLocation = Convert.ToUInt32(requestData["start_region_y"]);

                    string email = ""; // empty string for email
                    if (requestData.Contains("user_email"))
                        email = (string)requestData["user_email"];

                    Scene scene = m_application.SceneManager.CurrentOrFirstScene;
                    UUID scopeID = scene.RegionInfo.ScopeID;

                    UserAccount account = CreateUser(scopeID, firstName, lastName, password, email);

                    if (null == account)
                        throw new Exception(String.Format("failed to create new user {0} {1}",
                                                          firstName, lastName));

                    // Set home position

                    GridRegion home = scene.GridService.GetRegionByPosition(scopeID, 
                                        (int)Util.RegionToWorldLoc(regionXLocation), (int)Util.RegionToWorldLoc(regionYLocation));
                    if (null == home)
                    {
                        m_log.WarnFormat("[RADMIN]: Unable to set home region for newly created user account {0} {1}", firstName, lastName);
                    }
                    else
                    {
                        scene.GridUserService.SetHome(account.PrincipalID.ToString(), home.RegionID, new Vector3(128, 128, 0), new Vector3(0, 1, 0));
                        m_log.DebugFormat("[RADMIN]: Set home region {0} for updated user account {1} {2}", home.RegionID, firstName, lastName);
                    }

                    // Establish the avatar's initial appearance

                    UpdateUserAppearance(responseData, requestData, account.PrincipalID);

                    responseData["success"] = true;
                    responseData["avatar_uuid"] = account.PrincipalID.ToString();

                    m_log.InfoFormat("[RADMIN]: CreateUser: User {0} {1} created, UUID {2}", firstName, lastName, account.PrincipalID);
                }
                catch (Exception e)
                {
                    responseData["avatar_uuid"] = UUID.Zero.ToString();

                    throw e;
                }

                m_log.Info("[RADMIN]: CreateUser: request complete");
            }
        }

        /// <summary>
        /// Check whether a certain user account exists.
        /// <summary>
        /// <param name="request">incoming XML RPC request</param>
        /// <remarks>
        /// XmlRpcUserExistsMethod takes the following XMLRPC
        /// parameters
        /// <list type="table">
        /// <listheader><term>parameter name</term><description>description</description></listheader>
        /// <item><term>password</term>
        ///       <description>admin password as set in OpenSim.ini</description></item>
        /// <item><term>user_firstname</term>
        ///       <description>avatar's first name</description></item>
        /// <item><term>user_lastname</term>
        ///       <description>avatar's last name</description></item>
        /// </list>
        ///
        /// XmlRpcCreateUserMethod returns
        /// <list type="table">
        /// <listheader><term>name</term><description>description</description></listheader>
        /// <item><term>user_firstname</term>
        ///       <description>avatar's first name</description></item>
        /// <item><term>user_lastname</term>
        ///       <description>avatar's last name</description></item>
        /// <item><term>user_lastlogin</term>
        ///       <description>avatar's last login time (secs since UNIX epoch)</description></item>
        /// <item><term>success</term>
        ///       <description>true or false</description></item>
        /// <item><term>error</term>
        ///       <description>error message if success is false</description></item>
        /// </list>
        /// </remarks>
        private void XmlRpcUserExistsMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
        {
            m_log.Info("[RADMIN]: UserExists: new request");

            Hashtable responseData = (Hashtable)response.Value;
            Hashtable requestData = (Hashtable)request.Params[0];

            // check completeness
            CheckStringParameters(requestData, responseData, new string[] {"user_firstname", "user_lastname"});

            string firstName = (string) requestData["user_firstname"];
            string lastName = (string) requestData["user_lastname"];

            responseData["user_firstname"] = firstName;
            responseData["user_lastname"] = lastName;

            UUID scopeID = m_application.SceneManager.CurrentOrFirstScene.RegionInfo.ScopeID;

            UserAccount account = m_application.SceneManager.CurrentOrFirstScene.UserAccountService.GetUserAccount(scopeID, firstName, lastName);

            if (null == account)
            {
                responseData["success"] = false;
                responseData["lastlogin"] = 0;
            }
            else
            {
                GridUserInfo userInfo = m_application.SceneManager.CurrentOrFirstScene.GridUserService.GetGridUserInfo(account.PrincipalID.ToString());
                if (userInfo != null)
                    responseData["lastlogin"] = Util.ToUnixTime(userInfo.Login);
                else
                    responseData["lastlogin"] = 0;

                responseData["success"] = true;
            }

            m_log.Info("[RADMIN]: UserExists: request complete");
        }

        /// <summary>
        /// Update a user account.
        /// <summary>
        /// <param name="request">incoming XML RPC request</param>
        /// <remarks>
        /// XmlRpcUpdateUserAccountMethod takes the following XMLRPC
        /// parameters (changeable ones are optional)
        /// <list type="table">
        /// <listheader><term>parameter name</term><description>description</description></listheader>
        /// <item><term>password</term>
        ///       <description>admin password as set in OpenSim.ini</description></item>
        /// <item><term>user_firstname</term>
        ///       <description>avatar's first name (cannot be changed)</description></item>
        /// <item><term>user_lastname</term>
        ///       <description>avatar's last name (cannot be changed)</description></item>
        /// <item><term>user_password</term>
        ///       <description>avatar's password (changeable)</description></item>
        /// <item><term>start_region_x</term>
        ///       <description>avatar's start region coordinates, X
        ///                    value (changeable)</description></item>
        /// <item><term>start_region_y</term>
        ///       <description>avatar's start region coordinates, Y
        ///                    value (changeable)</description></item>
        /// <item><term>about_real_world (not implemented yet)</term>
        ///       <description>"about" text of avatar owner (changeable)</description></item>
        /// <item><term>about_virtual_world (not implemented yet)</term>
        ///       <description>"about" text of avatar (changeable)</description></item>
        /// </list>
        ///
        /// XmlRpcCreateUserMethod returns
        /// <list type="table">
        /// <listheader><term>name</term><description>description</description></listheader>
        /// <item><term>success</term>
        ///       <description>true or false</description></item>
        /// <item><term>error</term>
        ///       <description>error message if success is false</description></item>
        /// <item><term>avatar_uuid</term>
        ///       <description>UUID of the updated avatar
        ///                    account; UUID.Zero if failed.
        ///       </description></item>
        /// </list>
        /// </remarks>
        private void XmlRpcUpdateUserAccountMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
        {
            m_log.Info("[RADMIN]: UpdateUserAccount: new request");
            m_log.Warn("[RADMIN]: This method needs update for 0.7");

            Hashtable responseData = (Hashtable)response.Value;
            Hashtable requestData = (Hashtable)request.Params[0];

            lock (m_requestLock)
            {
                try
                {
                    // check completeness
                    CheckStringParameters(requestData, responseData, new string[] {
                            "user_firstname",
                            "user_lastname"});

                    // do the job
                    string firstName = (string) requestData["user_firstname"];
                    string lastName = (string) requestData["user_lastname"];

                    string password = String.Empty;
                    uint? regionXLocation = null;
                    uint? regionYLocation = null;
            //        uint? ulaX = null;
            //        uint? ulaY = null;
            //        uint? ulaZ = null;
            //        uint? usaX = null;
            //        uint? usaY = null;
            //        uint? usaZ = null;
            //        string aboutFirstLive = String.Empty;
            //        string aboutAvatar = String.Empty;

                    if (requestData.ContainsKey("user_password")) password = (string) requestData["user_password"];
                    if (requestData.ContainsKey("start_region_x"))
                        regionXLocation = Convert.ToUInt32(requestData["start_region_x"]);
                    if (requestData.ContainsKey("start_region_y"))
                        regionYLocation = Convert.ToUInt32(requestData["start_region_y"]);

            //        if (requestData.ContainsKey("start_lookat_x"))
            //            ulaX = Convert.ToUInt32((Int32) requestData["start_lookat_x"]);
            //        if (requestData.ContainsKey("start_lookat_y"))
            //            ulaY = Convert.ToUInt32((Int32) requestData["start_lookat_y"]);
            //        if (requestData.ContainsKey("start_lookat_z"))
            //            ulaZ = Convert.ToUInt32((Int32) requestData["start_lookat_z"]);

            //        if (requestData.ContainsKey("start_standat_x"))
            //            usaX = Convert.ToUInt32((Int32) requestData["start_standat_x"]);
            //        if (requestData.ContainsKey("start_standat_y"))
            //            usaY = Convert.ToUInt32((Int32) requestData["start_standat_y"]);
            //        if (requestData.ContainsKey("start_standat_z"))
            //            usaZ = Convert.ToUInt32((Int32) requestData["start_standat_z"]);
            //        if (requestData.ContainsKey("about_real_world"))
            //            aboutFirstLive = (string)requestData["about_real_world"];
            //        if (requestData.ContainsKey("about_virtual_world"))
            //            aboutAvatar = (string)requestData["about_virtual_world"];

                    Scene scene = m_application.SceneManager.CurrentOrFirstScene;
                    UUID scopeID = scene.RegionInfo.ScopeID;
                    UserAccount account = scene.UserAccountService.GetUserAccount(scopeID, firstName, lastName);

                    if (null == account)
                        throw new Exception(String.Format("avatar {0} {1} does not exist", firstName, lastName));

                    if (!String.IsNullOrEmpty(password))
                    {
                        m_log.DebugFormat("[RADMIN]: UpdateUserAccount: updating password for avatar {0} {1}", firstName, lastName);
                        ChangeUserPassword(firstName, lastName, password);
                    }

            //        if (null != usaX) userProfile.HomeLocationX = (uint) usaX;
            //        if (null != usaY) userProfile.HomeLocationY = (uint) usaY;
            //        if (null != usaZ) userProfile.HomeLocationZ = (uint) usaZ;

            //        if (null != ulaX) userProfile.HomeLookAtX = (uint) ulaX;
            //        if (null != ulaY) userProfile.HomeLookAtY = (uint) ulaY;
            //        if (null != ulaZ) userProfile.HomeLookAtZ = (uint) ulaZ;

            //        if (String.Empty != aboutFirstLive) userProfile.FirstLifeAboutText = aboutFirstLive;
            //        if (String.Empty != aboutAvatar) userProfile.AboutText = aboutAvatar;

                    // Set home position

                    if ((null != regionXLocation) && (null != regionYLocation))
                    {
                        GridRegion home = scene.GridService.GetRegionByPosition(scopeID, 
                                        (int)Util.RegionToWorldLoc((uint)regionXLocation), (int)Util.RegionToWorldLoc((uint)regionYLocation));
                        if (null == home) {
                            m_log.WarnFormat("[RADMIN]: Unable to set home region for updated user account {0} {1}", firstName, lastName);
                        } else {
                            scene.GridUserService.SetHome(account.PrincipalID.ToString(), home.RegionID, new Vector3(128, 128, 0), new Vector3(0, 1, 0));
                            m_log.DebugFormat("[RADMIN]: Set home region {0} for updated user account {1} {2}", home.RegionID, firstName, lastName);
                        }
                    }

                    // User has been created. Now establish gender and appearance.

                    UpdateUserAppearance(responseData, requestData, account.PrincipalID);

                    responseData["success"] = true;
                    responseData["avatar_uuid"] = account.PrincipalID.ToString();

                    m_log.InfoFormat("[RADMIN]: UpdateUserAccount: account for user {0} {1} updated, UUID {2}",
                                     firstName, lastName,
                                     account.PrincipalID);
                }
                catch (Exception e)
                {
                    responseData["avatar_uuid"] = UUID.Zero.ToString();

                    throw e;
                }
                
                m_log.Info("[RADMIN]: UpdateUserAccount: request complete");
            }
        }

        /// <summary>
        /// Authenticate an user.
        /// <summary>
        /// <param name="request">incoming XML RPC request</param>
        /// <remarks>
        /// XmlRpcAuthenticateUserMethod takes the following XMLRPC
        /// parameters
        /// <list type="table">
        /// <listheader><term>parameter name</term><description>description</description></listheader>
        /// <item><term>password</term>
        ///       <description>admin password as set in OpenSim.ini</description></item>
        /// <item><term>user_firstname</term>
        ///       <description>avatar's first name</description></item>
        /// <item><term>user_lastname</term>
        ///       <description>avatar's last name</description></item>
        /// <item><term>user_password</term>
        ///       <description>MD5 hash of avatar's password</description></item>
        /// <item><term>token_lifetime</term>
        ///       <description>the lifetime of the returned token (upper bounded to 30s)</description></item>
        /// </list>
        ///
        /// XmlRpcAuthenticateUserMethod returns
        /// <list type="table">
        /// <listheader><term>name</term><description>description</description></listheader>
        /// <item><term>success</term>
        ///       <description>true or false</description></item>
        /// <item><term>token</term>
        ///       <description>the authentication token sent by OpenSim</description></item>
        /// <item><term>error</term>
        ///       <description>error message if success is false</description></item>
        /// </list>
        /// </remarks>
        private void XmlRpcAuthenticateUserMethod(XmlRpcRequest request, XmlRpcResponse response,
                                                   IPEndPoint remoteClient)
        {
            m_log.Info("[RADMIN]: AuthenticateUser: new request");

            var responseData = (Hashtable)response.Value;
            var requestData = (Hashtable)request.Params[0];

            lock (m_requestLock)
            {
                try
                {
                    CheckStringParameters(requestData, responseData, new[]
                                                                         {
                                                                             "user_firstname",
                                                                             "user_lastname",
                                                                             "user_password",
                                                                             "token_lifetime"
                                                                         });

                    var firstName = (string)requestData["user_firstname"];
                    var lastName = (string)requestData["user_lastname"];
                    var password = (string)requestData["user_password"];

                    var scene = m_application.SceneManager.CurrentOrFirstScene;

                    if (scene.Equals(null))
                    {
                        m_log.Debug("scene does not exist");
                        throw new Exception("Scene does not exist.");
                    }

                    var scopeID = scene.RegionInfo.ScopeID;
                    var account = scene.UserAccountService.GetUserAccount(scopeID, firstName, lastName);

                    if (account.Equals(null) || account.PrincipalID.Equals(UUID.Zero))
                    {
                        m_log.DebugFormat("avatar {0} {1} does not exist", firstName, lastName);
                        throw new Exception(String.Format("avatar {0} {1} does not exist", firstName, lastName));
                    }

                    if (String.IsNullOrEmpty(password))
                    {
                        m_log.DebugFormat("[RADMIN]: AuthenticateUser: no password provided for {0} {1}", firstName,
                                          lastName);
                        throw new Exception(String.Format("no password provided for {0} {1}", firstName,
                                          lastName));
                    }

                    int lifetime;
                    if (int.TryParse((string)requestData["token_lifetime"], NumberStyles.Integer, CultureInfo.InvariantCulture, out lifetime) == false)
                    {
                        m_log.DebugFormat("[RADMIN]: AuthenticateUser: no token lifetime provided for {0} {1}", firstName,
                                          lastName);
                        throw new Exception(String.Format("no token lifetime provided for {0} {1}", firstName,
                                          lastName));
                    }

                    // Upper bound on lifetime set to 30s.
                    if (lifetime > 30)
                    {
                        m_log.DebugFormat("[RADMIN]: AuthenticateUser: token lifetime longer than 30s for {0} {1}", firstName,
                                          lastName);
                        throw new Exception(String.Format("token lifetime longer than 30s for {0} {1}", firstName,
                                          lastName));
                    }

                    var authModule = scene.RequestModuleInterface<IAuthenticationService>();
                    if (authModule == null)
                    {
                        m_log.Debug("[RADMIN]: AuthenticateUser: no authentication module loded");
                        throw new Exception("no authentication module loaded");
                    }

                    var token = authModule.Authenticate(account.PrincipalID, password, lifetime);
                    if (String.IsNullOrEmpty(token))
                    {
                        m_log.DebugFormat("[RADMIN]: AuthenticateUser: authentication failed for {0} {1}", firstName,
                            lastName);
                        throw new Exception(String.Format("authentication failed for {0} {1}", firstName,
                            lastName));
                    }

                    m_log.DebugFormat("[RADMIN]: AuthenticateUser: account for user {0} {1} identified with token {2}",
                        firstName, lastName, token);

                    responseData["token"] = token;
                    responseData["success"] = true;

                }
                catch (Exception e)
                {
                    responseData["success"] = false;
                    responseData["error"] = e.Message;
                    throw e;
                }

                m_log.Info("[RADMIN]: AuthenticateUser: request complete");
            }
        }

        /// <summary>
        /// Load an OAR file into a region..
        /// <summary>
        /// <param name="request">incoming XML RPC request</param>
        /// <remarks>
        /// XmlRpcLoadOARMethod takes the following XMLRPC
        /// parameters
        /// <list type="table">
        /// <listheader><term>parameter name</term><description>description</description></listheader>
        /// <item><term>password</term>
        ///       <description>admin password as set in OpenSim.ini</description></item>
        /// <item><term>filename</term>
        ///       <description>file name of the OAR file</description></item>
        /// <item><term>region_uuid</term>
        ///       <description>UUID of the region</description></item>
        /// <item><term>region_name</term>
        ///       <description>region name</description></item>
        /// <item><term>merge</term>
        ///       <description>true if oar should be merged</description></item>
        /// <item><term>skip-assets</term>
        ///       <description>true if assets should be skiped</description></item>
        /// </list>
        ///
        /// <code>region_uuid</code> takes precedence over
        /// <code>region_name</code> if both are present; one of both
        /// must be present.
        ///
        /// XmlRpcLoadOARMethod returns
        /// <list type="table">
        /// <listheader><term>name</term><description>description</description></listheader>
        /// <item><term>success</term>
        ///       <description>true or false</description></item>
        /// <item><term>error</term>
        ///       <description>error message if success is false</description></item>
        /// </list>
        /// </remarks>
        private void XmlRpcLoadOARMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
        {
            m_log.Info("[RADMIN]: Received Load OAR Administrator Request");

            Hashtable responseData = (Hashtable)response.Value;
            Hashtable requestData = (Hashtable)request.Params[0];

            lock (m_requestLock)
            {
                try
                {
                    CheckStringParameters(requestData, responseData, new string[] {"filename"});
                    CheckRegionParams(requestData, responseData);

                    Scene scene = null;
                    GetSceneFromRegionParams(requestData, responseData, out scene);

                    string filename = (string) requestData["filename"];
                    
                    bool mergeOar = false;
                    bool skipAssets = false;

                    if ((string)requestData["merge"] == "true")
                    {
                        mergeOar = true;
                    }
                    if ((string)requestData["skip-assets"] == "true")
                    {
                        skipAssets = true;
                    }

                    IRegionArchiverModule archiver = scene.RequestModuleInterface<IRegionArchiverModule>();
                    if (archiver != null)
                        archiver.DearchiveRegion(filename, mergeOar, skipAssets, Guid.Empty);
                    else
                        throw new Exception("Archiver module not present for scene");

                    responseData["loaded"] = true;
                }
                catch (Exception e)
                {
                    responseData["loaded"] = false;

                    throw e;
                }

                m_log.Info("[RADMIN]: Load OAR Administrator Request complete");
            }
        }

        /// <summary>
        /// Save a region to an OAR file
        /// <summary>
        /// <param name="request">incoming XML RPC request</param>
        /// <remarks>
        /// XmlRpcSaveOARMethod takes the following XMLRPC
        /// parameters
        /// <list type="table">
        /// <listheader><term>parameter name</term><description>description</description></listheader>
        /// <item><term>password</term>
        ///       <description>admin password as set in OpenSim.ini</description></item>
        /// <item><term>filename</term>
        ///       <description>file name for the OAR file</description></item>
        /// <item><term>region_uuid</term>
        ///       <description>UUID of the region</description></item>
        /// <item><term>region_name</term>
        ///       <description>region name</description></item>
        /// <item><term>profile</term>
        ///       <description>profile url</description></item>
        /// <item><term>noassets</term>
        ///       <description>true if no assets should be saved</description></item>
        /// <item><term>all</term>
        ///       <description>true to save all the regions in the simulator</description></item>
        /// <item><term>perm</term>
        ///       <description>C and/or T</description></item>
        /// </list>
        ///
        /// <code>region_uuid</code> takes precedence over
        /// <code>region_name</code> if both are present; one of both
        /// must be present.
        ///
        /// XmlRpcLoadOARMethod returns
        /// <list type="table">
        /// <listheader><term>name</term><description>description</description></listheader>
        /// <item><term>success</term>
        ///       <description>true or false</description></item>
        /// <item><term>error</term>
        ///       <description>error message if success is false</description></item>
        /// </list>
        /// </remarks>
        private void XmlRpcSaveOARMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
        {
            m_log.Info("[RADMIN]: Received Save OAR Request");

            Hashtable responseData = (Hashtable)response.Value;
            Hashtable requestData = (Hashtable)request.Params[0];

            try
            {
                CheckStringParameters(requestData, responseData, new string[] {"filename"});
                CheckRegionParams(requestData, responseData);

                Scene scene = null;
                GetSceneFromRegionParams(requestData, responseData, out scene);

                string filename = (string)requestData["filename"];

                Dictionary<string, object> options = new Dictionary<string, object>();

                //if (requestData.Contains("version"))
                //{
                //    options["version"] = (string)requestData["version"];
                //}

                if (requestData.Contains("home"))
                {
                    options["home"] = (string)requestData["home"];
                }

                if ((string)requestData["noassets"] == "true")
                {
                    options["noassets"] = (string)requestData["noassets"] ;
                }

                if (requestData.Contains("perm"))
                {
                    options["checkPermissions"] = (string)requestData["perm"];
                }

                if ((string)requestData["all"] == "true")
                {
                    options["all"] = (string)requestData["all"];
                }

                IRegionArchiverModule archiver = scene.RequestModuleInterface<IRegionArchiverModule>();

                if (archiver != null)
                {
                    Guid requestId = Guid.NewGuid();
                    scene.EventManager.OnOarFileSaved += RemoteAdminOarSaveCompleted;

                    m_log.InfoFormat(
                        "[RADMIN]: Submitting save OAR request for {0} to file {1}, request ID {2}", 
                        scene.Name, filename, requestId);

                    archiver.ArchiveRegion(filename, requestId, options);

                    lock (m_saveOarLock)
                        Monitor.Wait(m_saveOarLock,5000);

                    scene.EventManager.OnOarFileSaved -= RemoteAdminOarSaveCompleted;
                }
                else
                {
                    throw new Exception("Archiver module not present for scene");
                }

                responseData["saved"] = true;
            }
            catch (Exception e)
            {
                responseData["saved"] = false;

                throw e;
            }

            m_log.Info("[RADMIN]: Save OAR Request complete");
        }

        private void RemoteAdminOarSaveCompleted(Guid uuid, string name)
        {
            if (name != "")
                m_log.ErrorFormat("[RADMIN]: Saving of OAR file with request ID {0} failed with message {1}", uuid, name);
            else
                m_log.DebugFormat("[RADMIN]: Saved OAR file for request {0}", uuid);

            lock (m_saveOarLock)
                Monitor.Pulse(m_saveOarLock);
        }

        private void XmlRpcLoadXMLMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
        {
            m_log.Info("[RADMIN]: Received Load XML Administrator Request");

            Hashtable responseData = (Hashtable)response.Value;
            Hashtable requestData = (Hashtable)request.Params[0];

            lock (m_requestLock)
            {
                try
                {
                    CheckStringParameters(requestData, responseData, new string[] {"filename"});
                    CheckRegionParams(requestData, responseData);

                    Scene scene = null;
                    GetSceneFromRegionParams(requestData, responseData, out scene);

                    string filename = (string) requestData["filename"];

                    responseData["switched"] = true;

                    string xml_version = "1";
                    if (requestData.Contains("xml_version"))
                    {
                        xml_version = (string) requestData["xml_version"];
                    }

                    switch (xml_version)
                    {
                        case "1":
                            m_application.SceneManager.LoadCurrentSceneFromXml(filename, true, new Vector3(0, 0, 0));
                            break;

                        case "2":
                            m_application.SceneManager.LoadCurrentSceneFromXml2(filename);
                            break;

                        default:
                            throw new Exception(String.Format("unknown Xml{0} format", xml_version));
                    }

                    responseData["loaded"] = true;
                }
                catch (Exception e)
                {
                    responseData["loaded"] = false;
                    responseData["switched"] = false;

                    throw e;
                }

                m_log.Info("[RADMIN]: Load XML Administrator Request complete");
            }
        }

        private void XmlRpcSaveXMLMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
        {
            m_log.Info("[RADMIN]: Received Save XML Administrator Request");

            Hashtable responseData = (Hashtable)response.Value;
            Hashtable requestData = (Hashtable)request.Params[0];

            try
            {
                CheckStringParameters(requestData, responseData, new string[] {"filename"});
                CheckRegionParams(requestData, responseData);

                Scene scene = null;
                GetSceneFromRegionParams(requestData, responseData, out scene);

                string filename = (string) requestData["filename"];

                responseData["switched"] = true;

                string xml_version = "1";
                if (requestData.Contains("xml_version"))
                {
                    xml_version = (string) requestData["xml_version"];
                }

                switch (xml_version)
                {
                    case "1":
                        m_application.SceneManager.SaveCurrentSceneToXml(filename);
                        break;

                    case "2":
                        m_application.SceneManager.SaveCurrentSceneToXml2(filename);
                        break;

                    default:
                        throw new Exception(String.Format("unknown Xml{0} format", xml_version));
                }

                responseData["saved"] = true;
            }
            catch (Exception e)
            {
                responseData["saved"] = false;
                responseData["switched"] = false;

                throw e;
            }

            m_log.Info("[RADMIN]: Save XML Administrator Request complete");
        }

        private void XmlRpcRegionQueryMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
        {
            Hashtable responseData = (Hashtable)response.Value;
            Hashtable requestData = (Hashtable)request.Params[0];

            int flags = 0;
            string text = String.Empty;
            int health = 0;
            responseData["success"] = true;

            CheckRegionParams(requestData, responseData);

            Scene scene = null;
            try
            {
                GetSceneFromRegionParams(requestData, responseData, out scene);
                health = scene.GetHealth(out flags, out text);
            }
            catch (Exception e)
            {
                responseData["error"] = null;
            }

            responseData["success"] = true;
            responseData["health"] = health;
            responseData["flags"] = flags;
            responseData["message"] = text;
        }

        private void XmlRpcConsoleCommandMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
        {
            m_log.Info("[RADMIN]: Received Command XML Administrator Request");

            Hashtable responseData = (Hashtable)response.Value;
            Hashtable requestData = (Hashtable)request.Params[0];

            CheckStringParameters(requestData, responseData, new string[] {"command"});

            MainConsole.Instance.RunCommand(requestData["command"].ToString());

            m_log.Info("[RADMIN]: Command XML Administrator Request complete");
        }

        private void XmlRpcAccessListClear(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
        {
            m_log.Info("[RADMIN]: Received Access List Clear Request");

            Hashtable responseData = (Hashtable)response.Value;
            Hashtable requestData = (Hashtable)request.Params[0];

            responseData["success"] = true;

            CheckRegionParams(requestData, responseData);

            Scene scene = null;
            GetSceneFromRegionParams(requestData, responseData, out scene);

            scene.RegionInfo.EstateSettings.EstateAccess = new UUID[]{};

            if (scene.RegionInfo.Persistent)
                scene.RegionInfo.EstateSettings.Save();

            m_log.Info("[RADMIN]: Access List Clear Request complete");
        }

        private void XmlRpcAccessListAdd(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
        {
            m_log.Info("[RADMIN]: Received Access List Add Request");

            Hashtable responseData = (Hashtable)response.Value;
            Hashtable requestData = (Hashtable)request.Params[0];

            CheckRegionParams(requestData, responseData);

            Scene scene = null;
            GetSceneFromRegionParams(requestData, responseData, out scene);

            int addedUsers = 0;

            if (requestData.Contains("users"))
            {
                UUID scopeID = scene.RegionInfo.ScopeID;
                IUserAccountService userService = scene.UserAccountService;
                Hashtable users = (Hashtable) requestData["users"];
                List<UUID> uuids = new List<UUID>();
                foreach (string name in users.Values)
                {
                    string[] parts = name.Split();
                    UserAccount account = userService.GetUserAccount(scopeID, parts[0], parts[1]);
                    if (account != null)
                    {
                        uuids.Add(account.PrincipalID);
                        m_log.DebugFormat("[RADMIN]: adding \"{0}\" to ACL for \"{1}\"", name, scene.RegionInfo.RegionName);
                    }
                }
                List<UUID> accessControlList = new List<UUID>(scene.RegionInfo.EstateSettings.EstateAccess);
                foreach (UUID uuid in uuids)
                {
                   if (!accessControlList.Contains(uuid))
                    {
                        accessControlList.Add(uuid);
                        addedUsers++;
                    }
                }
                scene.RegionInfo.EstateSettings.EstateAccess = accessControlList.ToArray();
                if (scene.RegionInfo.Persistent)
                    scene.RegionInfo.EstateSettings.Save();
            }

            responseData["added"] = addedUsers;

            m_log.Info("[RADMIN]: Access List Add Request complete");
        }

        private void XmlRpcAccessListRemove(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
        {
            m_log.Info("[RADMIN]: Received Access List Remove Request");

            Hashtable responseData = (Hashtable)response.Value;
            Hashtable requestData = (Hashtable)request.Params[0];

            CheckRegionParams(requestData, responseData);

            Scene scene = null;
            GetSceneFromRegionParams(requestData, responseData, out scene);

            int removedUsers = 0;

            if (requestData.Contains("users"))
            {
                UUID scopeID = scene.RegionInfo.ScopeID;
                IUserAccountService userService = scene.UserAccountService;
                //UserProfileCacheService ups = m_application.CommunicationsManager.UserProfileCacheService;
                Hashtable users = (Hashtable) requestData["users"];
                List<UUID> uuids = new List<UUID>();
                foreach (string name in users.Values)
                {
                    string[] parts = name.Split();
                    UserAccount account = userService.GetUserAccount(scopeID, parts[0], parts[1]);
                    if (account != null)
                    {
                        uuids.Add(account.PrincipalID);
                    }
                }
                List<UUID> accessControlList = new List<UUID>(scene.RegionInfo.EstateSettings.EstateAccess);
                foreach (UUID uuid in uuids)
                {
                   if (accessControlList.Contains(uuid))
                    {
                        accessControlList.Remove(uuid);
                        removedUsers++;
                    }
                }
                scene.RegionInfo.EstateSettings.EstateAccess = accessControlList.ToArray();
                if (scene.RegionInfo.Persistent)
                    scene.RegionInfo.EstateSettings.Save();
            }

            responseData["removed"] = removedUsers;
            responseData["success"] = true;

            m_log.Info("[RADMIN]: Access List Remove Request complete");
        }

        private void XmlRpcAccessListList(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
        {
            m_log.Info("[RADMIN]: Received Access List List Request");

            Hashtable responseData = (Hashtable)response.Value;
            Hashtable requestData = (Hashtable)request.Params[0];

            CheckRegionParams(requestData, responseData);

            Scene scene = null;
            GetSceneFromRegionParams(requestData, responseData, out scene);

            UUID[] accessControlList = scene.RegionInfo.EstateSettings.EstateAccess;
            Hashtable users = new Hashtable();

            foreach (UUID user in accessControlList)
            {
                UUID scopeID = scene.RegionInfo.ScopeID;
                UserAccount account = scene.UserAccountService.GetUserAccount(scopeID, user);
                if (account != null)
                {
                    users[user.ToString()] = account.FirstName + " " + account.LastName;
                }
            }

            responseData["users"] = users;
            responseData["success"] = true;

            m_log.Info("[RADMIN]: Access List List Request complete");
        }

        private void XmlRpcEstateReload(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
        {
            m_log.Info("[RADMIN]: Received Estate Reload Request");

            Hashtable responseData = (Hashtable)response.Value;
//            Hashtable requestData = (Hashtable)request.Params[0];

            m_application.SceneManager.ForEachScene(s => 
                s.RegionInfo.EstateSettings = m_application.EstateDataService.LoadEstateSettings(s.RegionInfo.RegionID, false)                
            );

            responseData["success"] = true;

            m_log.Info("[RADMIN]: Estate Reload Request complete");
        }

        private void XmlRpcGetAgentsMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
        {
            Hashtable responseData = (Hashtable)response.Value;
            Hashtable requestData = (Hashtable)request.Params[0];

            bool includeChildren = false;

            if (requestData.Contains("include_children"))
                bool.TryParse((string)requestData["include_children"], out includeChildren);

            Scene scene;
            GetSceneFromRegionParams(requestData, responseData, out scene);

            ArrayList xmlRpcRegions = new ArrayList();
            responseData["regions"] = xmlRpcRegions;

            Hashtable xmlRpcRegion = new Hashtable();
            xmlRpcRegions.Add(xmlRpcRegion);

            xmlRpcRegion["name"] = scene.Name;
            xmlRpcRegion["id"] = scene.RegionInfo.RegionID.ToString();

            List<ScenePresence> agents = scene.GetScenePresences();
            ArrayList xmlrpcAgents = new ArrayList();

            foreach (ScenePresence agent in agents)
            {
                if (agent.IsChildAgent && !includeChildren)
                    continue;

                Hashtable xmlRpcAgent = new Hashtable();
                xmlRpcAgent.Add("name", agent.Name);
                xmlRpcAgent.Add("id", agent.UUID.ToString());
                xmlRpcAgent.Add("type", agent.PresenceType.ToString());
                xmlRpcAgent.Add("current_parcel_id", agent.currentParcelUUID.ToString());

                Vector3 pos = agent.AbsolutePosition;
                xmlRpcAgent.Add("pos_x", pos.X.ToString());
                xmlRpcAgent.Add("pos_y", pos.Y.ToString());
                xmlRpcAgent.Add("pos_z", pos.Z.ToString());

                Vector3 lookAt = agent.Lookat;
                xmlRpcAgent.Add("lookat_x", lookAt.X.ToString());
                xmlRpcAgent.Add("lookat_y", lookAt.Y.ToString());
                xmlRpcAgent.Add("lookat_z", lookAt.Z.ToString());

                Vector3 vel = agent.Velocity;
                xmlRpcAgent.Add("vel_x", vel.X.ToString());
                xmlRpcAgent.Add("vel_y", vel.Y.ToString());
                xmlRpcAgent.Add("vel_z", vel.Z.ToString());

                xmlRpcAgent.Add("is_flying", agent.Flying.ToString());
                xmlRpcAgent.Add("is_sat_on_ground", agent.SitGround.ToString());
                xmlRpcAgent.Add("is_sat_on_object", agent.IsSatOnObject.ToString());

                xmlrpcAgents.Add(xmlRpcAgent);
            }

            m_log.DebugFormat(
                "[REMOTE ADMIN]: XmlRpcGetAgents found {0} agents in {1}", xmlrpcAgents.Count, scene.Name);

            xmlRpcRegion["agents"] = xmlrpcAgents;
            responseData["success"] = true;
        }

        private void XmlRpcTeleportAgentMethod(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
        {
            Hashtable responseData = (Hashtable)response.Value;
            Hashtable requestData = (Hashtable)request.Params[0];

            UUID agentId;
            string regionName = null;
            Vector3 pos, lookAt;
            ScenePresence sp = null;

            if (requestData.Contains("agent_first_name") && requestData.Contains("agent_last_name"))
            {
                string firstName = requestData["agent_first_name"].ToString();
                string lastName = requestData["agent_last_name"].ToString();
                m_application.SceneManager.TryGetRootScenePresenceByName(firstName, lastName, out sp);

                if (sp == null)
                    throw new Exception(
                        string.Format(
                            "No agent found with agent_first_name {0} and agent_last_name {1}", firstName, lastName));
            }
            else if (requestData.Contains("agent_id"))
            {
                string rawAgentId = (string)requestData["agent_id"];

                if (!UUID.TryParse(rawAgentId, out agentId))
                    throw new Exception(string.Format("agent_id {0} does not have the correct id format", rawAgentId));

                m_application.SceneManager.TryGetRootScenePresence(agentId, out sp);

                if (sp == null)
                    throw new Exception(string.Format("No agent with agent_id {0} found in this simulator", agentId));
            }
            else
            {
                throw new Exception("No agent_id or agent_first_name and agent_last_name parameters specified");
            }

            if (requestData.Contains("region_name"))
                regionName = (string)requestData["region_name"];

            pos.X = ParseFloat(requestData, "pos_x", sp.AbsolutePosition.X);
            pos.Y = ParseFloat(requestData, "pos_y", sp.AbsolutePosition.Y);
            pos.Z = ParseFloat(requestData, "pos_z", sp.AbsolutePosition.Z);
            lookAt.X = ParseFloat(requestData, "lookat_x", sp.Lookat.X);
            lookAt.Y = ParseFloat(requestData, "lookat_y", sp.Lookat.Y);
            lookAt.Z = ParseFloat(requestData, "lookat_z", sp.Lookat.Z);

            sp.Scene.RequestTeleportLocation(
                sp.ControllingClient, regionName, pos, lookAt, (uint)Constants.TeleportFlags.ViaLocation);

            // We have no way of telling the failure of the actual teleport
            responseData["success"] = true;
        }

        private void XmlRpcRefreshSearch(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
        {
            m_log.Info("[RADMIN]: Received Refresh Search Request");

            Hashtable responseData = (Hashtable)response.Value;
            Hashtable requestData = (Hashtable)request.Params[0];

            CheckRegionParams(requestData, responseData);

            Scene scene = null;
            GetSceneFromRegionParams(requestData, responseData, out scene);

            ISearchModule searchModule = scene.RequestModuleInterface<ISearchModule>();
            if (searchModule != null)
            {
                searchModule.Refresh();
                responseData["success"] = true;
            }
            else
            {
                responseData["success"] = false;
            }

            m_log.Info("[RADMIN]: Refresh Search Request complete");
        }

        private void XmlRpcRefreshMap(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
        {
            m_log.Info("[RADMIN]: Received Refresh Map Request");

            Hashtable responseData = (Hashtable)response.Value;
            Hashtable requestData = (Hashtable)request.Params[0];

            CheckRegionParams(requestData, responseData);

            Scene scene = null;
            GetSceneFromRegionParams(requestData, responseData, out scene);

            IMapTileModule mapTileModule = scene.RequestModuleInterface<IMapTileModule>();
            if (mapTileModule != null)
            {
                Util.FireAndForget((x) =>
                {
                    mapTileModule.UploadMapTile(scene);
                });
                responseData["success"] = true;
            }
            else
            {
                responseData["success"] = false;
            }

            m_log.Info("[RADMIN]: Refresh Map Request complete");
        }

        private void XmlRpcGetOpenSimVersion(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
        {
            m_log.Info("[RADMIN]: Received Get OpenSim Version Request");

            Hashtable responseData = (Hashtable)response.Value;

            responseData["version"] = m_openSimVersion;
            responseData["success"] = true;

            m_log.Info("[RADMIN]: Get OpenSim Version Request complete");
        }

        private void XmlRpcGetAgentCount(XmlRpcRequest request, XmlRpcResponse response, IPEndPoint remoteClient)
        {
            m_log.Info("[RADMIN]: Received Get Agent Count Request");

            Hashtable responseData = (Hashtable)response.Value;
            Hashtable requestData = (Hashtable)request.Params[0];

            CheckRegionParams(requestData, responseData);

            Scene scene = null;
            GetSceneFromRegionParams(requestData, responseData, out scene);

            if (scene == null)
            {
                responseData["success"] = false;
            }
            else
            {
                responseData["count"] = scene.GetRootAgentCount();
                responseData["success"] = true;
            }

            m_log.Info("[RADMIN]: Get Agent Count Request complete");
        }

        /// <summary>
        /// Parse a float with the given parameter name from a request data hash table.
        /// </summary>
        /// <remarks>
        /// Will throw an exception if parameter is not a float.
        /// Will not throw if parameter is not found, passes back default value instead.
        /// </remarks>
        /// <param name="requestData"></param>
        /// <param name="paramName"></param>
        /// <param name="defaultVal"></param>
        /// <returns></returns>
        private static float ParseFloat(Hashtable requestData, string paramName, float defaultVal)
        {
            if (requestData.Contains(paramName))
            {
                string rawVal = (string)requestData[paramName];
                float val;

                if (!float.TryParse(rawVal, out val))
                    throw new Exception(string.Format("{0} {1} is not a valid float", paramName, rawVal));
                else
                    return val;
            }
            else
            {
                return defaultVal;
            }
        }

        private static void CheckStringParameters(Hashtable requestData, Hashtable responseData, string[] param)
        {
            foreach (string parameter in param)
            {
                if (!requestData.Contains(parameter))
                {
                    responseData["accepted"] = false;
                    throw new Exception(String.Format("missing string parameter {0}", parameter));
                }
                if (String.IsNullOrEmpty((string) requestData[parameter]))
                {
                    responseData["accepted"] = false;
                    throw new Exception(String.Format("parameter {0} is empty", parameter));
                }
            }
        }

        private static void CheckIntegerParams(Hashtable requestData, Hashtable responseData, string[] param)
        {
            foreach (string parameter in param)
            {
                if (!requestData.Contains(parameter))
                {
                    responseData["accepted"] = false;
                    throw new Exception(String.Format("missing integer parameter {0}", parameter));
                }
            }
        }

        private void CheckRegionParams(Hashtable requestData, Hashtable responseData)
        {
            //Checks if region parameters exist and gives exeption if no parameters are given
            if ((requestData.ContainsKey("region_id") && !String.IsNullOrEmpty((string)requestData["region_id"])) ||
                (requestData.ContainsKey("region_name") && !String.IsNullOrEmpty((string)requestData["region_name"])))
            {
                return;
            }
            else
            {
                responseData["accepted"] = false;
                throw new Exception("no region_name or region_id given");
            }
        }

        private void GetSceneFromRegionParams(Hashtable requestData, Hashtable responseData, out Scene scene)
        {
            scene = null;

            if (requestData.ContainsKey("region_id") &&
                !String.IsNullOrEmpty((string)requestData["region_id"]))
            {
                UUID regionID = (UUID)(string)requestData["region_id"];
                if (!m_application.SceneManager.TryGetScene(regionID, out scene))
                {
                    responseData["error"] = String.Format("Region ID {0} not found", regionID);
                    throw new Exception(String.Format("Region ID {0} not found", regionID));
                }
            }
            else if (requestData.ContainsKey("region_name") &&
                !String.IsNullOrEmpty((string)requestData["region_name"]))
            {
                string regionName = (string)requestData["region_name"];
                if (!m_application.SceneManager.TryGetScene(regionName, out scene))
                {
                    responseData["error"] = String.Format("Region {0} not found", regionName);
                    throw new Exception(String.Format("Region {0} not found", regionName));
                }
            }
            else
            {
                responseData["error"] = "no region_name or region_id given";
                throw new Exception("no region_name or region_id given");
            }
            return;
        }

        private bool GetBoolean(Hashtable requestData, string tag, bool defaultValue)
        {
            // If an access value has been provided, apply it.
            if (requestData.Contains(tag))
            {
                switch (((string)requestData[tag]).ToLower())
                {
                    case "true" :
                    case "t" :
                    case "1" :
                        return true;
                    case "false" :
                    case "f" :
                    case "0" :
                        return false;
                    default :
                        return defaultValue;
                }
            }
            else
                return defaultValue;
        }

        private int GetIntegerAttribute(XmlNode node, string attribute, int defaultValue)
        {
            try { return Convert.ToInt32(node.Attributes[attribute].Value); } catch{}
            return defaultValue;
        }

        private uint GetUnsignedAttribute(XmlNode node, string attribute, uint defaultValue)
        {
            try { return Convert.ToUInt32(node.Attributes[attribute].Value); } catch{}
            return defaultValue;
        }

        private string GetStringAttribute(XmlNode node, string attribute, string defaultValue)
        {
            try { return node.Attributes[attribute].Value; } catch{}
            return defaultValue;
        }

        public void Dispose()
        {
        }

        /// <summary>
        /// Create a user
        /// </summary>
        /// <param name="scopeID"></param>
        /// <param name="firstName"></param>
        /// <param name="lastName"></param>
        /// <param name="password"></param>
        /// <param name="email"></param>
        private UserAccount CreateUser(UUID scopeID, string firstName, string lastName, string password, string email)
        {
            Scene scene = m_application.SceneManager.CurrentOrFirstScene;
            IUserAccountService userAccountService = scene.UserAccountService;
            IGridService gridService = scene.GridService;
            IAuthenticationService authenticationService = scene.AuthenticationService;
            IGridUserService gridUserService = scene.GridUserService;
            IInventoryService inventoryService = scene.InventoryService;

            UserAccount account = userAccountService.GetUserAccount(scopeID, firstName, lastName);
            if (null == account)
            {
                account = new UserAccount(scopeID, UUID.Random(), firstName, lastName, email);
                if (account.ServiceURLs == null || (account.ServiceURLs != null && account.ServiceURLs.Count == 0))
                {
                    account.ServiceURLs = new Dictionary<string, object>();
                    account.ServiceURLs["HomeURI"] = string.Empty;
                    account.ServiceURLs["GatekeeperURI"] = string.Empty;
                    account.ServiceURLs["InventoryServerURI"] = string.Empty;
                    account.ServiceURLs["AssetServerURI"] = string.Empty;
                }

                if (userAccountService.StoreUserAccount(account))
                {
                    bool success;
                    if (authenticationService != null)
                    {
                        success = authenticationService.SetPassword(account.PrincipalID, password);
                        if (!success)
                            m_log.WarnFormat("[RADMIN]: Unable to set password for account {0} {1}.",
                                firstName, lastName);
                    }

                    GridRegion home = null;
                    if (gridService != null)
                    {
                        List<GridRegion> defaultRegions = gridService.GetDefaultRegions(UUID.Zero);
                        if (defaultRegions != null && defaultRegions.Count >= 1)
                            home = defaultRegions[0];

                        if (gridUserService != null && home != null)
                            gridUserService.SetHome(account.PrincipalID.ToString(), home.RegionID, new Vector3(128, 128, 0), new Vector3(0, 1, 0));
                        else
                            m_log.WarnFormat("[RADMIN]: Unable to set home for account {0} {1}.",
                               firstName, lastName);
                    }
                    else
                        m_log.WarnFormat("[RADMIN]: Unable to retrieve home region for account {0} {1}.",
                           firstName, lastName);

                    if (inventoryService != null)
                    {
                        success = inventoryService.CreateUserInventory(account.PrincipalID);
                        if (!success)
                            m_log.WarnFormat("[RADMIN]: Unable to create inventory for account {0} {1}.",
                                firstName, lastName);
                    }

                    m_log.InfoFormat("[RADMIN]: Account {0} {1} created successfully", firstName, lastName);
                    return account;
                 } else {
                    m_log.ErrorFormat("[RADMIN]: Account creation failed for account {0} {1}", firstName, lastName);
                }
            }
            else
            {
                m_log.ErrorFormat("[RADMIN]: A user with the name {0} {1} already exists!", firstName, lastName);
            }
            return null;
        }

        /// <summary>
        /// Change password
        /// </summary>
        /// <param name="firstName"></param>
        /// <param name="lastName"></param>
        /// <param name="password"></param>
        private bool ChangeUserPassword(string firstName, string lastName, string password)
        {
            Scene scene = m_application.SceneManager.CurrentOrFirstScene;
            IUserAccountService userAccountService = scene.UserAccountService;
            IAuthenticationService authenticationService = scene.AuthenticationService;

            UserAccount account = userAccountService.GetUserAccount(UUID.Zero, firstName, lastName);
            if (null != account)
            {
                bool success = false;
                if (authenticationService != null)
                    success = authenticationService.SetPassword(account.PrincipalID, password);

                if (!success)
                {
                    m_log.WarnFormat("[RADMIN]: Unable to set password for account {0} {1}.",
                       firstName, lastName);
                    return false;
                }
                return true;
            }
            else
            {
                m_log.ErrorFormat("[RADMIN]: No such user");
                return false;
            }
        }

        private bool LoadHeightmap(string file, UUID regionID)
        {
            m_log.InfoFormat("[RADMIN]: Terrain Loading: {0}", file);

            Scene region = null;

            if (!m_application.SceneManager.TryGetScene(regionID, out region))
            {
                m_log.InfoFormat("[RADMIN]: unable to get a scene with that name: {0}", regionID.ToString());
                return false;
            }

            ITerrainModule terrainModule = region.RequestModuleInterface<ITerrainModule>();
            if (null == terrainModule) throw new Exception("terrain module not available");
            if (Uri.IsWellFormedUriString(file, UriKind.Absolute))
            {
                m_log.Info("[RADMIN]: Terrain path is URL");
                Uri result;
                if (Uri.TryCreate(file, UriKind.RelativeOrAbsolute, out result))
                {
                    // the url is valid
                    string fileType = file.Substring(file.LastIndexOf('/') + 1);
                    terrainModule.LoadFromStream(fileType, result);
                }
            }
            else
            {
                terrainModule.LoadFromFile(file);
            }

            m_log.Info("[RADMIN]: Load height maps request complete");

            return true;
        }


        /// <summary>
        /// This method is called by the user-create and user-modify methods to establish
        /// or change, the user's appearance. Default avatar names can be specified via
        /// the config file, but must correspond to avatars in the default appearance
        /// file, or pre-existing in the user database.
        /// This should probably get moved into somewhere more core eventually.
        /// </summary>
        private void UpdateUserAppearance(Hashtable responseData, Hashtable requestData, UUID userid)
        {
            m_log.DebugFormat("[RADMIN]: updateUserAppearance");

            string defaultMale   = m_config.GetString("default_male", "Default Male");
            string defaultFemale = m_config.GetString("default_female", "Default Female");
            string defaultNeutral   = m_config.GetString("default_female", "Default Default");
            string model   = String.Empty;

            // Has a gender preference been supplied?

            if (requestData.Contains("gender"))
            {
                switch ((string)requestData["gender"])
                {
                    case "m" :
                    case "male" :
                        model = defaultMale;
                        break;
                    case "f" :
                    case "female" :
                        model = defaultFemale;
                        break;
                    case "n" :
                    case "neutral" :
                    default :
                        model = defaultNeutral;
                        break;
                }
            }

            // Has an explicit model been specified?

            if (requestData.Contains("model") && (String.IsNullOrEmpty((string)requestData["gender"])))
            {
                model = (string)requestData["model"];
            }

            // No appearance attributes were set

            if (String.IsNullOrEmpty(model))
            {
                m_log.DebugFormat("[RADMIN]: Appearance update not requested");
                return;
            }

            m_log.DebugFormat("[RADMIN]: Setting appearance for avatar {0}, using model <{1}>", userid, model);

            string[] modelSpecifiers = model.Split();
            if (modelSpecifiers.Length != 2)
            {
                m_log.WarnFormat("[RADMIN]: User appearance not set for {0}. Invalid model name : <{1}>", userid, model);
                // modelSpecifiers = dmodel.Split();
                return;
            }

            Scene scene = m_application.SceneManager.CurrentOrFirstScene;
            UUID scopeID = scene.RegionInfo.ScopeID;
            UserAccount modelProfile = scene.UserAccountService.GetUserAccount(scopeID, modelSpecifiers[0], modelSpecifiers[1]);

            if (modelProfile == null)
            {
                m_log.WarnFormat("[RADMIN]: Requested model ({0}) not found. Appearance unchanged", model);
                return;
            }

            // Set current user's appearance. This bit is easy. The appearance structure is populated with
            // actual asset ids, however to complete the magic we need to populate the inventory with the
            // assets in question.

            EstablishAppearance(userid, modelProfile.PrincipalID);

            m_log.DebugFormat("[RADMIN]: Finished setting appearance for avatar {0}, using model {1}",
                              userid, model);
        }

        /// <summary>
        /// This method is called by updateAvatarAppearance once any specified model has been
        /// ratified, or an appropriate default value has been adopted. The intended prototype
        /// is known to exist, as is the target avatar.
        /// </summary>
        private void EstablishAppearance(UUID destination, UUID source)
        {
            m_log.DebugFormat("[RADMIN]: Initializing inventory for {0} from {1}", destination, source);
            Scene scene = m_application.SceneManager.CurrentOrFirstScene;

            // If the model has no associated appearance we're done.
            AvatarAppearance avatarAppearance = scene.AvatarService.GetAppearance(source);
            if (avatarAppearance == null)
                return;

            // Simple appearance copy or copy Clothing and Bodyparts folders?
            bool copyFolders = m_config.GetBoolean("copy_folders", false);

            if (!copyFolders)
            {
                // Simple copy of wearables and appearance update
                try
                {
                    CopyWearablesAndAttachments(destination, source, avatarAppearance);

                    scene.AvatarService.SetAppearance(destination, avatarAppearance);
                }
                catch (Exception e)
                {
                    m_log.WarnFormat("[RADMIN]: Error transferring appearance for {0} : {1}",
                                      destination, e.Message);
                }

                return;
            }

            // Copy Clothing and Bodypart folders and appearance update
            try
            {
                Dictionary<UUID,UUID> inventoryMap = new Dictionary<UUID,UUID>();
                CopyInventoryFolders(destination, source, AssetType.Clothing, inventoryMap, avatarAppearance);
                CopyInventoryFolders(destination, source, AssetType.Bodypart, inventoryMap, avatarAppearance);

                AvatarWearable[] wearables = avatarAppearance.Wearables;

                for (int i=0; i<wearables.Length; i++)
                {
                    if (inventoryMap.ContainsKey(wearables[i][0].ItemID))
                    {
                        AvatarWearable wearable = new AvatarWearable();
                        wearable.Wear(inventoryMap[wearables[i][0].ItemID],
                                wearables[i][0].AssetID);
                        avatarAppearance.SetWearable(i, wearable);
                    }
                }

                scene.AvatarService.SetAppearance(destination, avatarAppearance);
            }
            catch (Exception e)
            {
               m_log.WarnFormat("[RADMIN]: Error transferring appearance for {0} : {1}",
                                  destination, e.Message);
            }

            return;
        }

        /// <summary>
        /// This method is called by establishAppearance to do a copy all inventory items
        /// worn or attached to the Clothing inventory folder of the receiving avatar.
        /// In parallel the avatar wearables and attachments are updated.
        /// </summary>
        private void CopyWearablesAndAttachments(UUID destination, UUID source, AvatarAppearance avatarAppearance)
        {
            IInventoryService inventoryService = m_application.SceneManager.CurrentOrFirstScene.InventoryService;

            // Get Clothing folder of receiver
            InventoryFolderBase destinationFolder = inventoryService.GetFolderForType(destination, AssetType.Clothing);

            if (destinationFolder == null)
                throw new Exception("Cannot locate folder(s)");

            // Missing destination folder? This should *never* be the case
            if (destinationFolder.Type != (short)AssetType.Clothing)
            {
                destinationFolder = new InventoryFolderBase();
                
                destinationFolder.ID       = UUID.Random();
                destinationFolder.Name     = "Clothing";
                destinationFolder.Owner    = destination;
                destinationFolder.Type     = (short)AssetType.Clothing;
                destinationFolder.ParentID = inventoryService.GetRootFolder(destination).ID;
                destinationFolder.Version  = 1;
                inventoryService.AddFolder(destinationFolder);     // store base record
                m_log.ErrorFormat("[RADMIN]: Created folder for destination {0}", source);
            }

            // Wearables
            AvatarWearable[] wearables = avatarAppearance.Wearables;
            AvatarWearable wearable;

            for (int i = 0; i<wearables.Length; i++)
            {
                wearable = wearables[i];
                if (wearable[0].ItemID != UUID.Zero)
                {
                    // Get inventory item and copy it
                    InventoryItemBase item = new InventoryItemBase(wearable[0].ItemID, source);
                    item = inventoryService.GetItem(item);

                    if (item != null)
                    {
                        InventoryItemBase destinationItem = new InventoryItemBase(UUID.Random(), destination);
                        destinationItem.Name = item.Name;
                        destinationItem.Owner = destination;
                        destinationItem.Description = item.Description;
                        destinationItem.InvType = item.InvType;
                        destinationItem.CreatorId = item.CreatorId;
                        destinationItem.CreatorData = item.CreatorData;
                        destinationItem.NextPermissions = item.NextPermissions;
                        destinationItem.CurrentPermissions = item.CurrentPermissions;
                        destinationItem.BasePermissions = item.BasePermissions;
                        destinationItem.EveryOnePermissions = item.EveryOnePermissions;
                        destinationItem.GroupPermissions = item.GroupPermissions;
                        destinationItem.AssetType = item.AssetType;
                        destinationItem.AssetID = item.AssetID;
                        destinationItem.GroupID = item.GroupID;
                        destinationItem.GroupOwned = item.GroupOwned;
                        destinationItem.SalePrice = item.SalePrice;
                        destinationItem.SaleType = item.SaleType;
                        destinationItem.Flags = item.Flags;
                        destinationItem.CreationDate = item.CreationDate;
                        destinationItem.Folder = destinationFolder.ID;
                        ApplyNextOwnerPermissions(destinationItem);

                        m_application.SceneManager.CurrentOrFirstScene.AddInventoryItem(destinationItem);
                        m_log.DebugFormat("[RADMIN]: Added item {0} to folder {1}", destinationItem.ID, destinationFolder.ID);

                        // Wear item
                        AvatarWearable newWearable = new AvatarWearable();
                        newWearable.Wear(destinationItem.ID, wearable[0].AssetID);
                        avatarAppearance.SetWearable(i, newWearable);
                    }
                    else
                    {
                        m_log.WarnFormat("[RADMIN]: Error transferring {0} to folder {1}", wearable[0].ItemID, destinationFolder.ID);
                    }
                }
            }

            // Attachments
            List<AvatarAttachment> attachments = avatarAppearance.GetAttachments();

            foreach (AvatarAttachment attachment in attachments)
            {
                int attachpoint = attachment.AttachPoint;
                UUID itemID = attachment.ItemID;

                if (itemID != UUID.Zero)
                {
                    // Get inventory item and copy it
                    InventoryItemBase item = new InventoryItemBase(itemID, source);
                    item = inventoryService.GetItem(item);

                    if (item != null)
                    {
                        InventoryItemBase destinationItem = new InventoryItemBase(UUID.Random(), destination);
                        destinationItem.Name = item.Name;
                        destinationItem.Owner = destination;
                        destinationItem.Description = item.Description;
                        destinationItem.InvType = item.InvType;
                        destinationItem.CreatorId = item.CreatorId;
                        destinationItem.CreatorData = item.CreatorData;
                        destinationItem.NextPermissions = item.NextPermissions;
                        destinationItem.CurrentPermissions = item.CurrentPermissions;
                        destinationItem.BasePermissions = item.BasePermissions;
                        destinationItem.EveryOnePermissions = item.EveryOnePermissions;
                        destinationItem.GroupPermissions = item.GroupPermissions;
                        destinationItem.AssetType = item.AssetType;
                        destinationItem.AssetID = item.AssetID;
                        destinationItem.GroupID = item.GroupID;
                        destinationItem.GroupOwned = item.GroupOwned;
                        destinationItem.SalePrice = item.SalePrice;
                        destinationItem.SaleType = item.SaleType;
                        destinationItem.Flags = item.Flags;
                        destinationItem.CreationDate = item.CreationDate;
                        destinationItem.Folder = destinationFolder.ID;
                        ApplyNextOwnerPermissions(destinationItem);

                        m_application.SceneManager.CurrentOrFirstScene.AddInventoryItem(destinationItem);
                        m_log.DebugFormat("[RADMIN]: Added item {0} to folder {1}", destinationItem.ID, destinationFolder.ID);

                        // Attach item
                        avatarAppearance.SetAttachment(attachpoint, destinationItem.ID, destinationItem.AssetID);
                        m_log.DebugFormat("[RADMIN]: Attached {0}", destinationItem.ID);
                    }
                    else
                    {
                        m_log.WarnFormat("[RADMIN]: Error transferring {0} to folder {1}", itemID, destinationFolder.ID);
                    }
                }
            }
        }

        /// <summary>
        /// This method is called by establishAppearance to copy inventory folders to make
        /// copies of Clothing and Bodyparts inventory folders and attaches worn attachments
        /// </summary>
        private void CopyInventoryFolders(UUID destination, UUID source, AssetType assetType, Dictionary<UUID,UUID> inventoryMap,
                                          AvatarAppearance avatarAppearance)
        {
            IInventoryService inventoryService = m_application.SceneManager.CurrentOrFirstScene.InventoryService;

            InventoryFolderBase sourceFolder = inventoryService.GetFolderForType(source, assetType);
            InventoryFolderBase destinationFolder = inventoryService.GetFolderForType(destination, assetType);

            if (sourceFolder == null || destinationFolder == null)
                throw new Exception("Cannot locate folder(s)");

            // Missing source folder? This should *never* be the case
            if (sourceFolder.Type != (short)assetType)
            {
                sourceFolder = new InventoryFolderBase();
                sourceFolder.ID       = UUID.Random();
                if (assetType == AssetType.Clothing) {
                    sourceFolder.Name     = "Clothing";
                } else {
                    sourceFolder.Name     = "Body Parts";
                }
                sourceFolder.Owner    = source;
                sourceFolder.Type     = (short)assetType;
                sourceFolder.ParentID = inventoryService.GetRootFolder(source).ID;
                sourceFolder.Version  = 1;
                inventoryService.AddFolder(sourceFolder);     // store base record
                m_log.ErrorFormat("[RADMIN] Created folder for source {0}", source);
            }

            // Missing destination folder? This should *never* be the case
            if (destinationFolder.Type != (short)assetType)
            {
                destinationFolder = new InventoryFolderBase();
                destinationFolder.ID       = UUID.Random();
                if (assetType == AssetType.Clothing)
                {
                    destinationFolder.Name  = "Clothing";
                }
                else
                {
                    destinationFolder.Name  = "Body Parts";
                }
                destinationFolder.Owner    = destination;
                destinationFolder.Type     = (short)assetType;
                destinationFolder.ParentID = inventoryService.GetRootFolder(destination).ID;
                destinationFolder.Version  = 1;
                inventoryService.AddFolder(destinationFolder);     // store base record
                m_log.ErrorFormat("[RADMIN]: Created folder for destination {0}", source);
            }

            InventoryFolderBase extraFolder;
            List<InventoryFolderBase> folders = inventoryService.GetFolderContent(source, sourceFolder.ID).Folders;

            foreach (InventoryFolderBase folder in folders)
            {
                extraFolder = new InventoryFolderBase();
                extraFolder.ID = UUID.Random();
                extraFolder.Name = folder.Name;
                extraFolder.Owner = destination;
                extraFolder.Type = folder.Type;
                extraFolder.Version = folder.Version;
                extraFolder.ParentID = destinationFolder.ID;
                inventoryService.AddFolder(extraFolder);

                m_log.DebugFormat("[RADMIN]: Added folder {0} to folder {1}", extraFolder.ID, sourceFolder.ID);

                List<InventoryItemBase> items = inventoryService.GetFolderContent(source, folder.ID).Items;

                foreach (InventoryItemBase item in items)
                {
                    InventoryItemBase destinationItem = new InventoryItemBase(UUID.Random(), destination);
                    destinationItem.Name = item.Name;
                    destinationItem.Owner = destination;
                    destinationItem.Description = item.Description;
                    destinationItem.InvType = item.InvType;
                    destinationItem.CreatorId = item.CreatorId;
                    destinationItem.CreatorData = item.CreatorData;
                    destinationItem.NextPermissions = item.NextPermissions;
                    destinationItem.CurrentPermissions = item.CurrentPermissions;
                    destinationItem.BasePermissions = item.BasePermissions;
                    destinationItem.EveryOnePermissions = item.EveryOnePermissions;
                    destinationItem.GroupPermissions = item.GroupPermissions;
                    destinationItem.AssetType = item.AssetType;
                    destinationItem.AssetID = item.AssetID;
                    destinationItem.GroupID = item.GroupID;
                    destinationItem.GroupOwned = item.GroupOwned;
                    destinationItem.SalePrice = item.SalePrice;
                    destinationItem.SaleType = item.SaleType;
                    destinationItem.Flags = item.Flags;
                    destinationItem.CreationDate = item.CreationDate;
                    destinationItem.Folder = extraFolder.ID;
                    ApplyNextOwnerPermissions(destinationItem);

                    m_application.SceneManager.CurrentOrFirstScene.AddInventoryItem(destinationItem);
                    inventoryMap.Add(item.ID, destinationItem.ID);
                    m_log.DebugFormat("[RADMIN]: Added item {0} to folder {1}", destinationItem.ID, extraFolder.ID);

                    // Attach item, if original is attached
                    int attachpoint = avatarAppearance.GetAttachpoint(item.ID);
                    if (attachpoint != 0)
                    {
                        avatarAppearance.SetAttachment(attachpoint, destinationItem.ID, destinationItem.AssetID);
                        m_log.DebugFormat("[RADMIN]: Attached {0}", destinationItem.ID);
                    }
                }
            }
        }

        /// <summary>
        /// Apply next owner permissions.
        /// </summary>
        private void ApplyNextOwnerPermissions(InventoryItemBase item)
        {
            if (item.InvType == (int)InventoryType.Object && (item.CurrentPermissions & 7) != 0)
            {
                uint perms = item.CurrentPermissions;
                PermissionsUtil.ApplyFoldedPermissions(item.CurrentPermissions, ref perms);
                item.CurrentPermissions = perms;
            }

            item.CurrentPermissions &= item.NextPermissions;
            item.BasePermissions &= item.NextPermissions;
            item.EveryOnePermissions &= item.NextPermissions;
            // item.OwnerChanged = true;
            // item.PermsMask = 0;
            // item.PermsGranter = UUID.Zero;
        }

        /// <summary>
        /// This method is called if a given model avatar name can not be found. If the external
        /// file has already been loaded once, then control returns immediately. If not, then it
        /// looks for a default appearance file. This file contains XML definitions of zero or more named
        /// avatars, each avatar can specify zero or more "outfits". Each outfit is a collection
        /// of items that together, define a particular ensemble for the avatar. Each avatar should
        /// indicate which outfit is the default, and this outfit will be automatically worn. The
        /// other outfits are provided to allow "real" avatars a way to easily change their outfits.
        /// </summary>
        private bool CreateDefaultAvatars()
        {
            // Only load once
            if (m_defaultAvatarsLoaded)
            {
                return false;
            }

            m_log.DebugFormat("[RADMIN]: Creating default avatar entries");

            m_defaultAvatarsLoaded = true;

            // Load processing starts here...

            try
            {
                string defaultAppearanceFileName = null;

                //m_config may be null if RemoteAdmin configuration secition is missing or disabled in OpenSim.ini
                if (m_config != null)
                {
                    defaultAppearanceFileName = m_config.GetString("default_appearance", "default_appearance.xml");
                }

                if (File.Exists(defaultAppearanceFileName))
                {
                    XmlDocument doc = new XmlDocument();
                    string name     = "*unknown*";
                    string email    = "anon@anon";
                    uint   regionXLocation     = 1000;
                    uint   regionYLocation     = 1000;
                    string password   = UUID.Random().ToString(); // No requirement to sign-in.
                    UUID ID = UUID.Zero;
                    AvatarAppearance avatarAppearance;
                    XmlNodeList avatars;
                    XmlNodeList assets;
                    XmlNode perms = null;
                    bool include = false;
                    bool select  = false;

                    Scene scene = m_application.SceneManager.CurrentOrFirstScene;
                    IInventoryService inventoryService = scene.InventoryService;
                    IAssetService assetService = scene.AssetService;

                    doc.LoadXml(File.ReadAllText(defaultAppearanceFileName));

                    // Load up any included assets. Duplicates will be ignored
                    assets = doc.GetElementsByTagName("RequiredAsset");
                    foreach (XmlNode assetNode in assets)
                    {
                        AssetBase asset = new AssetBase(UUID.Random(), GetStringAttribute(assetNode, "name", ""), SByte.Parse(GetStringAttribute(assetNode, "type", "")), UUID.Zero.ToString());
                        asset.Description = GetStringAttribute(assetNode,"desc","");
                        asset.Local       = Boolean.Parse(GetStringAttribute(assetNode,"local",""));
                        asset.Temporary   = Boolean.Parse(GetStringAttribute(assetNode,"temporary",""));
                        asset.Data        = Convert.FromBase64String(assetNode.InnerText);
                        assetService.Store(asset);
                    }

                    avatars = doc.GetElementsByTagName("Avatar");

                    // The document may contain multiple avatars

                    foreach (XmlElement avatar in avatars)
                    {
                        m_log.DebugFormat("[RADMIN]: Loading appearance for {0}, gender = {1}",
                            GetStringAttribute(avatar,"name","?"), GetStringAttribute(avatar,"gender","?"));

                        // Create the user identified by the avatar entry

                        try
                        {
                            // Only the name value is mandatory
                            name   = GetStringAttribute(avatar,"name",name);
                            email  = GetStringAttribute(avatar,"email",email);
                            regionXLocation   = GetUnsignedAttribute(avatar,"regx",regionXLocation);
                            regionYLocation   = GetUnsignedAttribute(avatar,"regy",regionYLocation);
                            password = GetStringAttribute(avatar,"password",password);

                            string[] names = name.Split();
                            UUID scopeID = scene.RegionInfo.ScopeID;
                            UserAccount account = scene.UserAccountService.GetUserAccount(scopeID, names[0], names[1]);
                            if (null == account)
                            {
                                account = CreateUser(scopeID, names[0], names[1], password, email);
                                if (null == account)
                                {
                                    m_log.ErrorFormat("[RADMIN]: Avatar {0} {1} was not created", names[0], names[1]);
                                    return false;
                                }
                            }

                            // Set home position

                            GridRegion home = scene.GridService.GetRegionByPosition(scopeID, 
                                        (int)Util.RegionToWorldLoc(regionXLocation), (int)Util.RegionToWorldLoc(regionYLocation));
                            if (null == home) {
                                m_log.WarnFormat("[RADMIN]: Unable to set home region for newly created user account {0} {1}", names[0], names[1]);
                            } else {
                                scene.GridUserService.SetHome(account.PrincipalID.ToString(), home.RegionID, new Vector3(128, 128, 0), new Vector3(0, 1, 0));
                                m_log.DebugFormat("[RADMIN]: Set home region {0} for updated user account {1} {2}", home.RegionID, names[0], names[1]);
                            }

                            ID = account.PrincipalID;

                            m_log.DebugFormat("[RADMIN]: User {0}[{1}] created or retrieved", name, ID);
                            include = true;
                        }
                        catch (Exception e)
                        {
                            m_log.DebugFormat("[RADMIN]: Error creating user {0} : {1}", name, e.Message);
                            include = false;
                        }

                        // OK, User has been created OK, now we can install the inventory.
                        // First retrieve the current inventory (the user may already exist)
                        // Note that althought he inventory is retrieved, the hierarchy has
                        // not been interpreted at all.

                        if (include)
                        {
                            // Setup for appearance processing
                            avatarAppearance = scene.AvatarService.GetAppearance(ID);
                            if (avatarAppearance == null)
                                avatarAppearance = new AvatarAppearance();

                            AvatarWearable[] wearables = avatarAppearance.Wearables;
                            for (int i=0; i<wearables.Length; i++)
                            {
                                wearables[i] = new AvatarWearable();
                            }

                            try
                            {
                                // m_log.DebugFormat("[RADMIN] {0} folders, {1} items in inventory",
                                //   uic.folders.Count, uic.items.Count);

                                InventoryFolderBase clothingFolder = inventoryService.GetFolderForType(ID, AssetType.Clothing);

                                // This should *never* be the case
                                if (clothingFolder == null || clothingFolder.Type != (short)AssetType.Clothing)
                                {
                                    clothingFolder = new InventoryFolderBase();
                                    clothingFolder.ID       = UUID.Random();
                                    clothingFolder.Name     = "Clothing";
                                    clothingFolder.Owner    = ID;
                                    clothingFolder.Type     = (short)AssetType.Clothing;
                                    clothingFolder.ParentID = inventoryService.GetRootFolder(ID).ID;
                                    clothingFolder.Version  = 1;
                                    inventoryService.AddFolder(clothingFolder);     // store base record
                                    m_log.ErrorFormat("[RADMIN]: Created clothing folder for {0}/{1}", name, ID);
                                }

                                // OK, now we have an inventory for the user, read in the outfits from the
                                // default appearance XMl file.

                                XmlNodeList outfits = avatar.GetElementsByTagName("Ensemble");
                                InventoryFolderBase extraFolder;
                                string outfitName;
                                UUID assetid;

                                foreach (XmlElement outfit in outfits)
                                {
                                    m_log.DebugFormat("[RADMIN]: Loading outfit {0} for {1}",
                                        GetStringAttribute(outfit,"name","?"), GetStringAttribute(avatar,"name","?"));

                                    outfitName   = GetStringAttribute(outfit,"name","");
                                    select  = (GetStringAttribute(outfit,"default","no") == "yes");

                                    // If the folder already exists, re-use it. The defaults may
                                    // change over time. Augment only.

                                    List<InventoryFolderBase> folders = inventoryService.GetFolderContent(ID, clothingFolder.ID).Folders;
                                    extraFolder = null;

                                    foreach (InventoryFolderBase folder in folders)
                                    {
                                    if (folder.Name == outfitName)
                                        {
                                            extraFolder = folder;
                                            break;
                                        }
                                    }

                                    // Otherwise, we must create the folder.
                                    if (extraFolder == null)
                                    {
                                        m_log.DebugFormat("[RADMIN]: Creating outfit folder {0} for {1}", outfitName, name);
                                        extraFolder          = new InventoryFolderBase();
                                        extraFolder.ID       = UUID.Random();
                                        extraFolder.Name     = outfitName;
                                        extraFolder.Owner    = ID;
                                        extraFolder.Type     = (short)AssetType.Clothing;
                                        extraFolder.Version  = 1;
                                        extraFolder.ParentID = clothingFolder.ID;
                                        inventoryService.AddFolder(extraFolder);
                                        m_log.DebugFormat("[RADMIN]: Adding outfile folder {0} to folder {1}", extraFolder.ID, clothingFolder.ID);
                                    }

                                    // Now get the pieces that make up the outfit
                                    XmlNodeList items = outfit.GetElementsByTagName("Item");

                                    foreach (XmlElement item in items)
                                    {
                                        assetid = UUID.Zero;
                                        XmlNodeList children = item.ChildNodes;
                                        foreach (XmlNode child in children)
                                        {
                                            switch (child.Name)
                                            {
                                                case "Permissions" :
                                                    m_log.DebugFormat("[RADMIN]: Permissions specified");
                                                    perms = child;
                                                    break;
                                                case "Asset" :
                                                    assetid = new UUID(child.InnerText);
                                                    break;
                                            }
                                        }

                                        InventoryItemBase inventoryItem = null;

                                        // Check if asset is in inventory already
                                        inventoryItem = null;
                                        List<InventoryItemBase> inventoryItems = inventoryService.GetFolderContent(ID, extraFolder.ID).Items;

                                        foreach (InventoryItemBase listItem in inventoryItems)
                                        {
                                            if (listItem.AssetID == assetid)
                                            {
                                                inventoryItem = listItem;
                                                break;
                                            }
                                        }

                                        // Create inventory item
                                        if (inventoryItem == null)
                                        {
                                            inventoryItem = new InventoryItemBase(UUID.Random(), ID);
                                            inventoryItem.Name = GetStringAttribute(item,"name","");
                                            inventoryItem.Description = GetStringAttribute(item,"desc","");
                                            inventoryItem.InvType = GetIntegerAttribute(item,"invtype",-1);
                                            inventoryItem.CreatorId = GetStringAttribute(item,"creatorid","");
                                            inventoryItem.CreatorData = GetStringAttribute(item, "creatordata", "");
                                            inventoryItem.NextPermissions = GetUnsignedAttribute(perms, "next", 0x7fffffff);
                                            inventoryItem.CurrentPermissions = GetUnsignedAttribute(perms,"current",0x7fffffff);
                                            inventoryItem.BasePermissions = GetUnsignedAttribute(perms,"base",0x7fffffff);
                                            inventoryItem.EveryOnePermissions = GetUnsignedAttribute(perms,"everyone",0x7fffffff);
                                            inventoryItem.GroupPermissions = GetUnsignedAttribute(perms,"group",0x7fffffff);
                                            inventoryItem.AssetType = GetIntegerAttribute(item,"assettype",-1);
                                            inventoryItem.AssetID = assetid; // associated asset
                                            inventoryItem.GroupID = (UUID)GetStringAttribute(item,"groupid","");
                                            inventoryItem.GroupOwned = (GetStringAttribute(item,"groupowned","false") == "true");
                                            inventoryItem.SalePrice = GetIntegerAttribute(item,"saleprice",0);
                                            inventoryItem.SaleType = (byte)GetIntegerAttribute(item,"saletype",0);
                                            inventoryItem.Flags = GetUnsignedAttribute(item,"flags",0);
                                            inventoryItem.CreationDate = GetIntegerAttribute(item,"creationdate",Util.UnixTimeSinceEpoch());
                                            inventoryItem.Folder = extraFolder.ID; // Parent folder

                                            m_application.SceneManager.CurrentOrFirstScene.AddInventoryItem(inventoryItem);
                                            m_log.DebugFormat("[RADMIN]: Added item {0} to folder {1}", inventoryItem.ID, extraFolder.ID);
                                        }

                                        // Attach item, if attachpoint is specified
                                        int attachpoint = GetIntegerAttribute(item,"attachpoint",0);
                                        if (attachpoint != 0)
                                        {
                                            avatarAppearance.SetAttachment(attachpoint, inventoryItem.ID, inventoryItem.AssetID);
                                            m_log.DebugFormat("[RADMIN]: Attached {0}", inventoryItem.ID);
                                        }

                                        // Record whether or not the item is to be initially worn
                                        try
                                        {
                                        if (select && (GetStringAttribute(item, "wear", "false") == "true"))
                                            {
                                                avatarAppearance.Wearables[inventoryItem.Flags].Wear(inventoryItem.ID, inventoryItem.AssetID);
                                            }
                                        }
                                        catch (Exception e)
                                        {
                                            m_log.WarnFormat("[RADMIN]: Error wearing item {0} : {1}", inventoryItem.ID, e.Message);
                                        }
                                    } // foreach item in outfit
                                    m_log.DebugFormat("[RADMIN]: Outfit {0} load completed", outfitName);
                                } // foreach outfit
                                m_log.DebugFormat("[RADMIN]: Inventory update complete for {0}", name);
                                scene.AvatarService.SetAppearance(ID, avatarAppearance);
                            }
                            catch (Exception e)
                            {
                                m_log.WarnFormat("[RADMIN]: Inventory processing incomplete for user {0} : {1}",
                                    name, e.Message);
                            }
                        } // End of include
                    }
                    m_log.DebugFormat("[RADMIN]: Default avatar loading complete");
                }
                else
                {
                    m_log.DebugFormat("[RADMIN]: No default avatar information available");
                    return false;
                }
            }
            catch (Exception e)
            {
                m_log.WarnFormat("[RADMIN]: Exception whilst loading default avatars ; {0}", e.Message);
                return false;
            }

            return true;
        }
    }
}