aboutsummaryrefslogtreecommitdiffstats
path: root/channels/chan_sip.c
blob: 54be4895ea1e32dbf5fc9a15b3d9340babf2c975 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913
17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
17932
17933
17934
17935
17936
17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948
17949
17950
17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
17964
17965
17966
17967
17968
17969
17970
17971
17972
17973
17974
17975
17976
17977
17978
17979
17980
17981
17982
17983
17984
17985
17986
17987
17988
17989
17990
17991
17992
17993
17994
17995
17996
17997
17998
17999
18000
18001
18002
18003
18004
18005
18006
18007
18008
18009
18010
18011
18012
18013
18014
18015
18016
18017
18018
18019
18020
18021
18022
18023
18024
18025
18026
18027
18028
18029
18030
18031
18032
18033
18034
18035
18036
18037
18038
18039
18040
18041
18042
18043
18044
18045
18046
18047
18048
18049
18050
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060
18061
18062
18063
18064
18065
18066
18067
18068
18069
18070
18071
18072
18073
18074
18075
18076
18077
18078
18079
18080
18081
18082
18083
18084
18085
18086
18087
18088
18089
18090
18091
18092
18093
18094
18095
18096
18097
18098
18099
18100
18101
18102
18103
18104
18105
18106
18107
18108
18109
18110
18111
18112
18113
18114
18115
18116
18117
18118
18119
18120
18121
18122
18123
18124
18125
18126
18127
18128
18129
18130
18131
18132
18133
18134
18135
18136
18137
18138
18139
18140
18141
18142
18143
18144
18145
18146
18147
18148
18149
18150
18151
18152
18153
18154
18155
18156
18157
18158
18159
18160
18161
18162
18163
18164
18165
18166
18167
18168
18169
18170
18171
18172
18173
18174
18175
18176
18177
18178
18179
18180
18181
18182
18183
18184
18185
18186
18187
18188
18189
18190
18191
18192
18193
18194
18195
18196
18197
18198
18199
18200
18201
18202
18203
18204
18205
18206
18207
18208
18209
18210
18211
18212
18213
18214
18215
18216
18217
18218
18219
18220
18221
18222
18223
18224
18225
18226
18227
18228
18229
18230
18231
18232
18233
18234
18235
18236
18237
18238
18239
18240
18241
18242
18243
18244
18245
18246
18247
18248
18249
18250
18251
18252
18253
18254
18255
18256
18257
18258
18259
18260
18261
18262
18263
18264
18265
18266
18267
18268
18269
18270
18271
18272
18273
18274
18275
18276
18277
18278
18279
18280
18281
18282
18283
18284
18285
18286
18287
18288
18289
18290
18291
18292
18293
18294
18295
18296
18297
18298
18299
18300
18301
18302
18303
18304
18305
18306
18307
18308
18309
18310
18311
18312
18313
18314
18315
18316
18317
18318
18319
18320
18321
18322
18323
18324
18325
18326
18327
18328
18329
18330
18331
18332
18333
18334
18335
18336
18337
18338
18339
18340
18341
18342
18343
18344
18345
18346
18347
18348
18349
18350
18351
18352
18353
18354
18355
18356
18357
18358
18359
18360
18361
18362
18363
18364
18365
18366
18367
18368
18369
18370
18371
18372
18373
18374
18375
18376
18377
18378
18379
18380
18381
18382
18383
18384
18385
18386
18387
18388
18389
18390
18391
18392
18393
18394
18395
18396
18397
18398
18399
18400
18401
18402
18403
18404
18405
18406
18407
18408
18409
18410
18411
18412
18413
18414
18415
18416
18417
18418
18419
18420
18421
18422
18423
18424
18425
18426
18427
18428
18429
18430
18431
18432
18433
18434
18435
18436
18437
18438
18439
18440
18441
18442
18443
18444
18445
18446
18447
18448
18449
18450
18451
18452
18453
18454
18455
18456
18457
18458
18459
18460
18461
18462
18463
18464
18465
18466
18467
18468
18469
18470
18471
18472
18473
18474
18475
18476
18477
18478
18479
18480
18481
18482
18483
18484
18485
18486
18487
18488
18489
18490
18491
18492
18493
18494
18495
18496
18497
18498
18499
18500
18501
18502
18503
18504
18505
18506
18507
18508
18509
18510
18511
18512
18513
18514
18515
18516
18517
18518
18519
18520
18521
18522
18523
18524
18525
18526
18527
18528
18529
18530
18531
18532
18533
18534
18535
18536
18537
18538
18539
18540
18541
18542
18543
18544
18545
18546
18547
18548
18549
18550
18551
18552
18553
18554
18555
18556
18557
18558
18559
18560
18561
18562
18563
18564
18565
18566
18567
18568
18569
18570
18571
18572
18573
18574
18575
18576
18577
18578
18579
18580
18581
18582
18583
18584
18585
18586
18587
18588
18589
18590
18591
18592
18593
18594
18595
18596
18597
18598
18599
18600
18601
18602
18603
18604
18605
18606
18607
18608
18609
18610
18611
18612
18613
18614
18615
18616
18617
18618
18619
18620
18621
18622
18623
18624
18625
18626
18627
18628
18629
18630
18631
18632
18633
18634
18635
18636
18637
18638
18639
18640
18641
18642
18643
18644
18645
18646
18647
18648
18649
18650
18651
18652
18653
18654
18655
18656
18657
18658
18659
18660
18661
18662
18663
18664
18665
18666
18667
18668
18669
18670
18671
18672
18673
18674
18675
18676
18677
18678
18679
18680
18681
18682
18683
18684
18685
18686
18687
18688
18689
18690
18691
18692
18693
18694
18695
18696
18697
18698
18699
18700
18701
18702
18703
18704
18705
18706
18707
18708
18709
18710
18711
18712
18713
18714
18715
18716
18717
18718
18719
18720
18721
18722
18723
18724
18725
18726
18727
18728
18729
18730
18731
18732
18733
18734
18735
18736
18737
18738
18739
18740
18741
18742
18743
18744
18745
18746
18747
18748
18749
18750
18751
18752
18753
18754
18755
18756
18757
18758
18759
18760
18761
18762
18763
18764
18765
18766
18767
18768
18769
18770
18771
18772
18773
18774
18775
18776
18777
18778
18779
18780
18781
18782
18783
18784
18785
18786
18787
18788
18789
18790
18791
18792
18793
18794
18795
18796
18797
18798
18799
18800
18801
18802
18803
18804
18805
18806
18807
18808
18809
18810
18811
18812
18813
18814
18815
18816
18817
18818
18819
18820
18821
18822
18823
18824
18825
18826
18827
18828
18829
18830
18831
18832
18833
18834
18835
18836
18837
18838
18839
18840
18841
18842
18843
18844
18845
18846
18847
18848
18849
18850
18851
18852
18853
18854
18855
18856
18857
18858
18859
18860
18861
18862
18863
18864
18865
18866
18867
18868
18869
18870
18871
18872
18873
18874
18875
18876
18877
18878
18879
18880
18881
18882
18883
18884
18885
18886
18887
18888
18889
18890
18891
18892
18893
18894
18895
18896
18897
18898
18899
18900
18901
18902
18903
18904
18905
18906
18907
18908
18909
18910
18911
18912
18913
18914
18915
18916
18917
18918
18919
18920
18921
18922
18923
18924
18925
18926
18927
18928
18929
18930
18931
18932
18933
18934
18935
18936
18937
18938
18939
18940
18941
18942
18943
18944
18945
18946
18947
18948
18949
18950
18951
18952
18953
18954
18955
18956
18957
18958
18959
18960
18961
18962
18963
18964
18965
18966
18967
18968
18969
18970
18971
18972
18973
18974
18975
18976
18977
18978
18979
18980
18981
18982
18983
18984
18985
18986
18987
18988
18989
18990
18991
18992
18993
18994
18995
18996
18997
18998
18999
19000
19001
19002
19003
19004
19005
19006
19007
19008
19009
19010
19011
19012
19013
19014
19015
19016
19017
19018
19019
19020
19021
19022
19023
19024
19025
19026
19027
19028
19029
19030
19031
19032
19033
19034
19035
19036
19037
19038
19039
19040
19041
19042
19043
19044
19045
19046
19047
19048
19049
19050
19051
19052
19053
19054
19055
19056
19057
19058
19059
19060
19061
19062
19063
19064
19065
19066
19067
19068
19069
19070
19071
19072
19073
19074
19075
19076
19077
19078
19079
19080
19081
19082
19083
19084
19085
19086
19087
19088
19089
19090
19091
19092
19093
19094
19095
19096
19097
19098
19099
19100
19101
19102
19103
19104
19105
19106
19107
19108
19109
19110
19111
19112
19113
19114
19115
19116
19117
19118
19119
19120
19121
19122
19123
19124
19125
19126
19127
19128
19129
19130
19131
19132
19133
19134
19135
19136
19137
19138
19139
19140
19141
19142
19143
19144
19145
19146
19147
19148
19149
19150
19151
19152
19153
19154
19155
19156
19157
19158
19159
19160
19161
19162
19163
19164
19165
19166
19167
19168
19169
19170
19171
19172
19173
19174
19175
19176
19177
19178
19179
19180
19181
19182
19183
19184
19185
19186
19187
19188
19189
19190
19191
19192
19193
19194
19195
19196
19197
19198
19199
19200
19201
19202
19203
19204
19205
19206
19207
19208
19209
19210
19211
19212
19213
19214
19215
19216
19217
19218
19219
19220
19221
19222
19223
19224
19225
19226
19227
19228
19229
19230
19231
19232
19233
19234
19235
19236
19237
19238
19239
19240
19241
19242
19243
19244
19245
19246
19247
19248
19249
19250
19251
19252
19253
19254
19255
19256
19257
19258
19259
19260
19261
19262
19263
19264
19265
19266
19267
19268
19269
19270
19271
19272
19273
19274
19275
19276
19277
19278
19279
19280
19281
19282
19283
19284
19285
19286
19287
19288
19289
19290
19291
19292
19293
19294
19295
19296
19297
19298
19299
19300
19301
19302
19303
19304
19305
19306
19307
19308
19309
19310
19311
19312
19313
19314
19315
19316
19317
19318
19319
19320
19321
19322
19323
19324
19325
19326
19327
19328
19329
19330
19331
19332
19333
19334
19335
19336
19337
19338
19339
19340
19341
19342
19343
19344
19345
19346
19347
19348
19349
19350
19351
19352
19353
19354
19355
19356
19357
19358
19359
19360
19361
19362
19363
19364
19365
19366
19367
19368
19369
19370
19371
19372
19373
19374
19375
19376
19377
19378
19379
19380
19381
19382
19383
19384
19385
19386
19387
19388
19389
19390
19391
19392
19393
19394
19395
19396
19397
19398
19399
19400
19401
19402
19403
19404
19405
19406
19407
19408
19409
19410
19411
19412
19413
19414
19415
19416
19417
19418
19419
19420
19421
19422
19423
19424
19425
19426
19427
19428
19429
19430
19431
19432
19433
19434
19435
19436
19437
19438
19439
19440
19441
19442
19443
19444
19445
19446
19447
19448
19449
19450
19451
19452
19453
19454
19455
19456
19457
19458
19459
19460
19461
19462
19463
19464
19465
19466
19467
19468
19469
19470
19471
19472
19473
19474
19475
19476
19477
19478
19479
19480
19481
19482
19483
19484
19485
19486
19487
19488
19489
19490
19491
19492
19493
19494
19495
19496
19497
19498
19499
19500
19501
19502
19503
19504
19505
19506
19507
19508
19509
19510
19511
19512
19513
19514
19515
19516
19517
19518
19519
19520
19521
19522
19523
19524
19525
19526
19527
19528
19529
19530
19531
19532
19533
19534
19535
19536
19537
19538
19539
19540
19541
19542
19543
19544
19545
19546
19547
19548
19549
19550
19551
19552
19553
19554
19555
19556
19557
19558
19559
19560
19561
19562
19563
19564
19565
19566
19567
19568
19569
19570
19571
19572
19573
19574
19575
19576
19577
19578
19579
19580
19581
19582
19583
19584
19585
19586
19587
19588
19589
19590
19591
19592
19593
19594
19595
19596
19597
19598
19599
19600
19601
19602
19603
19604
19605
19606
19607
19608
19609
19610
19611
19612
19613
19614
19615
19616
19617
19618
19619
19620
19621
19622
19623
19624
19625
19626
19627
19628
19629
19630
19631
19632
19633
19634
19635
19636
19637
19638
19639
19640
19641
19642
19643
19644
19645
19646
19647
19648
19649
19650
19651
19652
19653
19654
19655
19656
19657
19658
19659
19660
19661
19662
19663
19664
19665
19666
19667
19668
19669
19670
19671
19672
19673
19674
19675
19676
19677
19678
19679
19680
19681
19682
19683
19684
19685
19686
19687
19688
19689
19690
19691
19692
19693
19694
19695
19696
19697
19698
19699
19700
19701
19702
19703
19704
19705
19706
19707
19708
19709
19710
19711
19712
19713
19714
19715
19716
19717
19718
19719
19720
19721
19722
19723
19724
19725
19726
19727
19728
19729
19730
19731
19732
19733
19734
19735
19736
19737
19738
19739
19740
19741
19742
19743
19744
19745
19746
19747
19748
19749
19750
19751
19752
19753
19754
19755
19756
19757
19758
19759
19760
19761
19762
19763
19764
19765
19766
19767
19768
19769
19770
19771
19772
19773
19774
19775
19776
19777
19778
19779
19780
19781
19782
19783
19784
19785
19786
19787
19788
19789
19790
19791
19792
19793
19794
19795
19796
19797
19798
19799
19800
19801
19802
19803
19804
19805
19806
19807
19808
19809
19810
19811
19812
19813
19814
19815
19816
19817
19818
19819
19820
19821
19822
19823
19824
19825
19826
19827
19828
19829
19830
19831
19832
19833
19834
19835
19836
19837
19838
19839
19840
19841
19842
19843
19844
19845
19846
19847
19848
19849
19850
19851
19852
19853
19854
19855
19856
19857
19858
19859
19860
19861
19862
19863
19864
19865
19866
19867
19868
19869
19870
19871
19872
19873
19874
19875
19876
19877
19878
19879
19880
19881
19882
19883
19884
19885
19886
19887
19888
19889
19890
19891
19892
19893
19894
19895
19896
19897
19898
19899
19900
19901
19902
19903
19904
19905
19906
19907
19908
19909
19910
19911
19912
19913
19914
19915
19916
19917
19918
19919
19920
19921
19922
19923
19924
19925
19926
19927
19928
19929
19930
19931
19932
19933
19934
19935
19936
19937
19938
19939
19940
19941
19942
19943
19944
19945
19946
19947
19948
19949
19950
19951
19952
19953
19954
19955
19956
19957
19958
19959
19960
19961
19962
19963
19964
19965
19966
19967
19968
19969
19970
19971
19972
19973
19974
19975
19976
19977
19978
19979
19980
19981
19982
19983
19984
19985
19986
19987
19988
19989
19990
19991
19992
19993
19994
19995
19996
19997
19998
19999
20000
20001
20002
20003
20004
20005
20006
20007
20008
20009
20010
20011
20012
20013
20014
20015
20016
20017
20018
20019
20020
20021
20022
20023
20024
20025
20026
20027
20028
20029
20030
20031
20032
20033
20034
20035
20036
20037
20038
20039
20040
20041
20042
20043
20044
20045
20046
20047
20048
20049
20050
20051
20052
20053
20054
20055
20056
20057
20058
20059
20060
20061
20062
20063
20064
20065
20066
20067
20068
20069
20070
20071
20072
20073
20074
20075
20076
20077
20078
20079
20080
20081
20082
20083
20084
20085
20086
20087
20088
20089
20090
20091
20092
20093
20094
20095
20096
20097
20098
20099
20100
20101
20102
20103
20104
20105
20106
20107
20108
20109
20110
20111
20112
20113
20114
20115
20116
20117
20118
20119
20120
20121
20122
20123
20124
20125
20126
20127
20128
20129
20130
20131
20132
20133
20134
20135
20136
20137
20138
20139
20140
20141
20142
20143
20144
20145
20146
20147
20148
20149
20150
20151
20152
20153
20154
20155
20156
20157
20158
20159
20160
20161
20162
20163
20164
20165
20166
20167
20168
20169
20170
20171
20172
20173
20174
20175
20176
20177
20178
20179
20180
20181
20182
20183
20184
20185
20186
20187
20188
20189
20190
20191
20192
20193
20194
20195
20196
20197
20198
20199
20200
20201
20202
20203
20204
20205
20206
20207
20208
20209
20210
20211
20212
20213
20214
20215
20216
20217
20218
20219
20220
20221
20222
20223
20224
20225
20226
20227
20228
20229
20230
20231
20232
20233
20234
20235
20236
20237
20238
20239
20240
20241
20242
20243
20244
20245
20246
20247
20248
20249
20250
20251
20252
20253
20254
20255
20256
20257
20258
20259
20260
20261
20262
20263
20264
20265
20266
20267
20268
20269
20270
20271
20272
20273
20274
20275
20276
20277
20278
20279
20280
20281
20282
20283
20284
20285
20286
20287
20288
20289
20290
20291
20292
20293
20294
20295
20296
20297
20298
20299
20300
20301
20302
20303
20304
20305
20306
20307
20308
20309
20310
20311
20312
20313
20314
20315
20316
20317
20318
20319
20320
20321
20322
20323
20324
20325
20326
20327
20328
20329
20330
20331
20332
20333
20334
20335
20336
20337
20338
20339
20340
20341
20342
20343
20344
20345
20346
20347
20348
20349
20350
20351
20352
20353
20354
20355
20356
20357
20358
20359
20360
20361
20362
20363
20364
20365
20366
20367
20368
20369
20370
20371
20372
20373
20374
20375
20376
20377
20378
20379
20380
20381
20382
20383
20384
20385
20386
20387
20388
20389
20390
20391
20392
20393
20394
20395
20396
20397
20398
20399
20400
20401
20402
20403
20404
20405
20406
20407
20408
20409
20410
20411
20412
20413
20414
20415
20416
20417
20418
20419
20420
20421
20422
20423
20424
20425
20426
20427
20428
20429
20430
20431
20432
20433
20434
20435
20436
20437
20438
20439
20440
20441
20442
20443
20444
20445
20446
20447
20448
20449
20450
20451
20452
20453
20454
20455
20456
20457
20458
20459
20460
20461
20462
20463
20464
20465
20466
20467
20468
20469
20470
20471
20472
20473
20474
20475
20476
20477
20478
20479
20480
20481
20482
20483
20484
20485
20486
20487
20488
20489
20490
20491
20492
20493
20494
20495
20496
20497
20498
20499
20500
20501
20502
20503
20504
20505
20506
20507
20508
20509
20510
20511
20512
20513
20514
20515
20516
20517
20518
20519
20520
20521
20522
20523
20524
20525
20526
20527
20528
20529
20530
20531
20532
20533
20534
20535
20536
20537
20538
20539
20540
20541
20542
20543
20544
20545
20546
20547
20548
20549
20550
20551
20552
20553
20554
20555
20556
20557
20558
20559
20560
20561
20562
20563
20564
20565
20566
20567
20568
20569
20570
20571
20572
20573
20574
20575
20576
20577
20578
20579
20580
20581
20582
20583
20584
20585
20586
20587
20588
20589
20590
20591
20592
20593
20594
20595
20596
20597
20598
20599
20600
20601
20602
20603
20604
20605
20606
20607
20608
20609
20610
20611
20612
20613
20614
20615
20616
20617
20618
20619
20620
20621
20622
20623
20624
20625
20626
20627
20628
20629
20630
20631
20632
20633
20634
20635
20636
20637
20638
20639
20640
20641
20642
20643
20644
20645
20646
20647
20648
20649
20650
20651
20652
20653
20654
20655
20656
20657
20658
20659
20660
20661
20662
20663
20664
20665
20666
20667
20668
20669
20670
20671
20672
20673
20674
20675
20676
20677
20678
20679
20680
20681
20682
20683
20684
20685
20686
20687
20688
20689
20690
20691
20692
20693
20694
20695
20696
20697
20698
20699
20700
20701
20702
20703
20704
20705
20706
20707
20708
20709
20710
20711
20712
20713
20714
20715
20716
20717
20718
20719
20720
20721
20722
20723
20724
20725
20726
20727
20728
20729
20730
20731
20732
20733
20734
20735
20736
20737
20738
20739
20740
20741
20742
20743
20744
20745
20746
20747
20748
20749
20750
20751
20752
20753
20754
20755
20756
20757
20758
20759
20760
20761
20762
20763
20764
20765
20766
20767
20768
20769
20770
20771
20772
20773
20774
20775
20776
20777
20778
20779
20780
20781
20782
20783
20784
20785
20786
20787
20788
20789
20790
20791
20792
20793
20794
20795
20796
20797
20798
20799
20800
20801
20802
20803
20804
20805
20806
20807
20808
20809
20810
20811
20812
20813
20814
20815
20816
20817
20818
20819
20820
20821
20822
20823
20824
20825
20826
20827
20828
20829
20830
20831
20832
20833
20834
20835
20836
20837
20838
20839
20840
20841
20842
20843
20844
20845
20846
20847
20848
20849
20850
20851
20852
20853
20854
20855
20856
20857
20858
20859
20860
20861
20862
20863
20864
20865
20866
20867
20868
20869
20870
20871
20872
20873
20874
20875
20876
20877
20878
20879
20880
20881
20882
20883
20884
20885
20886
20887
20888
20889
20890
20891
20892
20893
20894
20895
20896
20897
20898
20899
20900
20901
20902
20903
20904
20905
20906
20907
20908
20909
20910
20911
20912
20913
20914
20915
20916
20917
20918
20919
20920
20921
20922
20923
20924
20925
20926
20927
20928
20929
20930
20931
20932
20933
20934
20935
20936
20937
20938
20939
20940
20941
20942
20943
20944
20945
20946
20947
20948
20949
20950
20951
20952
20953
20954
20955
20956
20957
20958
20959
20960
20961
20962
20963
20964
20965
20966
20967
20968
20969
20970
20971
20972
20973
20974
20975
20976
20977
20978
20979
20980
20981
20982
20983
20984
20985
20986
20987
20988
20989
20990
20991
20992
20993
20994
20995
20996
20997
20998
20999
21000
21001
21002
21003
21004
21005
21006
21007
21008
21009
21010
21011
21012
21013
21014
21015
21016
21017
21018
21019
21020
21021
21022
21023
21024
21025
21026
21027
21028
21029
21030
21031
21032
21033
21034
21035
21036
21037
21038
21039
21040
21041
21042
21043
21044
21045
21046
21047
21048
21049
21050
21051
21052
21053
21054
21055
21056
21057
21058
21059
21060
21061
21062
21063
21064
21065
21066
21067
21068
21069
21070
21071
21072
21073
21074
21075
21076
21077
21078
21079
21080
21081
21082
21083
21084
21085
21086
21087
21088
21089
21090
21091
21092
21093
21094
21095
21096
21097
21098
21099
21100
21101
21102
21103
21104
21105
21106
21107
21108
21109
21110
21111
21112
21113
21114
21115
21116
21117
21118
21119
21120
21121
21122
21123
21124
21125
21126
21127
21128
21129
21130
21131
21132
21133
21134
21135
21136
21137
21138
21139
21140
21141
21142
21143
21144
21145
21146
21147
21148
21149
21150
21151
21152
21153
21154
21155
21156
21157
21158
21159
21160
21161
21162
21163
21164
21165
21166
21167
21168
21169
21170
21171
21172
21173
21174
21175
21176
21177
21178
21179
21180
21181
21182
21183
21184
21185
21186
21187
21188
21189
21190
21191
21192
21193
21194
21195
21196
21197
21198
21199
21200
21201
21202
21203
21204
21205
21206
21207
21208
21209
21210
21211
21212
21213
21214
21215
21216
21217
21218
21219
21220
21221
21222
21223
21224
21225
21226
21227
21228
21229
21230
21231
21232
21233
21234
21235
21236
21237
21238
21239
21240
21241
21242
21243
21244
21245
21246
21247
21248
21249
21250
21251
21252
21253
21254
21255
21256
21257
21258
21259
21260
21261
21262
21263
21264
21265
21266
21267
21268
21269
21270
21271
21272
21273
21274
21275
21276
21277
21278
21279
21280
21281
21282
21283
21284
21285
21286
21287
21288
21289
21290
21291
21292
21293
21294
21295
21296
21297
21298
21299
21300
21301
21302
21303
21304
21305
21306
21307
21308
21309
21310
21311
21312
21313
21314
21315
21316
21317
21318
21319
21320
21321
21322
21323
21324
21325
21326
21327
21328
21329
21330
21331
21332
21333
21334
21335
21336
21337
21338
21339
21340
21341
21342
21343
21344
21345
21346
21347
21348
21349
21350
21351
21352
21353
21354
21355
21356
21357
21358
21359
21360
21361
21362
21363
21364
21365
21366
21367
21368
21369
21370
21371
21372
21373
21374
21375
21376
21377
21378
21379
21380
21381
21382
21383
21384
21385
21386
21387
21388
21389
21390
21391
21392
21393
21394
21395
21396
21397
21398
21399
21400
21401
21402
21403
21404
21405
21406
21407
21408
21409
21410
21411
21412
21413
21414
21415
21416
21417
21418
21419
21420
21421
21422
21423
21424
21425
21426
21427
21428
21429
21430
21431
21432
21433
21434
21435
21436
21437
21438
21439
21440
21441
21442
21443
21444
21445
21446
21447
21448
21449
21450
21451
21452
21453
21454
21455
21456
21457
21458
21459
21460
21461
21462
21463
21464
21465
21466
21467
21468
21469
21470
21471
21472
21473
21474
21475
21476
21477
21478
21479
21480
21481
21482
21483
21484
21485
21486
21487
21488
21489
21490
21491
21492
21493
21494
21495
21496
21497
21498
21499
21500
21501
21502
21503
21504
21505
21506
21507
21508
21509
21510
21511
21512
21513
21514
21515
21516
21517
21518
21519
21520
21521
21522
21523
21524
21525
21526
21527
21528
21529
21530
21531
21532
21533
21534
21535
21536
21537
21538
21539
21540
21541
21542
21543
21544
21545
21546
21547
21548
21549
21550
21551
21552
21553
21554
21555
21556
21557
21558
21559
21560
21561
21562
21563
21564
21565
21566
21567
21568
21569
21570
21571
21572
21573
21574
21575
21576
21577
21578
21579
21580
21581
21582
21583
21584
21585
21586
21587
21588
21589
21590
21591
21592
21593
21594
21595
21596
21597
21598
21599
21600
21601
21602
21603
21604
21605
21606
21607
21608
21609
21610
21611
21612
21613
21614
21615
21616
21617
21618
21619
21620
21621
21622
21623
21624
21625
21626
21627
21628
21629
21630
21631
21632
21633
21634
21635
21636
21637
21638
21639
21640
21641
21642
21643
21644
21645
21646
21647
21648
21649
21650
21651
21652
21653
21654
21655
21656
21657
21658
21659
21660
21661
21662
21663
21664
21665
21666
21667
21668
21669
21670
21671
21672
21673
21674
21675
21676
21677
21678
21679
21680
21681
21682
21683
21684
21685
21686
21687
21688
21689
21690
21691
21692
21693
21694
21695
21696
21697
21698
21699
21700
21701
21702
21703
21704
21705
21706
21707
21708
21709
21710
21711
21712
21713
21714
21715
21716
21717
21718
21719
21720
21721
21722
21723
21724
21725
21726
21727
21728
21729
21730
21731
21732
21733
21734
21735
21736
21737
21738
21739
21740
21741
21742
21743
21744
21745
21746
21747
21748
21749
21750
21751
21752
21753
21754
21755
21756
21757
21758
21759
21760
21761
21762
21763
21764
21765
21766
21767
21768
21769
21770
21771
21772
21773
21774
21775
21776
21777
21778
21779
21780
21781
21782
21783
21784
21785
21786
21787
21788
21789
21790
21791
21792
21793
21794
21795
21796
21797
21798
21799
21800
21801
21802
21803
21804
21805
21806
21807
21808
21809
21810
21811
21812
21813
21814
21815
21816
21817
21818
21819
21820
21821
21822
21823
21824
21825
21826
21827
21828
21829
21830
21831
21832
21833
21834
21835
21836
21837
21838
21839
21840
21841
21842
21843
21844
21845
21846
21847
21848
21849
21850
21851
21852
21853
21854
21855
21856
21857
21858
21859
21860
21861
21862
21863
21864
21865
21866
21867
21868
21869
21870
21871
21872
21873
21874
21875
21876
21877
21878
21879
21880
21881
21882
21883
21884
21885
21886
21887
21888
21889
21890
21891
21892
21893
21894
21895
21896
21897
21898
21899
21900
21901
21902
21903
21904
21905
21906
21907
21908
21909
21910
21911
21912
21913
21914
21915
21916
21917
21918
21919
21920
21921
21922
21923
21924
21925
21926
21927
21928
21929
21930
21931
21932
21933
21934
21935
21936
21937
21938
21939
21940
21941
21942
21943
21944
21945
21946
21947
21948
21949
21950
21951
21952
21953
21954
21955
21956
21957
21958
21959
21960
21961
21962
21963
21964
21965
21966
21967
21968
21969
21970
21971
21972
21973
21974
21975
21976
21977
21978
21979
21980
21981
21982
21983
21984
21985
21986
21987
21988
21989
21990
21991
21992
21993
21994
21995
21996
21997
21998
21999
22000
22001
22002
22003
22004
22005
22006
22007
22008
22009
22010
22011
22012
22013
22014
22015
22016
22017
22018
22019
22020
22021
22022
22023
22024
22025
22026
22027
22028
22029
22030
22031
22032
22033
22034
22035
22036
22037
22038
22039
22040
22041
22042
22043
22044
22045
22046
22047
22048
22049
22050
22051
22052
22053
22054
22055
22056
22057
22058
22059
22060
22061
22062
22063
22064
22065
22066
22067
22068
22069
22070
22071
22072
22073
22074
22075
22076
22077
22078
22079
22080
22081
22082
22083
22084
22085
22086
22087
22088
22089
22090
22091
22092
22093
22094
22095
22096
22097
22098
22099
22100
22101
22102
22103
22104
22105
22106
22107
22108
22109
22110
22111
22112
22113
22114
22115
22116
22117
22118
22119
22120
22121
22122
22123
22124
22125
22126
22127
22128
22129
22130
22131
22132
22133
22134
22135
22136
22137
22138
22139
22140
22141
22142
22143
22144
22145
22146
22147
22148
22149
22150
22151
22152
22153
22154
22155
22156
22157
22158
22159
22160
22161
22162
22163
22164
22165
22166
22167
22168
22169
22170
22171
22172
22173
22174
22175
22176
22177
22178
22179
22180
22181
22182
22183
22184
22185
22186
22187
22188
22189
22190
22191
22192
22193
22194
22195
22196
22197
22198
22199
22200
22201
22202
22203
22204
22205
22206
22207
22208
22209
22210
22211
22212
22213
22214
22215
22216
22217
22218
22219
22220
22221
22222
22223
22224
22225
22226
22227
22228
22229
22230
22231
22232
22233
22234
22235
22236
22237
22238
22239
22240
22241
22242
22243
22244
22245
22246
22247
22248
22249
22250
22251
22252
22253
22254
22255
22256
22257
22258
22259
22260
22261
22262
22263
22264
22265
22266
22267
22268
22269
22270
22271
22272
22273
22274
22275
22276
22277
22278
22279
22280
22281
22282
22283
22284
22285
22286
22287
22288
22289
22290
22291
22292
22293
22294
22295
22296
22297
22298
22299
22300
22301
22302
22303
22304
22305
22306
22307
22308
22309
22310
22311
22312
22313
22314
22315
22316
22317
22318
22319
22320
22321
22322
22323
22324
22325
22326
22327
22328
22329
22330
22331
22332
22333
22334
22335
22336
22337
22338
22339
22340
22341
22342
22343
22344
22345
22346
22347
22348
22349
22350
22351
22352
22353
22354
22355
22356
22357
22358
22359
22360
22361
22362
22363
22364
22365
22366
22367
22368
22369
22370
22371
22372
22373
22374
22375
22376
22377
22378
22379
22380
22381
22382
22383
22384
22385
22386
22387
22388
22389
22390
22391
22392
22393
22394
22395
22396
22397
22398
22399
22400
22401
22402
22403
22404
22405
22406
22407
22408
22409
22410
22411
22412
22413
22414
22415
22416
22417
22418
22419
22420
22421
22422
22423
22424
22425
22426
22427
22428
22429
22430
22431
22432
22433
22434
22435
22436
22437
22438
22439
22440
22441
22442
22443
22444
22445
22446
22447
22448
22449
22450
22451
22452
22453
22454
22455
22456
22457
22458
22459
22460
22461
22462
22463
22464
22465
22466
22467
22468
22469
22470
22471
22472
22473
22474
22475
22476
22477
22478
22479
22480
22481
22482
22483
22484
22485
22486
22487
22488
22489
22490
22491
22492
22493
22494
22495
22496
22497
22498
22499
22500
22501
22502
22503
22504
22505
22506
22507
22508
22509
22510
22511
22512
22513
22514
22515
22516
22517
22518
22519
22520
22521
22522
22523
22524
22525
22526
22527
22528
22529
22530
22531
22532
22533
22534
22535
22536
22537
22538
22539
22540
22541
22542
22543
22544
22545
22546
22547
22548
22549
22550
22551
22552
22553
22554
22555
22556
22557
22558
22559
22560
22561
22562
22563
22564
22565
22566
22567
22568
22569
22570
22571
22572
22573
22574
22575
22576
22577
22578
22579
22580
22581
22582
22583
22584
22585
22586
22587
22588
22589
22590
22591
22592
22593
22594
22595
22596
22597
22598
22599
22600
22601
22602
22603
22604
22605
22606
22607
22608
22609
22610
22611
22612
22613
22614
22615
22616
22617
22618
22619
22620
22621
22622
22623
22624
22625
22626
22627
22628
22629
22630
22631
22632
22633
22634
22635
22636
22637
22638
22639
22640
22641
22642
22643
22644
22645
22646
22647
22648
22649
22650
22651
22652
22653
22654
22655
22656
22657
22658
22659
22660
22661
22662
22663
22664
22665
22666
22667
22668
22669
22670
22671
22672
22673
22674
22675
22676
22677
22678
22679
22680
22681
22682
22683
22684
22685
22686
22687
22688
22689
22690
22691
22692
22693
22694
22695
22696
22697
22698
22699
22700
22701
22702
22703
22704
22705
22706
22707
22708
22709
22710
22711
22712
22713
22714
22715
22716
22717
22718
22719
22720
22721
22722
22723
22724
22725
22726
22727
22728
22729
22730
22731
22732
22733
22734
22735
22736
22737
22738
22739
22740
22741
22742
22743
22744
22745
22746
22747
22748
22749
22750
22751
22752
22753
22754
22755
22756
22757
22758
22759
22760
22761
22762
22763
22764
22765
22766
22767
22768
22769
22770
22771
22772
22773
22774
22775
22776
22777
22778
22779
22780
22781
22782
22783
22784
22785
22786
22787
22788
22789
22790
22791
22792
22793
22794
22795
22796
22797
22798
22799
22800
22801
22802
22803
22804
22805
22806
22807
22808
22809
22810
22811
22812
22813
22814
22815
22816
22817
22818
22819
22820
22821
22822
22823
22824
22825
22826
22827
22828
22829
22830
22831
22832
22833
22834
22835
22836
22837
22838
22839
22840
22841
22842
22843
22844
22845
22846
22847
22848
22849
22850
22851
22852
22853
22854
22855
22856
22857
22858
22859
22860
22861
22862
22863
22864
22865
22866
22867
22868
22869
22870
22871
22872
22873
22874
22875
22876
22877
22878
22879
22880
22881
22882
22883
22884
22885
22886
22887
22888
22889
22890
22891
22892
22893
22894
22895
22896
22897
22898
22899
22900
22901
22902
22903
22904
22905
22906
22907
22908
22909
22910
22911
22912
22913
22914
22915
22916
22917
22918
22919
22920
22921
22922
22923
22924
22925
22926
22927
22928
22929
22930
22931
22932
22933
22934
22935
22936
22937
22938
22939
22940
22941
22942
22943
22944
22945
22946
22947
22948
22949
22950
22951
22952
22953
22954
22955
22956
22957
22958
22959
22960
22961
22962
22963
22964
22965
22966
22967
22968
22969
22970
22971
22972
22973
22974
22975
22976
22977
22978
22979
22980
22981
22982
22983
22984
22985
22986
22987
22988
22989
22990
22991
22992
22993
22994
22995
22996
22997
22998
22999
23000
23001
23002
23003
23004
23005
23006
23007
23008
23009
23010
23011
23012
23013
23014
23015
23016
23017
23018
23019
23020
23021
23022
23023
23024
23025
23026
23027
23028
23029
23030
23031
23032
23033
23034
23035
23036
23037
23038
23039
23040
23041
23042
23043
23044
23045
23046
23047
23048
23049
23050
23051
23052
23053
23054
23055
23056
23057
23058
23059
23060
23061
23062
23063
23064
23065
23066
23067
23068
23069
23070
23071
23072
23073
23074
23075
23076
23077
23078
23079
23080
23081
23082
23083
23084
23085
23086
23087
23088
23089
23090
23091
23092
23093
23094
23095
23096
23097
23098
23099
23100
23101
23102
23103
23104
23105
23106
23107
23108
23109
23110
23111
23112
23113
23114
23115
23116
23117
23118
23119
23120
23121
23122
23123
23124
23125
23126
23127
23128
23129
23130
23131
23132
23133
23134
23135
23136
23137
23138
23139
23140
23141
23142
23143
23144
23145
23146
23147
23148
23149
23150
23151
23152
23153
23154
23155
23156
23157
23158
23159
23160
23161
23162
23163
23164
23165
23166
23167
23168
23169
23170
23171
23172
23173
23174
23175
23176
23177
23178
23179
23180
23181
23182
23183
23184
23185
23186
23187
23188
23189
23190
23191
23192
23193
23194
23195
23196
23197
23198
23199
23200
23201
23202
23203
23204
23205
23206
23207
23208
23209
23210
23211
23212
23213
23214
23215
23216
23217
23218
23219
23220
23221
23222
23223
23224
23225
23226
23227
23228
23229
23230
23231
23232
23233
23234
23235
23236
23237
23238
23239
23240
23241
23242
23243
23244
23245
23246
23247
23248
23249
23250
23251
23252
23253
23254
23255
23256
23257
23258
23259
23260
23261
23262
23263
23264
23265
23266
23267
23268
23269
23270
23271
23272
23273
23274
23275
23276
23277
23278
23279
23280
23281
23282
23283
23284
23285
23286
23287
23288
23289
23290
23291
23292
23293
23294
23295
23296
23297
23298
23299
23300
23301
23302
23303
23304
23305
23306
23307
23308
23309
23310
23311
23312
23313
23314
23315
23316
23317
23318
23319
23320
23321
23322
23323
23324
23325
23326
23327
23328
23329
23330
23331
23332
23333
23334
23335
23336
23337
23338
23339
23340
23341
23342
23343
23344
23345
23346
23347
23348
23349
23350
23351
23352
23353
23354
23355
23356
23357
23358
23359
23360
23361
23362
23363
23364
23365
23366
23367
23368
23369
23370
23371
23372
23373
23374
23375
23376
23377
23378
23379
23380
23381
23382
23383
23384
23385
23386
23387
23388
23389
23390
23391
23392
23393
23394
23395
23396
23397
23398
23399
23400
23401
23402
23403
23404
23405
23406
23407
23408
23409
23410
23411
23412
23413
23414
23415
23416
23417
23418
23419
23420
23421
23422
23423
23424
23425
23426
23427
23428
23429
23430
23431
23432
23433
23434
23435
23436
23437
23438
23439
23440
23441
23442
23443
23444
23445
23446
23447
23448
23449
23450
23451
23452
23453
23454
23455
23456
23457
23458
23459
23460
23461
23462
23463
23464
23465
23466
23467
23468
23469
23470
23471
23472
23473
23474
23475
23476
23477
23478
23479
23480
23481
23482
23483
23484
23485
23486
23487
23488
23489
23490
23491
23492
23493
23494
23495
23496
23497
23498
23499
23500
23501
23502
23503
23504
23505
23506
23507
23508
23509
23510
23511
23512
23513
23514
23515
23516
23517
23518
23519
23520
23521
23522
23523
23524
23525
23526
23527
23528
23529
23530
23531
23532
23533
23534
23535
23536
23537
23538
23539
23540
23541
23542
23543
23544
23545
23546
23547
23548
23549
23550
23551
23552
23553
23554
23555
23556
23557
23558
23559
23560
23561
23562
23563
23564
23565
23566
23567
23568
23569
23570
23571
23572
23573
23574
23575
23576
23577
23578
23579
23580
23581
23582
23583
23584
23585
23586
23587
23588
23589
23590
23591
23592
23593
23594
23595
23596
23597
23598
23599
23600
23601
23602
23603
23604
23605
23606
23607
23608
23609
23610
23611
23612
23613
23614
23615
23616
23617
23618
23619
23620
23621
23622
23623
23624
23625
23626
23627
23628
23629
23630
23631
23632
23633
23634
23635
23636
23637
23638
23639
23640
23641
23642
23643
23644
23645
23646
23647
23648
23649
23650
23651
23652
23653
23654
23655
23656
23657
23658
23659
23660
23661
23662
23663
23664
23665
23666
23667
23668
23669
23670
23671
23672
23673
23674
23675
23676
23677
23678
23679
23680
23681
23682
23683
23684
23685
23686
23687
23688
23689
23690
23691
23692
23693
23694
23695
23696
23697
23698
23699
23700
23701
23702
23703
23704
23705
23706
23707
23708
23709
23710
23711
23712
23713
23714
23715
23716
23717
23718
23719
23720
23721
23722
23723
23724
23725
23726
23727
23728
23729
23730
23731
23732
23733
23734
23735
23736
23737
23738
23739
23740
23741
23742
23743
23744
23745
23746
23747
23748
23749
23750
23751
23752
23753
23754
23755
23756
23757
23758
23759
23760
23761
23762
23763
23764
23765
23766
23767
23768
23769
23770
23771
23772
23773
23774
23775
23776
23777
23778
23779
23780
23781
23782
23783
23784
23785
23786
23787
23788
23789
23790
23791
23792
23793
23794
23795
23796
23797
23798
23799
23800
23801
23802
23803
23804
23805
23806
23807
23808
23809
23810
23811
23812
23813
23814
23815
23816
23817
23818
23819
23820
23821
23822
23823
23824
23825
23826
23827
23828
23829
23830
23831
23832
23833
23834
23835
23836
23837
23838
23839
23840
23841
23842
23843
23844
23845
23846
23847
23848
23849
23850
23851
23852
23853
23854
23855
23856
23857
23858
23859
23860
23861
23862
/*
 * Asterisk -- An open source telephony toolkit.
 *
 * Copyright (C) 1999 - 2006, Digium, Inc.
 *
 * Mark Spencer <markster@digium.com>
 *
 * See http://www.asterisk.org for more information about
 * the Asterisk project. Please do not directly contact
 * any of the maintainers of this project for assistance;
 * the project provides a web site, mailing lists and IRC
 * channels for your use.
 *
 * This program is free software, distributed under the terms of
 * the GNU General Public License Version 2. See the LICENSE file
 * at the top of the source tree.
 */

/*!
 * \file
 * \brief Implementation of Session Initiation Protocol
 *
 * \author Mark Spencer <markster@digium.com>
 *
 * See Also:
 * \arg \ref AstCREDITS
 *
 * Implementation of RFC 3261 - without S/MIME, TCP and TLS support
 * Configuration file \link Config_sip sip.conf \endlink
 *
 *
 * \todo Better support of forking
 * \todo VIA branch tag transaction checking
 * \todo Transaction support
 * \todo We need to test TCP sessions with SIP proxies and in regards
 *       to the SIP outbound specs.
 *
 * \ingroup channel_drivers
 *
 * \par Overview of the handling of SIP sessions
 * The SIP channel handles several types of SIP sessions, or dialogs,
 * not all of them being "telephone calls".
 * - Incoming calls that will be sent to the PBX core
 * - Outgoing calls, generated by the PBX
 * - SIP subscriptions and notifications of states and voicemail messages
 * - SIP registrations, both inbound and outbound
 * - SIP peer management (peerpoke, OPTIONS)
 * - SIP text messages
 *
 * In the SIP channel, there's a list of active SIP dialogs, which includes
 * all of these when they are active. "sip show channels" in the CLI will
 * show most of these, excluding subscriptions which are shown by
 * "sip show subscriptions"
 *
 * \par incoming packets
 * Incoming packets are received in the monitoring thread, then handled by
 * sipsock_read(). This function parses the packet and matches an existing
 * dialog or starts a new SIP dialog.
 * 
 * sipsock_read sends the packet to handle_incoming(), that parses a bit more.
 * If it is a response to an outbound request, the packet is sent to handle_response().
 * If it is a request, handle_incoming() sends it to one of a list of functions
 * depending on the request type - INVITE, OPTIONS, REFER, BYE, CANCEL etc
 * sipsock_read locks the ast_channel if it exists (an active call) and
 * unlocks it after we have processed the SIP message.
 *
 * A new INVITE is sent to handle_request_invite(), that will end up
 * starting a new channel in the PBX, the new channel after that executing
 * in a separate channel thread. This is an incoming "call".
 * When the call is answered, either by a bridged channel or the PBX itself
 * the sip_answer() function is called.
 *
 * The actual media - Video or Audio - is mostly handled by the RTP subsystem
 * in rtp.c 
 * 
 * \par Outbound calls
 * Outbound calls are set up by the PBX through the sip_request_call()
 * function. After that, they are activated by sip_call().
 * 
 * \par Hanging up
 * The PBX issues a hangup on both incoming and outgoing calls through
 * the sip_hangup() function
 */

/*** MODULEINFO
        <depend>chan_local</depend>
 ***/

/*!  \page sip_session_timers SIP Session Timers in Asterisk Chan_sip

	The SIP Session-Timers is an extension of the SIP protocol that allows end-points and proxies to
	refresh a session periodically. The sessions are kept alive by sending a RE-INVITE or UPDATE
	request at a negotiated interval. If a session refresh fails then all the entities that support Session-
	Timers clear their internal session state. In addition, UAs generate a BYE request in order to clear
	the state in the proxies and the remote UA (this is done for the benefit of SIP entities in the path
	that do not support Session-Timers).

	The Session-Timers can be configured on a system-wide, per-user, or per-peer basis. The peruser/
	per-peer settings override the global settings. The following new parameters have been
	added to the sip.conf file.
		session-timers=["accept", "originate", "refuse"]
		session-expires=[integer]
		session-minse=[integer]
		session-refresher=["uas", "uac"]

	The session-timers parameter in sip.conf defines the mode of operation of SIP session-timers feature in
	Asterisk. The Asterisk can be configured in one of the following three modes:

	1. Accept :: In the "accept" mode, the Asterisk server honors session-timers requests
		made by remote end-points. A remote end-point can request Asterisk to engage
		session-timers by either sending it an INVITE request with a "Supported: timer"
		header in it or by responding to Asterisk's INVITE with a 200 OK that contains
		Session-Expires: header in it. In this mode, the Asterisk server does not 
		request session-timers from remote end-points. This is the default mode.
	2. Originate :: In the "originate" mode, the Asterisk server requests the remote 
		end-points to activate session-timers in addition to honoring such requests
		made by the remote end-pints. In order to get as much protection as possible
		against hanging SIP channels due to network or end-point failures, Asterisk
		resends periodic re-INVITEs even if a remote end-point does not support
		the session-timers feature.
	3. Refuse :: In the "refuse" mode, Asterisk acts as if it does not support session-
		timers for inbound or outbound requests. If a remote end-point requests
		session-timers in a dialog, then Asterisk ignores that request unless it's
		noted as a requirement (Require: header), in which case the INVITE is 
		rejected with a 420 Bad Extension response.

*/

#include "asterisk.h"

ASTERISK_FILE_VERSION(__FILE__, "$Revision$")

#include <ctype.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/signal.h>
#include <regex.h>

#include "asterisk/network.h"
#include "asterisk/paths.h"	/* need ast_config_AST_SYSTEM_NAME */

#include "asterisk/lock.h"
#include "asterisk/channel.h"
#include "asterisk/config.h"
#include "asterisk/module.h"
#include "asterisk/pbx.h"
#include "asterisk/sched.h"
#include "asterisk/io.h"
#include "asterisk/rtp.h"
#include "asterisk/udptl.h"
#include "asterisk/acl.h"
#include "asterisk/manager.h"
#include "asterisk/callerid.h"
#include "asterisk/cli.h"
#include "asterisk/app.h"
#include "asterisk/musiconhold.h"
#include "asterisk/dsp.h"
#include "asterisk/features.h"
#include "asterisk/srv.h"
#include "asterisk/astdb.h"
#include "asterisk/causes.h"
#include "asterisk/utils.h"
#include "asterisk/file.h"
#include "asterisk/astobj.h"
#include "asterisk/astobj2.h"
#include "asterisk/dnsmgr.h"
#include "asterisk/devicestate.h"
#include "asterisk/linkedlists.h"
#include "asterisk/stringfields.h"
#include "asterisk/monitor.h"
#include "asterisk/netsock.h"
#include "asterisk/localtime.h"
#include "asterisk/abstract_jb.h"
#include "asterisk/threadstorage.h"
#include "asterisk/translate.h"
#include "asterisk/ast_version.h"
#include "asterisk/event.h"
#include "asterisk/tcptls.h"
#include "asterisk/strings.h"

#ifndef FALSE
#define FALSE    0
#endif

#ifndef TRUE
#define TRUE     1
#endif

#define	SIPBUFSIZE		512

#define XMIT_ERROR		-2

#define SIP_RESERVED ";/?:@&=+$,# "

/* #define VOCAL_DATA_HACK */

#define DEFAULT_DEFAULT_EXPIRY  120
#define DEFAULT_MIN_EXPIRY      60
#define DEFAULT_MAX_EXPIRY      3600
#define DEFAULT_REGISTRATION_TIMEOUT 20
#define DEFAULT_MAX_FORWARDS    "70"

/* guard limit must be larger than guard secs */
/* guard min must be < 1000, and should be >= 250 */
#define EXPIRY_GUARD_SECS       15                /*!< How long before expiry do we reregister */
#define EXPIRY_GUARD_LIMIT      30                /*!< Below here, we use EXPIRY_GUARD_PCT instead of 
	                                                 EXPIRY_GUARD_SECS */
#define EXPIRY_GUARD_MIN        500                /*!< This is the minimum guard time applied. If 
                                                   GUARD_PCT turns out to be lower than this, it 
                                                   will use this time instead.
                                                   This is in milliseconds. */
#define EXPIRY_GUARD_PCT        0.20                /*!< Percentage of expires timeout to use when 
                                                    below EXPIRY_GUARD_LIMIT */
#define DEFAULT_EXPIRY 900                          /*!< Expire slowly */

static int min_expiry = DEFAULT_MIN_EXPIRY;        /*!< Minimum accepted registration time */
static int max_expiry = DEFAULT_MAX_EXPIRY;        /*!< Maximum accepted registration time */
static int default_expiry = DEFAULT_DEFAULT_EXPIRY;

#define CALLERID_UNKNOWN             "Anonymous"
#define FROMDOMAIN_INVALID           "anonymous.invalid"

#define DEFAULT_MAXMS                2000             /*!< Qualification: Must be faster than 2 seconds by default */
#define DEFAULT_QUALIFYFREQ          60 * 1000        /*!< Qualification: How often to check for the host to be up */
#define DEFAULT_FREQ_NOTOK           10 * 1000        /*!< Qualification: How often to check, if the host is down... */

#define DEFAULT_RETRANS              1000             /*!< How frequently to retransmit Default: 2 * 500 ms in RFC 3261 */
#define MAX_RETRANS                  6                /*!< Try only 6 times for retransmissions, a total of 7 transmissions */
#define SIP_TIMER_T1                 500              /* SIP timer T1 (according to RFC 3261) */
#define SIP_TRANS_TIMEOUT            64 * SIP_TIMER_T1/*!< SIP request timeout (rfc 3261) 64*T1 
                                                      \todo Use known T1 for timeout (peerpoke)
                                                      */
#define DEFAULT_TRANS_TIMEOUT        -1               /* Use default SIP transaction timeout */
#define PROVIS_KEEPALIVE_TIMEOUT     60000            /*!< How long to wait before retransmitting a provisional response (rfc 3261 13.3.1.1) */
#define MAX_AUTHTRIES                3                /*!< Try authentication three times, then fail */

#define SIP_MAX_HEADERS              64               /*!< Max amount of SIP headers to read */
#define SIP_MAX_LINES                256              /*!< Max amount of lines in SIP attachment (like SDP) */
#define SIP_MAX_PACKET               4096             /*!< Also from RFC 3261 (2543), should sub headers tho */

#define INITIAL_CSEQ                 101              /*!< our initial sip sequence number */

#define DEFAULT_MAX_SE               1800             /*!< Session-Timer Default Session-Expires period (RFC 4028) */
#define DEFAULT_MIN_SE               90               /*!< Session-Timer Default Min-SE period (RFC 4028) */

#define SDP_MAX_RTPMAP_CODECS        32               /*!< Maximum number of codecs allowed in received SDP */

/*! \brief Global jitterbuffer configuration - by default, jb is disabled */
static struct ast_jb_conf default_jbconf =
{
	.flags = 0,
	.max_size = -1,
	.resync_threshold = -1,
	.impl = "",
	.target_extra = -1,
};
static struct ast_jb_conf global_jbconf;	/*!< Global jitterbuffer configuration */

static const char config[] = "sip.conf";	/*!< Main configuration file */
static const char notify_config[] = "sip_notify.conf";	/*!< Configuration file for sending Notify with CLI commands to reconfigure or reboot phones */

#define RTP 	1
#define NO_RTP	0

/*! \brief Authorization scheme for call transfers 
\note Not a bitfield flag, since there are plans for other modes,
	like "only allow transfers for authenticated devices" */
enum transfermodes {
	TRANSFER_OPENFORALL,            /*!< Allow all SIP transfers */
	TRANSFER_CLOSED,                /*!< Allow no SIP transfers */
};


enum sip_result {
	AST_SUCCESS = 0,
	AST_FAILURE = -1,
};

/*! \brief States for the INVITE transaction, not the dialog 
	\note this is for the INVITE that sets up the dialog
*/
enum invitestates {
	INV_NONE = 0,	        /*!< No state at all, maybe not an INVITE dialog */
	INV_CALLING = 1,	/*!< Invite sent, no answer */
	INV_PROCEEDING = 2,	/*!< We got/sent 1xx message */
	INV_EARLY_MEDIA = 3,    /*!< We got 18x message with to-tag back */
	INV_COMPLETED = 4,	/*!< Got final response with error. Wait for ACK, then CONFIRMED */
	INV_CONFIRMED = 5,	/*!< Confirmed response - we've got an ack (Incoming calls only) */
	INV_TERMINATED = 6,	/*!< Transaction done - either successful (AST_STATE_UP) or failed, but done 
				     The only way out of this is a BYE from one side */
	INV_CANCELLED = 7,	/*!< Transaction cancelled by client or server in non-terminated state */
};

enum xmittype {
	XMIT_CRITICAL = 2,              /*!< Transmit critical SIP message reliably, with re-transmits.
                                              If it fails, it's critical and will cause a teardown of the session */
	XMIT_RELIABLE = 1,              /*!< Transmit SIP message reliably, with re-transmits */
	XMIT_UNRELIABLE = 0,            /*!< Transmit SIP message without bothering with re-transmits */
};

enum parse_register_result {
	PARSE_REGISTER_DENIED,
	PARSE_REGISTER_FAILED,
	PARSE_REGISTER_UPDATE,
	PARSE_REGISTER_QUERY,
};

enum subscriptiontype { 
	NONE = 0,
	XPIDF_XML,
	DIALOG_INFO_XML,
	CPIM_PIDF_XML,
	PIDF_XML,
	MWI_NOTIFICATION
};

/*! \brief Subscription types that we support. We support
   - dialoginfo updates (really device status, not dialog info as was the original intent of the standard)
   - SIMPLE presence used for device status
   - Voicemail notification subscriptions
*/
static const struct cfsubscription_types {
	enum subscriptiontype type;
	const char * const event;
	const char * const mediatype;
	const char * const text;
} subscription_types[] = {
	{ NONE,		   "-",        "unknown",	             "unknown" },
 	/* RFC 4235: SIP Dialog event package */
	{ DIALOG_INFO_XML, "dialog",   "application/dialog-info+xml", "dialog-info+xml" },
	{ CPIM_PIDF_XML,   "presence", "application/cpim-pidf+xml",   "cpim-pidf+xml" },  /* RFC 3863 */
	{ PIDF_XML,        "presence", "application/pidf+xml",        "pidf+xml" },       /* RFC 3863 */
	{ XPIDF_XML,       "presence", "application/xpidf+xml",       "xpidf+xml" },       /* Pre-RFC 3863 with MS additions */
	{ MWI_NOTIFICATION,	"message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
};


/*! \brief Authentication types - proxy or www authentication 
	\note Endpoints, like Asterisk, should always use WWW authentication to
	allow multiple authentications in the same call - to the proxy and
	to the end point.
*/
enum sip_auth_type {
	PROXY_AUTH = 407,
	WWW_AUTH = 401,
};

/*! \brief Authentication result from check_auth* functions */
enum check_auth_result {
	AUTH_DONT_KNOW = -100,	/*!< no result, need to check further */
		/* XXX maybe this is the same as AUTH_NOT_FOUND */

	AUTH_SUCCESSFUL = 0,
	AUTH_CHALLENGE_SENT = 1,
	AUTH_SECRET_FAILED = -1,
	AUTH_USERNAME_MISMATCH = -2,
	AUTH_NOT_FOUND = -3,	/*!< returned by register_verify */
	AUTH_FAKE_AUTH = -4,
	AUTH_UNKNOWN_DOMAIN = -5,
	AUTH_PEER_NOT_DYNAMIC = -6,
	AUTH_ACL_FAILED = -7,
	AUTH_BAD_TRANSPORT = -8,
};

/*! \brief States for outbound registrations (with register= lines in sip.conf */
enum sipregistrystate {
	REG_STATE_UNREGISTERED = 0,	/*!< We are not registered 
		 *  \note Initial state. We should have a timeout scheduled for the initial
		 * (or next) registration transmission, calling sip_reregister
		 */

	REG_STATE_REGSENT,	/*!< Registration request sent 
		 * \note sent initial request, waiting for an ack or a timeout to
		 * retransmit the initial request.
		*/

	REG_STATE_AUTHSENT,	/*!< We have tried to authenticate 
		 * \note entered after transmit_register with auth info,
		 * waiting for an ack.
		 */

	REG_STATE_REGISTERED,	/*!< Registered and done */

	REG_STATE_REJECTED,	/*!< Registration rejected *
		 * \note only used when the remote party has an expire larger than
		 * our max-expire. This is a final state from which we do not
		 * recover (not sure how correctly).
		 */

	REG_STATE_TIMEOUT,	/*!< Registration timed out *
		* \note XXX unused */

	REG_STATE_NOAUTH,	/*!< We have no accepted credentials
		 * \note fatal - no chance to proceed */

	REG_STATE_FAILED,	/*!< Registration failed after several tries
		 * \note fatal - no chance to proceed */
};

/*! \brief Modes in which Asterisk can be configured to run SIP Session-Timers */
enum st_mode {
        SESSION_TIMER_MODE_INVALID = 0, /*!< Invalid value */ 
        SESSION_TIMER_MODE_ACCEPT,      /*!< Honor inbound Session-Timer requests */
        SESSION_TIMER_MODE_ORIGINATE,   /*!< Originate outbound and honor inbound requests */
        SESSION_TIMER_MODE_REFUSE       /*!< Ignore inbound Session-Timers requests */
};

/*! \brief The entity playing the refresher role for Session-Timers */
enum st_refresher {
        SESSION_TIMER_REFRESHER_AUTO,    /*!< Negotiated                      */
        SESSION_TIMER_REFRESHER_UAC,     /*!< Session is refreshed by the UAC */
        SESSION_TIMER_REFRESHER_UAS      /*!< Session is refreshed by the UAS */
};

/*!< Define some SIP transports */
enum sip_transport {
	SIP_TRANSPORT_UDP = 1,
	SIP_TRANSPORT_TCP = 1 << 1,
	SIP_TRANSPORT_TLS = 1 << 2,
};

/*! \brief definition of a sip proxy server
 *
 * For outbound proxies, this is allocated in the SIP peer dynamically or
 * statically as the global_outboundproxy. The pointer in a SIP message is just
 * a pointer and should *not* be de-allocated.
 */
struct sip_proxy {
	char name[MAXHOSTNAMELEN];      /*!< DNS name of domain/host or IP */
	struct sockaddr_in ip;          /*!< Currently used IP address and port */
	time_t last_dnsupdate;          /*!< When this was resolved */
	enum sip_transport transport;
	int force;                      /*!< If it's an outbound proxy, Force use of this outbound proxy for all outbound requests */
	/* Room for a SRV record chain based on the name */
};

/*! \brief States whether a SIP message can create a dialog in Asterisk. */
enum can_create_dialog {
	CAN_NOT_CREATE_DIALOG,
	CAN_CREATE_DIALOG,
	CAN_CREATE_DIALOG_UNSUPPORTED_METHOD,
};

/*! \brief SIP Request methods known by Asterisk 

   \note Do _NOT_ make any changes to this enum, or the array following it;
   if you think you are doing the right thing, you are probably
   not doing the right thing. If you think there are changes
   needed, get someone else to review them first _before_
   submitting a patch. If these two lists do not match properly
   bad things will happen.
*/

enum sipmethod {
	SIP_UNKNOWN,		/*!< Unknown response */
	SIP_RESPONSE,		/*!< Not request, response to outbound request */
	SIP_REGISTER,		/*!< Registration to the mothership, tell us where you are located */
	SIP_OPTIONS,		/*!< Check capabilities of a device, used for "ping" too */
	SIP_NOTIFY,		/*!< Status update, Part of the event package standard, result of a SUBSCRIBE or a REFER */
	SIP_INVITE,		/*!< Set up a session */
	SIP_ACK,		/*!< End of a three-way handshake started with INVITE. */
	SIP_PRACK,		/*!< Reliable pre-call signalling. Not supported in Asterisk. */
	SIP_BYE,		/*!< End of a session */
	SIP_REFER,		/*!< Refer to another URI (transfer) */
	SIP_SUBSCRIBE,		/*!< Subscribe for updates (voicemail, session status, device status, presence) */
	SIP_MESSAGE,		/*!< Text messaging */
	SIP_UPDATE,		/*!< Update a dialog. We can send UPDATE; but not accept it */
	SIP_INFO,		/*!< Information updates during a session */
	SIP_CANCEL,		/*!< Cancel an INVITE */
	SIP_PUBLISH,		/*!< Not supported in Asterisk */
	SIP_PING,		/*!< Not supported at all, no standard but still implemented out there */
};

/*! \brief The core structure to setup dialogs. We parse incoming messages by using
	structure and then route the messages according to the type.

      \note Note that sip_methods[i].id == i must hold or the code breaks */
static const struct  cfsip_methods { 
	enum sipmethod id;
	int need_rtp;		/*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
	char * const text;
	enum can_create_dialog can_create;
} sip_methods[] = {
	{ SIP_UNKNOWN,	 RTP,    "-UNKNOWN-", 	CAN_CREATE_DIALOG },
	{ SIP_RESPONSE,	 NO_RTP, "SIP/2.0",	CAN_NOT_CREATE_DIALOG },
	{ SIP_REGISTER,	 NO_RTP, "REGISTER", 	CAN_CREATE_DIALOG },
 	{ SIP_OPTIONS,	 NO_RTP, "OPTIONS", 	CAN_CREATE_DIALOG },
	{ SIP_NOTIFY,	 NO_RTP, "NOTIFY", 	CAN_CREATE_DIALOG },
	{ SIP_INVITE,	 RTP,    "INVITE", 	CAN_CREATE_DIALOG },
	{ SIP_ACK,	 NO_RTP, "ACK", 	CAN_NOT_CREATE_DIALOG },
	{ SIP_PRACK,	 NO_RTP, "PRACK", 	CAN_NOT_CREATE_DIALOG },
	{ SIP_BYE,	 NO_RTP, "BYE", 	CAN_NOT_CREATE_DIALOG },
	{ SIP_REFER,	 NO_RTP, "REFER", 	CAN_CREATE_DIALOG },
	{ SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE", 	CAN_CREATE_DIALOG },
	{ SIP_MESSAGE,	 NO_RTP, "MESSAGE", 	CAN_CREATE_DIALOG },
	{ SIP_UPDATE,	 NO_RTP, "UPDATE", 	CAN_NOT_CREATE_DIALOG },
	{ SIP_INFO,	 NO_RTP, "INFO", 	CAN_NOT_CREATE_DIALOG },
	{ SIP_CANCEL,	 NO_RTP, "CANCEL", 	CAN_NOT_CREATE_DIALOG },
	{ SIP_PUBLISH,	 NO_RTP, "PUBLISH", 	CAN_CREATE_DIALOG_UNSUPPORTED_METHOD },
	{ SIP_PING,	 NO_RTP, "PING", 	CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
};

static unsigned int chan_idx;

/*!  Define SIP option tags, used in Require: and Supported: headers 
 	We need to be aware of these properties in the phones to use 
	the replace: header. We should not do that without knowing
	that the other end supports it... 
	This is nothing we can configure, we learn by the dialog
	Supported: header on the REGISTER (peer) or the INVITE
	(other devices)
	We are not using many of these today, but will in the future.
	This is documented in RFC 3261
*/
#define SUPPORTED		1
#define NOT_SUPPORTED		0

/* SIP options */
#define SIP_OPT_REPLACES	(1 << 0)
#define SIP_OPT_100REL		(1 << 1)
#define SIP_OPT_TIMER		(1 << 2)
#define SIP_OPT_EARLY_SESSION	(1 << 3)
#define SIP_OPT_JOIN		(1 << 4)
#define SIP_OPT_PATH		(1 << 5)
#define SIP_OPT_PREF		(1 << 6)
#define SIP_OPT_PRECONDITION	(1 << 7)
#define SIP_OPT_PRIVACY		(1 << 8)
#define SIP_OPT_SDP_ANAT	(1 << 9)
#define SIP_OPT_SEC_AGREE	(1 << 10)
#define SIP_OPT_EVENTLIST	(1 << 11)
#define SIP_OPT_GRUU		(1 << 12)
#define SIP_OPT_TARGET_DIALOG	(1 << 13)
#define SIP_OPT_NOREFERSUB	(1 << 14)
#define SIP_OPT_HISTINFO	(1 << 15)
#define SIP_OPT_RESPRIORITY	(1 << 16)
#define SIP_OPT_UNKNOWN		(1 << 17)


/*! \brief List of well-known SIP options. If we get this in a require,
   we should check the list and answer accordingly. */
static const struct cfsip_options {
	int id;			/*!< Bitmap ID */
	int supported;		/*!< Supported by Asterisk ? */
	char * const text;	/*!< Text id, as in standard */
} sip_options[] = {	/* XXX used in 3 places */
	/* RFC3891: Replaces: header for transfer */
	{ SIP_OPT_REPLACES,	SUPPORTED,	"replaces" },	
	/* One version of Polycom firmware has the wrong label */
	{ SIP_OPT_REPLACES,	SUPPORTED,	"replace" },	
	/* RFC3262: PRACK 100% reliability */
	{ SIP_OPT_100REL,	NOT_SUPPORTED,	"100rel" },	
	/* RFC4028: SIP Session-Timers */
	{ SIP_OPT_TIMER,	SUPPORTED,	"timer" },
	/* RFC3959: SIP Early session support */
	{ SIP_OPT_EARLY_SESSION, NOT_SUPPORTED,	"early-session" },
	/* RFC3911: SIP Join header support */
	{ SIP_OPT_JOIN,		NOT_SUPPORTED,	"join" },
	/* RFC3327: Path support */
	{ SIP_OPT_PATH,		NOT_SUPPORTED,	"path" },
	/* RFC3840: Callee preferences */
	{ SIP_OPT_PREF,		NOT_SUPPORTED,	"pref" },
	/* RFC3312: Precondition support */
	{ SIP_OPT_PRECONDITION,	NOT_SUPPORTED,	"precondition" },
	/* RFC3323: Privacy with proxies*/
	{ SIP_OPT_PRIVACY,	NOT_SUPPORTED,	"privacy" },
	/* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
	{ SIP_OPT_SDP_ANAT,	NOT_SUPPORTED,	"sdp-anat" },
	/* RFC3329: Security agreement mechanism */
	{ SIP_OPT_SEC_AGREE,	NOT_SUPPORTED,	"sec_agree" },
	/* SIMPLE events:  RFC4662 */
	{ SIP_OPT_EVENTLIST,	NOT_SUPPORTED,	"eventlist" },
	/* GRUU: Globally Routable User Agent URI's */
	{ SIP_OPT_GRUU,		NOT_SUPPORTED,	"gruu" },
	/* RFC4538: Target-dialog */
	{ SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED,	"tdialog" },
	/* Disable the REFER subscription, RFC 4488 */
	{ SIP_OPT_NOREFERSUB,	NOT_SUPPORTED,	"norefersub" },
	/* ietf-sip-history-info-06.txt */
	{ SIP_OPT_HISTINFO,	NOT_SUPPORTED,	"histinfo" },
	/* ietf-sip-resource-priority-10.txt */
	{ SIP_OPT_RESPRIORITY,	NOT_SUPPORTED,	"resource-priority" },
};


/*! \brief SIP Methods we support 
	\todo This string should be set dynamically. We only support REFER and SUBSCRIBE is we have
	allowsubscribe and allowrefer on in sip.conf.
*/
#define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY, INFO"

/*! \brief SIP Extensions we support */
#define SUPPORTED_EXTENSIONS "replaces, timer" 

/*! \brief Standard SIP and TLS port from RFC 3261. DO NOT CHANGE THIS */
#define STANDARD_SIP_PORT	5060
#define STANDARD_TLS_PORT	5061
/*! \note in many SIP headers, absence of a port number implies port 5060,
 * and this is why we cannot change the above constant.
 * There is a limited number of places in asterisk where we could,
 * in principle, use a different "default" port number, but
 * we do not support this feature at the moment.
 * You can run Asterisk with SIP on a different port with a configuration
 * option. If you change this value, the signalling will be incorrect.
 */

/*! \name DefaultValues Default values, set and reset in reload_config before reading configuration 

   These are default values in the source. There are other recommended values in the
   sip.conf.sample for new installations. These may differ to keep backwards compatibility,
   yet encouraging new behaviour on new installations 
 */
/*@{*/ 
#define DEFAULT_CONTEXT		"default"
#define DEFAULT_MOHINTERPRET    "default"
#define DEFAULT_MOHSUGGEST      ""
#define DEFAULT_VMEXTEN 	"asterisk"
#define DEFAULT_CALLERID 	"asterisk"
#define DEFAULT_NOTIFYMIME 	"application/simple-message-summary"
#define DEFAULT_ALLOWGUEST	TRUE
#define DEFAULT_CALLCOUNTER	FALSE
#define DEFAULT_SRVLOOKUP	TRUE		/*!< Recommended setting is ON */
#define DEFAULT_COMPACTHEADERS	FALSE
#define DEFAULT_TOS_SIP         0               /*!< Call signalling packets should be marked as DSCP CS3, but the default is 0 to be compatible with previous versions. */
#define DEFAULT_TOS_AUDIO       0               /*!< Audio packets should be marked as DSCP EF (Expedited Forwarding), but the default is 0 to be compatible with previous versions. */
#define DEFAULT_TOS_VIDEO       0               /*!< Video packets should be marked as DSCP AF41, but the default is 0 to be compatible with previous versions. */
#define DEFAULT_TOS_TEXT        0               /*!< Text packets should be marked as XXXX XXXX, but the default is 0 to be compatible with previous versions. */
#define DEFAULT_COS_SIP         4
#define DEFAULT_COS_AUDIO       5
#define DEFAULT_COS_VIDEO       6
#define DEFAULT_COS_TEXT        5
#define DEFAULT_ALLOW_EXT_DOM	TRUE
#define DEFAULT_REALM		"asterisk"
#define DEFAULT_NOTIFYRINGING	TRUE
#define DEFAULT_PEDANTIC	FALSE
#define DEFAULT_AUTOCREATEPEER	FALSE
#define DEFAULT_QUALIFY		FALSE
#define DEFAULT_REGEXTENONQUALIFY FALSE
#define DEFAULT_T1MIN		100		/*!< 100 MS for minimal roundtrip time */
#define DEFAULT_MAX_CALL_BITRATE (384)		/*!< Max bitrate for video */
#ifndef DEFAULT_USERAGENT
#define DEFAULT_USERAGENT "Asterisk PBX"	/*!< Default Useragent: header unless re-defined in sip.conf */
#define DEFAULT_SDPSESSION "Asterisk PBX"	/*!< Default SDP session name, (s=) header unless re-defined in sip.conf */
#define DEFAULT_SDPOWNER "root"		/*!< Default SDP username field in (o=) header unless re-defined in sip.conf */
#endif
/*@}*/ 

/*! \name DefaultSettings
	Default setttings are used as a channel setting and as a default when
	configuring devices 
*/
/*@{*/ 
static char default_context[AST_MAX_CONTEXT];
static char default_subscribecontext[AST_MAX_CONTEXT];
static char default_language[MAX_LANGUAGE];
static char default_callerid[AST_MAX_EXTENSION];
static char default_fromdomain[AST_MAX_EXTENSION];
static char default_notifymime[AST_MAX_EXTENSION];
static int default_qualify;		/*!< Default Qualify= setting */
static char default_vmexten[AST_MAX_EXTENSION];
static char default_mohinterpret[MAX_MUSICCLASS];  /*!< Global setting for moh class to use when put on hold */
static char default_mohsuggest[MAX_MUSICCLASS];	   /*!< Global setting for moh class to suggest when putting 
                                                    *   a bridged channel on hold */
static int default_maxcallbitrate;	/*!< Maximum bitrate for call */
static struct ast_codec_pref default_prefs;		/*!< Default codec prefs */

/*! \brief a place to store all global settings for the sip channel driver */
struct sip_settings {
	int peer_rtupdate;	/*!< G: Update database with registration data for peer? */
	int rtsave_sysname;	/*!< G: Save system name at registration? */
	int ignore_regexpire;	/*!< G: Ignore expiration of peer  */
};

static struct sip_settings sip_cfg;
/*@}*/ 

/*! \name GlobalSettings
	Global settings apply to the channel (often settings you can change in the general section
	of sip.conf
*/
/*@{*/ 
static int global_directrtpsetup;	/*!< Enable support for Direct RTP setup (no re-invites) */
static int global_limitonpeers;		/*!< Match call limit on peers only */
static int global_rtautoclear;		/*!< Realtime ?? */
static int global_notifyringing;	/*!< Send notifications on ringing */
static int global_notifyhold;		/*!< Send notifications on hold */
static int global_alwaysauthreject;	/*!< Send 401 Unauthorized for all failing requests */
static int global_srvlookup;		/*!< SRV Lookup on or off. Default is on */
static int pedanticsipchecking;		/*!< Extra checking ?  Default off */
static int autocreatepeer;		/*!< Auto creation of peers at registration? Default off. */
static int global_match_auth_username;		/*!< Match auth username if available instead of From: Default off. */
static int global_relaxdtmf;		/*!< Relax DTMF */
static int global_prematuremediafilter;	/*!< Enable/disable premature frames in a call (causing 183 early media) */
static int global_relaxdtmf;			/*!< Relax DTMF */
static int global_rtptimeout;		/*!< Time out call if no RTP */
static int global_rtpholdtimeout;	/*!< Time out call if no RTP during hold */
static int global_rtpkeepalive;		/*!< Send RTP keepalives */
static int global_reg_timeout;	
static int global_regattempts_max;	/*!< Registration attempts before giving up */
static int global_shrinkcallerid;	/*!< enable or disable shrinking of caller id  */
static int global_allowguest;		/*!< allow unauthenticated users/peers to connect? */
static int global_callcounter;		/*!< Enable call counters for all devices. This is currently enabled by setting the peer
						call-limit to 999. When we remove the call-limit from the code, we can make it
						with just a boolean flag in the device structure */
static int global_allowsubscribe;	/*!< Flag for disabling ALL subscriptions, this is FALSE only if all peers are FALSE 
					    the global setting is in globals_flags[1] */
static unsigned int global_tos_sip;		/*!< IP type of service for SIP packets */
static unsigned int global_tos_audio;		/*!< IP type of service for audio RTP packets */
static unsigned int global_tos_video;		/*!< IP type of service for video RTP packets */
static unsigned int global_tos_text;		/*!< IP type of service for text RTP packets */
static unsigned int global_cos_sip;		/*!< 802.1p class of service for SIP packets */
static unsigned int global_cos_audio;		/*!< 802.1p class of service for audio RTP packets */
static unsigned int global_cos_video;		/*!< 802.1p class of service for video RTP packets */
static unsigned int global_cos_text;		/*!< 802.1p class of service for text RTP packets */
static int compactheaders;		/*!< send compact sip headers */
static int recordhistory;		/*!< Record SIP history. Off by default */
static int dumphistory;			/*!< Dump history to verbose before destroying SIP dialog */
static char global_realm[MAXHOSTNAMELEN]; 		/*!< Default realm */
static char global_regcontext[AST_MAX_CONTEXT];		/*!< Context for auto-extensions */
static char global_useragent[AST_MAX_EXTENSION];	/*!< Useragent for the SIP channel */
static char global_sdpsession[AST_MAX_EXTENSION];	/*!< SDP session name for the SIP channel */
static char global_sdpowner[AST_MAX_EXTENSION];	/*!< SDP owner name for the SIP channel */
static int allow_external_domains;	/*!< Accept calls to external SIP domains? */
static int global_callevents;		/*!< Whether we send manager events or not */
static int global_t1;			/*!< T1 time */
static int global_t1min;		/*!< T1 roundtrip time minimum */
static int global_timer_b;    /*!< Timer B - RFC 3261 Section 17.1.1.2 */
static int global_regextenonqualify;  /*!< Whether to add/remove regexten when qualifying peers */
static int global_autoframing;          /*!< Turn autoframing on or off. */
static enum transfermodes global_allowtransfer;	/*!< SIP Refer restriction scheme */
static struct sip_proxy global_outboundproxy;	/*!< Outbound proxy */
static int global_matchexterniplocally; /*!< Match externip/externhost setting against localnet setting */
static int global_qualifyfreq; /*!< Qualify frequency */


/*! \brief Codecs that we support by default: */
static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
static enum st_mode global_st_mode;           /*!< Mode of operation for Session-Timers           */
static enum st_refresher global_st_refresher; /*!< Session-Timer refresher                        */
static int global_min_se;                     /*!< Lowest threshold for session refresh interval  */
static int global_max_se;                     /*!< Highest threshold for session refresh interval */

static int global_dynamic_exclude_static = 0;	/*!< Exclude static peers from contact registrations */
/*@}*/

/*! \brief Global list of addresses dynamic peers are not allowed to use */
static struct ast_ha *global_contact_ha = NULL;

/*! \name Object counters @{
 * \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
 * should be used to modify these values. */
static int suserobjs = 0;                /*!< Static users */
static int ruserobjs = 0;                /*!< Realtime users */
static int speerobjs = 0;                /*!< Static peers */
static int rpeerobjs = 0;                /*!< Realtime peers */
static int apeerobjs = 0;                /*!< Autocreated peer objects */
static int regobjs = 0;                  /*!< Registry objects */
/* }@ */

static struct ast_flags global_flags[2] = {{0}};        /*!< global SIP_ flags */
static int global_t38_maxdatagram;			/*!< global T.38 FaxMaxDatagram override */

static char used_context[AST_MAX_CONTEXT]; /*!< name of automatically created context for unloading */


AST_MUTEX_DEFINE_STATIC(netlock);

/*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
   when it's doing something critical. */

AST_MUTEX_DEFINE_STATIC(monlock);

AST_MUTEX_DEFINE_STATIC(sip_reload_lock);

/*! \brief This is the thread for the monitor which checks for input on the channels
   which are not currently in use.  */
static pthread_t monitor_thread = AST_PTHREADT_NULL;

static int sip_reloading = FALSE;                       /*!< Flag for avoiding multiple reloads at the same time */
static enum channelreloadreason sip_reloadreason;       /*!< Reason for last reload/load of configuration */

static struct sched_context *sched;     /*!< The scheduling context */
static struct io_context *io;           /*!< The IO context */
static int *sipsock_read_id;            /*!< ID of IO entry for sipsock FD */

#define DEC_CALL_LIMIT	0
#define INC_CALL_LIMIT	1
#define DEC_CALL_RINGING 2
#define INC_CALL_RINGING 3

/*!< The SIP socket definition */
struct sip_socket {
	enum sip_transport type;
	int fd;
	uint16_t port;
	struct ast_tcptls_session_instance *tcptls_session;	/* If tcp or tls, a socket manager */
};

/*! \brief sip_request: The data grabbed from the UDP socket
 *
 * \verbatim
 * Incoming messages: we first store the data from the socket in data[],
 * adding a trailing \0 to make string parsing routines happy.
 * Then call parse_request() and req.method = find_sip_method();
 * to initialize the other fields. The \r\n at the end of each line is   
 * replaced by \0, so that data[] is not a conforming SIP message anymore.
 * After this processing, rlPart1 is set to non-NULL to remember
 * that we can run get_header() on this kind of packet.
 *
 * parse_request() splits the first line as follows:
 * Requests have in the first line      method uri SIP/2.0
 *      rlPart1 = method; rlPart2 = uri;
 * Responses have in the first line     SIP/2.0 NNN description
 *      rlPart1 = SIP/2.0; rlPart2 = NNN + description;
 *
 * For outgoing packets, we initialize the fields with init_req() or init_resp()
 * (which fills the first line to "METHOD uri SIP/2.0" or "SIP/2.0 code text"),
 * and then fill the rest with add_header() and add_line().
 * The \r\n at the end of the line are still there, so the get_header()
 * and similar functions don't work on these packets. 
 * \endverbatim
 */
struct sip_request {
	char *rlPart1; 	        /*!< SIP Method Name or "SIP/2.0" protocol version */
	char *rlPart2; 	        /*!< The Request URI or Response Status */
	int len;                /*!< bytes used in data[], excluding trailing null terminator. Rarely used. */
	int headers;            /*!< # of SIP Headers */
	int method;             /*!< Method of this request */
	int lines;              /*!< Body Content */
	unsigned int sdp_start; /*!< the line number where the SDP begins */
	unsigned int sdp_count; /*!< the number of lines of SDP */
	char debug;		/*!< print extra debugging if non zero */
	char has_to_tag;	/*!< non-zero if packet has To: tag */
	char ignore;		/*!< if non-zero This is a re-transmit, ignore it */
	char *header[SIP_MAX_HEADERS];
	char *line[SIP_MAX_LINES];
	char data[SIP_MAX_PACKET];
	/* XXX Do we need to unref socket.ser when the request goes away? */
	struct sip_socket socket;	/*!< The socket used for this request */
	AST_LIST_ENTRY(sip_request) next;
};

/*! \brief structure used in transfers */
struct sip_dual {
	struct ast_channel *chan1;	/*!< First channel involved */
	struct ast_channel *chan2;	/*!< Second channel involved */
	struct sip_request req;		/*!< Request that caused the transfer (REFER) */
	int seqno;			/*!< Sequence number */
};

struct sip_pkt;

/*! \brief Parameters to the transmit_invite function */
struct sip_invite_param {
	int addsipheaders;		/*!< Add extra SIP headers */
	const char *uri_options;	/*!< URI options to add to the URI */
	const char *vxml_url;		/*!< VXML url for Cisco phones */
	char *auth;			/*!< Authentication */
	char *authheader;		/*!< Auth header */
	enum sip_auth_type auth_type;	/*!< Authentication type */
	const char *replaces;		/*!< Replaces header for call transfers */
	int transfer;			/*!< Flag - is this Invite part of a SIP transfer? (invite/replaces) */
};

/*! \brief Structure to save routing information for a SIP session */
struct sip_route {
	struct sip_route *next;
	char hop[0];
};

/*! \brief Modes for SIP domain handling in the PBX */
enum domain_mode {
	SIP_DOMAIN_AUTO,		/*!< This domain is auto-configured */
	SIP_DOMAIN_CONFIG,		/*!< This domain is from configuration */
};

/*! \brief Domain data structure. 
	\note In the future, we will connect this to a configuration tree specific
	for this domain
*/
struct domain {
	char domain[MAXHOSTNAMELEN];		/*!< SIP domain we are responsible for */
	char context[AST_MAX_EXTENSION];	/*!< Incoming context for this domain */
	enum domain_mode mode;			/*!< How did we find this domain? */
	AST_LIST_ENTRY(domain) list;		/*!< List mechanics */
};

static AST_LIST_HEAD_STATIC(domain_list, domain);	/*!< The SIP domain list */


/*! \brief sip_history: Structure for saving transactions within a SIP dialog */
struct sip_history {
	AST_LIST_ENTRY(sip_history) list;
	char event[0];	/* actually more, depending on needs */
};

AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */

/*! \brief sip_auth: Credentials for authentication to other SIP services */
struct sip_auth {
	char realm[AST_MAX_EXTENSION];  /*!< Realm in which these credentials are valid */
	char username[256];             /*!< Username */
	char secret[256];               /*!< Secret */
	char md5secret[256];            /*!< MD5Secret */
	struct sip_auth *next;          /*!< Next auth structure in list */
};

/*! \name SIPflags
	Various flags for the flags field in the pvt structure 
	Trying to sort these up (one or more of the following):
	D: Dialog
	P: Peer/user
	G: Global flag
	When flags are used by multiple structures, it is important that
	they have a common layout so it is easy to copy them.
*/
/*@{*/ 
#define SIP_OUTGOING		(1 << 0)	/*!< D: Direction of the last transaction in this dialog */
#define SIP_RINGING		(1 << 2)	/*!< D: Have sent 180 ringing */
#define SIP_PROGRESS_SENT	(1 << 3)	/*!< D: Have sent 183 message progress */
#define SIP_NEEDREINVITE	(1 << 4)	/*!< D: Do we need to send another reinvite? */
#define SIP_PENDINGBYE		(1 << 5)	/*!< D: Need to send bye after we ack? */
#define SIP_GOTREFER		(1 << 6)	/*!< D: Got a refer? */
#define SIP_CALL_LIMIT		(1 << 7)	/*!< D: Call limit enforced for this call */
#define SIP_INC_COUNT		(1 << 8)	/*!< D: Did this dialog increment the counter of in-use calls? */
#define SIP_INC_RINGING		(1 << 9)	/*!< D: Did this connection increment the counter of in-use calls? */
#define SIP_DEFER_BYE_ON_TRANSFER	(1 << 10)	/*!< D: Do not hangup at first ast_hangup */

#define SIP_PROMISCREDIR	(1 << 11)	/*!< DP: Promiscuous redirection */
#define SIP_TRUSTRPID		(1 << 12)	/*!< DP: Trust RPID headers? */
#define SIP_USEREQPHONE		(1 << 13)	/*!< DP: Add user=phone to numeric URI. Default off */
#define SIP_USECLIENTCODE	(1 << 14)	/*!< DP: Trust X-ClientCode info message */

/* DTMF flags - see str2dtmfmode() and dtmfmode2str() */
#define SIP_DTMF		(7 << 15)	/*!< DP: DTMF Support: five settings, uses three bits */
#define SIP_DTMF_RFC2833	(0 << 15)	/*!< DP: DTMF Support: RTP DTMF - "rfc2833" */
#define SIP_DTMF_INBAND		(1 << 15)	/*!< DP: DTMF Support: Inband audio, only for ULAW/ALAW - "inband" */
#define SIP_DTMF_INFO		(2 << 15)	/*!< DP: DTMF Support: SIP Info messages - "info" */
#define SIP_DTMF_AUTO		(3 << 15)	/*!< DP: DTMF Support: AUTO switch between rfc2833 and in-band DTMF */
#define SIP_DTMF_SHORTINFO      (4 << 15)       /*!< DP: DTMF Support: SIP Info messages - "info" - short variant */

/* NAT settings - see nat2str() */
#define SIP_NAT			(3 << 18)	/*!< DP: four settings, uses two bits */
#define SIP_NAT_NEVER		(0 << 18)	/*!< DP: No nat support */
#define SIP_NAT_RFC3581		(1 << 18)	/*!< DP: NAT RFC3581 */
#define SIP_NAT_ROUTE		(2 << 18)	/*!< DP: NAT Only ROUTE */
#define SIP_NAT_ALWAYS		(3 << 18)	/*!< DP: NAT Both ROUTE and RFC3581 */

/* re-INVITE related settings */
#define SIP_REINVITE		(7 << 20)	/*!< DP: four settings, uses three bits */
#define SIP_REINVITE_NONE	(0 << 20)	/*!< DP: no reinvite allowed */
#define SIP_CAN_REINVITE	(1 << 20)	/*!< DP: allow peers to be reinvited to send media directly p2p */
#define SIP_CAN_REINVITE_NAT	(2 << 20)	/*!< DP: allow media reinvite when new peer is behind NAT */
#define SIP_REINVITE_UPDATE	(4 << 20)	/*!< DP: use UPDATE (RFC3311) when reinviting this peer */

/* "insecure" settings - see insecure2str() */
#define SIP_INSECURE		(3 << 23)	/*!< DP: three settings, uses two bits */
#define SIP_INSECURE_NONE	(0 << 23)	/*!< DP: secure mode */
#define SIP_INSECURE_PORT	(1 << 23)	/*!< DP: don't require matching port for incoming requests */
#define SIP_INSECURE_INVITE	(1 << 24)	/*!< DP: don't require authentication for incoming INVITEs */

/* Sending PROGRESS in-band settings */
#define SIP_PROG_INBAND		(3 << 25)	/*!< DP: three settings, uses two bits */
#define SIP_PROG_INBAND_NEVER	(0 << 25)
#define SIP_PROG_INBAND_NO	(1 << 25)
#define SIP_PROG_INBAND_YES	(2 << 25)

#define SIP_SENDRPID		(1 << 29)	/*!< DP: Remote Party-ID Support */
#define SIP_G726_NONSTANDARD	(1 << 31)	/*!< DP: Use non-standard packing for G726-32 data */

/*! \brief Flags to copy from peer/user to dialog */
#define SIP_FLAGS_TO_COPY \
	(SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
	 SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \
	 SIP_USEREQPHONE | SIP_INSECURE)
/*@}*/ 

/*! \name SIPflags2
	a second page of flags (for flags[1] */
/*@{*/ 
/* realtime flags */
#define SIP_PAGE2_RTCACHEFRIENDS	(1 << 0)	/*!< GP: Should we keep RT objects in memory for extended time? */
#define SIP_PAGE2_RTAUTOCLEAR		(1 << 2)	/*!< GP: Should we clean memory from peers after expiry? */
#define SIP_PAGE2_HAVEPEERCONTEXT	(1 << 3)	/*< Are we associated with a configured peer context? */
/* Space for addition of other realtime flags in the future */
#define SIP_PAGE2_STATECHANGEQUEUE	(1 << 9)	/*!< D: Unsent state pending change exists */

#define SIP_PAGE2_RPORT_PRESENT         (1 << 10)       /*!< Was rport received in the Via header? */
#define SIP_PAGE2_VIDEOSUPPORT		(1 << 14)	/*!< DP: Video supported if offered? */
#define SIP_PAGE2_TEXTSUPPORT		(1 << 15)	/*!< GDP: Global text enable */
#define SIP_PAGE2_ALLOWSUBSCRIBE	(1 << 16)	/*!< GP: Allow subscriptions from this peer? */
#define SIP_PAGE2_ALLOWOVERLAP		(1 << 17)	/*!< DP: Allow overlap dialing ? */
#define SIP_PAGE2_SUBSCRIBEMWIONLY	(1 << 18)	/*!< GP: Only issue MWI notification if subscribed to */
#define SIP_PAGE2_IGNORESDPVERSION	(1 << 19)	/*!< GDP: Ignore the SDP session version number we receive and treat all sessions as new */

#define SIP_PAGE2_T38SUPPORT		        (3 << 20)	/*!< GDP: T.38 Fax Support */
#define SIP_PAGE2_T38SUPPORT_UDPTL	        (1 << 20)	/*!< GDP: T.38 Fax Support (no error correction) */
#define SIP_PAGE2_T38SUPPORT_UDPTL_FEC	        (2 << 20)	/*!< GDP: T.38 Fax Support (FEC error correction) */
#define SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY	(3 << 20)	/*!< GDP: T.38 Fax Support (redundancy error correction) */

#define SIP_PAGE2_CALL_ONHOLD		(3 << 23)	/*!< D: Call hold states: */
#define SIP_PAGE2_CALL_ONHOLD_ACTIVE    (1 << 23)       /*!< D: Active hold */
#define SIP_PAGE2_CALL_ONHOLD_ONEDIR	(2 << 23)	/*!< D: One directional hold */
#define SIP_PAGE2_CALL_ONHOLD_INACTIVE	(3 << 23)	/*!< D: Inactive hold */

#define SIP_PAGE2_RFC2833_COMPENSATE    (1 << 25)	/*!< DP: Compensate for buggy RFC2833 implementations */
#define SIP_PAGE2_BUGGY_MWI		(1 << 26)	/*!< DP: Buggy CISCO MWI fix */
#define SIP_PAGE2_DIALOG_ESTABLISHED    (1 << 27)       /*!< 29: Has a dialog been established? */
#define SIP_PAGE2_FAX_DETECT		(1 << 28)		/*!< DP: Fax Detection support */
#define SIP_PAGE2_REGISTERTRYING        (1 << 29)       /*!< DP: Send 100 Trying on REGISTER attempts */
#define SIP_PAGE2_UDPTL_DESTINATION     (1 << 30)       /*!< DP: Use source IP of RTP as destination if NAT is enabled */

#define SIP_PAGE2_FLAGS_TO_COPY \
	(SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_IGNORESDPVERSION | \
	SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE | \
	 SIP_PAGE2_BUGGY_MWI | SIP_PAGE2_TEXTSUPPORT | SIP_PAGE2_UDPTL_DESTINATION | \
	 SIP_PAGE2_FAX_DETECT | SIP_PAGE2_HAVEPEERCONTEXT)

/*@}*/ 

/*! \brief debugging state
 * We store separately the debugging requests from the config file
 * and requests from the CLI. Debugging is enabled if either is set
 * (which means that if sipdebug is set in the config file, we can
 * only turn it off by reloading the config).
 */
enum sip_debug_e {
	sip_debug_none = 0,
	sip_debug_config = 1,
	sip_debug_console = 2,
};

static enum sip_debug_e sipdebug;

/*! \brief extra debugging for 'text' related events.
 * At thie moment this is set together with sip_debug_console.
 * It should either go away or be implemented properly.
 */
static int sipdebug_text;

/*! \brief T38 States for a call */
enum t38state {
	T38_DISABLED = 0,                /*!< Not enabled */
	T38_LOCAL_REINVITE,              /*!< Offered from local - REINVITE */
	T38_PEER_REINVITE,               /*!< Offered from peer - REINVITE */
	T38_ENABLED                      /*!< Negotiated (enabled) */
};

/*! \brief T.38 channel settings (at some point we need to make this alloc'ed */
struct t38properties {
	enum t38state state;		/*!< T.38 state */
	struct ast_control_t38_parameters our_parms;
	struct ast_control_t38_parameters their_parms;
};

/*! \brief Parameters to know status of transfer */
enum referstatus {
	REFER_IDLE,                    /*!< No REFER is in progress */
	REFER_SENT,                    /*!< Sent REFER to transferee */
	REFER_RECEIVED,                /*!< Received REFER from transferrer */
	REFER_CONFIRMED,               /*!< Refer confirmed with a 100 TRYING (unused) */
	REFER_ACCEPTED,                /*!< Accepted by transferee */
	REFER_RINGING,                 /*!< Target Ringing */
	REFER_200OK,                   /*!< Answered by transfer target */
	REFER_FAILED,                  /*!< REFER declined - go on */
	REFER_NOAUTH                   /*!< We had no auth for REFER */
};

/*! \brief generic struct to map between strings and integers.
 * Fill it with x-s pairs, terminate with an entry with s = NULL;
 * Then you can call map_x_s(...) to map an integer to a string,
 * and map_s_x() for the string -> integer mapping.
 */
struct _map_x_s {
	int x;
	const char *s;
};              

static const struct _map_x_s referstatusstrings[] = {
	{ REFER_IDLE,		"<none>" },
	{ REFER_SENT,		"Request sent" },
	{ REFER_RECEIVED,	"Request received" },
	{ REFER_CONFIRMED,	"Confirmed" },
	{ REFER_ACCEPTED,	"Accepted" },
	{ REFER_RINGING,	"Target ringing" },
	{ REFER_200OK,		"Done" },
	{ REFER_FAILED,		"Failed" },
	{ REFER_NOAUTH,		"Failed - auth failure" },
	{ -1,			NULL} /* terminator */
};

/*! \brief Structure to handle SIP transfers. Dynamically allocated when needed
	\note OEJ: Should be moved to string fields */
struct sip_refer {
	char refer_to[AST_MAX_EXTENSION];		/*!< Place to store REFER-TO extension */
	char refer_to_domain[AST_MAX_EXTENSION];	/*!< Place to store REFER-TO domain */
	char refer_to_urioption[AST_MAX_EXTENSION];	/*!< Place to store REFER-TO uri options */
	char refer_to_context[AST_MAX_EXTENSION];	/*!< Place to store REFER-TO context */
	char referred_by[AST_MAX_EXTENSION];		/*!< Place to store REFERRED-BY extension */
	char referred_by_name[AST_MAX_EXTENSION];	/*!< Place to store REFERRED-BY extension */
	char refer_contact[AST_MAX_EXTENSION];		/*!< Place to store Contact info from a REFER extension */
	char replaces_callid[SIPBUFSIZE];			/*!< Replace info: callid */
	char replaces_callid_totag[SIPBUFSIZE/2];		/*!< Replace info: to-tag */
	char replaces_callid_fromtag[SIPBUFSIZE/2];		/*!< Replace info: from-tag */
	struct sip_pvt *refer_call;			/*!< Call we are referring. This is just a reference to a
							 * dialog owned by someone else, so we should not destroy
							 * it when the sip_refer object goes.
							 */
	int attendedtransfer;				/*!< Attended or blind transfer? */
	int localtransfer;				/*!< Transfer to local domain? */
	enum referstatus status;			/*!< REFER status */
};


/*! \brief Structure that encapsulates all attributes related to running 
 *   SIP Session-Timers feature on a per dialog basis.
 */
struct sip_st_dlg {
	int st_active;                          /*!< Session-Timers on/off */ 
	int st_interval;                        /*!< Session-Timers negotiated session refresh interval */
	int st_schedid;                         /*!< Session-Timers ast_sched scheduler id */
	enum st_refresher st_ref;               /*!< Session-Timers session refresher */
	int st_expirys;                         /*!< Session-Timers number of expirys */
	int st_active_peer_ua;                  /*!< Session-Timers on/off in peer UA */
	int st_cached_min_se;                   /*!< Session-Timers cached Min-SE */
	int st_cached_max_se;                   /*!< Session-Timers cached Session-Expires */
	enum st_mode st_cached_mode;            /*!< Session-Timers cached M.O. */
	enum st_refresher st_cached_ref;        /*!< Session-Timers cached refresher */
	unsigned char quit_flag:1;              /*!< Stop trying to lock; just quit */
};


/*! \brief Structure that encapsulates all attributes related to configuration 
 *   of SIP Session-Timers feature on a per user/peer basis.
 */
struct sip_st_cfg {
	enum st_mode st_mode_oper;      /*!< Mode of operation for Session-Timers           */
	enum st_refresher st_ref;       /*!< Session-Timer refresher                        */
	int st_min_se;                  /*!< Lowest threshold for session refresh interval  */
	int st_max_se;                  /*!< Highest threshold for session refresh interval */
};

struct offered_media {
	int offered;
	char text[128];
};

/*! \brief sip_pvt: structures used for each SIP dialog, ie. a call, a registration, a subscribe.
 * Created and initialized by sip_alloc(), the descriptor goes into the list of
 * descriptors (dialoglist).
 */
struct sip_pvt {
	struct sip_pvt *next;			/*!< Next dialog in chain */
	ast_mutex_t pvt_lock;			/*!< Dialog private lock */
	enum invitestates invitestate;		/*!< Track state of SIP_INVITEs */
	int method;				/*!< SIP method that opened this dialog */
	AST_DECLARE_STRING_FIELDS(
		AST_STRING_FIELD(callid);	/*!< Global CallID */
		AST_STRING_FIELD(randdata);	/*!< Random data */
		AST_STRING_FIELD(accountcode);	/*!< Account code */
		AST_STRING_FIELD(realm);	/*!< Authorization realm */
		AST_STRING_FIELD(nonce);	/*!< Authorization nonce */
		AST_STRING_FIELD(opaque);	/*!< Opaque nonsense */
		AST_STRING_FIELD(qop);		/*!< Quality of Protection, since SIP wasn't complicated enough yet. */
		AST_STRING_FIELD(domain);	/*!< Authorization domain */
		AST_STRING_FIELD(from);		/*!< The From: header */
		AST_STRING_FIELD(useragent);	/*!< User agent in SIP request */
		AST_STRING_FIELD(exten);	/*!< Extension where to start */
		AST_STRING_FIELD(context);	/*!< Context for this call */
		AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */
		AST_STRING_FIELD(subscribeuri); /*!< Subscribecontext */
		AST_STRING_FIELD(fromdomain);	/*!< Domain to show in the from field */
		AST_STRING_FIELD(fromuser);	/*!< User to show in the user field */
		AST_STRING_FIELD(fromname);	/*!< Name to show in the user field */
		AST_STRING_FIELD(tohost);	/*!< Host we should put in the "to" field */
		AST_STRING_FIELD(todnid);	/*!< DNID of this call (overrides host) */
		AST_STRING_FIELD(language);	/*!< Default language for this call */
		AST_STRING_FIELD(mohinterpret);	/*!< MOH class to use when put on hold */
		AST_STRING_FIELD(mohsuggest);	/*!< MOH class to suggest when putting a peer on hold */
		AST_STRING_FIELD(rdnis);	/*!< Referring DNIS */
		AST_STRING_FIELD(redircause);	/*!< Referring cause */
		AST_STRING_FIELD(theirtag);	/*!< Their tag */
		AST_STRING_FIELD(username);	/*!< [user] name */
		AST_STRING_FIELD(peername);	/*!< [peer] name, not set if [user] */
		AST_STRING_FIELD(authname);	/*!< Who we use for authentication */
		AST_STRING_FIELD(uri);		/*!< Original requested URI */
		AST_STRING_FIELD(okcontacturi);	/*!< URI from the 200 OK on INVITE */
		AST_STRING_FIELD(peersecret);	/*!< Password */
		AST_STRING_FIELD(peermd5secret);
		AST_STRING_FIELD(cid_num);	/*!< Caller*ID number */
		AST_STRING_FIELD(cid_name);	/*!< Caller*ID name */
		AST_STRING_FIELD(fullcontact);	/*!< The Contact: that the UA registers with us */
			/* we only store the part in <brackets> in this field. */
		AST_STRING_FIELD(our_contact);	/*!< Our contact header */
		AST_STRING_FIELD(rpid);		/*!< Our RPID header */
		AST_STRING_FIELD(rpid_from);	/*!< Our RPID From header */
		AST_STRING_FIELD(url);		/*!< URL to be sent with next message to peer */
	);
	char via[128];                          /*!< Via: header */
	struct sip_socket socket;		/*!< The socket used for this dialog */
	unsigned int ocseq;			/*!< Current outgoing seqno */
	unsigned int icseq;			/*!< Current incoming seqno */
	ast_group_t callgroup;			/*!< Call group */
	ast_group_t pickupgroup;		/*!< Pickup group */
	int lastinvite;				/*!< Last Cseq of invite */
	struct ast_flags flags[2];		/*!< SIP_ flags */

	/* boolean or small integers that don't belong in flags */
	char do_history;			/*!< Set if we want to record history */
	char alreadygone;			/*!< already destroyed by our peer */
	char needdestroy;			/*!< need to be destroyed by the monitor thread */
	char outgoing_call;			/*!< this is an outgoing call */
	char answered_elsewhere;		/*!< This call is cancelled due to answer on another channel */
	char novideo;				/*!< Didn't get video in invite, don't offer */
	char notext;				/*!< Text not supported  (?) */

	int timer_t1;				/*!< SIP timer T1, ms rtt */
	int timer_b;                            /*!< SIP timer B, ms */
	unsigned int sipoptions;		/*!< Supported SIP options on the other end */
	unsigned int reqsipoptions;		/*!< Required SIP options on the other end */
	struct ast_codec_pref prefs;		/*!< codec prefs */
	int capability;				/*!< Special capability (codec) */
	int jointcapability;			/*!< Supported capability at both ends (codecs) */
	int peercapability;			/*!< Supported peer capability */
	int prefcodec;				/*!< Preferred codec (outbound only) */
	int noncodeccapability;			/*!< DTMF RFC2833 telephony-event */
	int jointnoncodeccapability;            /*!< Joint Non codec capability */
	int redircodecs;			/*!< Redirect codecs */
	int maxcallbitrate;			/*!< Maximum Call Bitrate for Video Calls */
	int t38_maxdatagram;			/*!< T.38 FaxMaxDatagram override */
	struct sip_proxy *outboundproxy;	/*!< Outbound proxy for this dialog */
	struct t38properties t38;		/*!< T38 settings */
	struct sockaddr_in udptlredirip;	/*!< Where our T.38 UDPTL should be going if not to us */
	struct ast_udptl *udptl;		/*!< T.38 UDPTL session */
	int callingpres;			/*!< Calling presentation */
	int authtries;				/*!< Times we've tried to authenticate */
	int expiry;				/*!< How long we take to expire */
	long branch;				/*!< The branch identifier of this session */
	long invite_branch;			/*!< The branch used when we sent the initial INVITE */
	char tag[11];				/*!< Our tag for this session */
	int sessionid;				/*!< SDP Session ID */
	int sessionversion;			/*!< SDP Session Version */
	unsigned int portinuri:1;		/*!< Non zero if a port has been specified, will also disable srv lookups */
	int64_t sessionversion_remote;		/*!< Remote UA's SDP Session Version */
	int session_modify;			/*!< Session modification request true/false  */
	struct sockaddr_in sa;			/*!< Our peer */
	struct sockaddr_in redirip;		/*!< Where our RTP should be going if not to us */
	struct sockaddr_in vredirip;		/*!< Where our Video RTP should be going if not to us */
	struct sockaddr_in tredirip;		/*!< Where our Text RTP should be going if not to us */
	time_t lastrtprx;			/*!< Last RTP received */
	time_t lastrtptx;			/*!< Last RTP sent */
	int rtptimeout;				/*!< RTP timeout time */
	struct sockaddr_in recv;		/*!< Received as */
	struct sockaddr_in ourip;		/*!< Our IP (as seen from the outside) */
	struct ast_channel *owner;		/*!< Who owns us (if we have an owner) */
	struct sip_route *route;		/*!< Head of linked list of routing steps (fm Record-Route) */
	int route_persistant;			/*!< Is this the "real" route? */
	struct sip_auth *peerauth;		/*!< Realm authentication */
	int noncecount;				/*!< Nonce-count */
	unsigned int stalenonce:1;	/*!< Marks the current nonce as responded too */
	char lastmsg[256];			/*!< Last Message sent/received */
	int amaflags;				/*!< AMA Flags */
	int pendinginvite;			/*!< Any pending INVITE or state NOTIFY (in subscribe pvt's) ? (seqno of this) */
	int glareinvite;			/*!< A invite received while a pending invite is already present is stored here.  Its seqno is the
						value. Since this glare invite's seqno is not the same as the pending invite's, it must be 
						held in order to properly process acknowledgements for our 491 response. */

	struct sip_request initreq;		/*!< Latest request that opened a new transaction
							within this dialog.
							NOT the request that opened the dialog */

	int initid;				/*!< Auto-congest ID if appropriate (scheduler) */
	int waitid;				/*!< Wait ID for scheduler after 491 or other delays */
	int autokillid;				/*!< Auto-kill ID (scheduler) */
	int t38id;                              /*!< T.38 Response ID */
	enum transfermodes allowtransfer;	/*!< REFER: restriction scheme */
	struct sip_refer *refer;		/*!< REFER: SIP transfer data structure */
	enum subscriptiontype subscribed;	/*!< SUBSCRIBE: Is this dialog a subscription?  */
	int stateid;				/*!< SUBSCRIBE: ID for devicestate subscriptions */
	int laststate;				/*!< SUBSCRIBE: Last known extension state */
	int dialogver;				/*!< SUBSCRIBE: Version for subscription dialog-info */

	struct ast_dsp *dsp;			/*!< A DSP for inband DTMF and fax CNG tone detection */

	struct sip_peer *relatedpeer;		/*!< If this dialog is related to a peer, which one 
							Used in peerpoke, mwi subscriptions */
	struct sip_registry *registry;		/*!< If this is a REGISTER dialog, to which registry */
	struct ast_rtp *rtp;			/*!< RTP Session */
	struct ast_rtp *vrtp;			/*!< Video RTP session */
	struct ast_rtp *trtp;			/*!< Text RTP session */
	struct sip_pkt *packets;		/*!< Packets scheduled for re-transmission */
	struct sip_history_head *history;	/*!< History of this SIP dialog */
	size_t history_entries;			/*!< Number of entires in the history */
	struct ast_variable *chanvars;		/*!< Channel variables to set for inbound call */
	AST_LIST_HEAD_NOLOCK(request_queue, sip_request) request_queue; /*!< Requests that arrived but could not be processed immediately */
	int request_queue_sched_id;		/*!< Scheduler ID of any scheduled action to process queued requests */
	int provisional_keepalive_sched_id; /*!< Scheduler ID for provisional responses that need to be sent out to avoid cancellation */
	const char *last_provisional;   /*!< The last successfully transmitted provisonal response message */
	struct sip_invite_param *options;	/*!< Options for INVITE */
	int autoframing;			/*!< The number of Asters we group in a Pyroflax
							before strolling to the Grokyzpå
							(A bit unsure of this, please correct if
							you know more) */
	struct sip_st_dlg *stimer;		/*!< SIP Session-Timers */              
	int hangupcause;			/*!< Storage of hangupcause copied from our owner before we disconnect from the AST channel (only used at hangup) */
	/*! When receiving an SDP offer, it is important to take note of what media types were offered.
	 * By doing this, even if we don't want to answer a particular media stream with something meaningful, we can
	 * still put an m= line in our answer with the port set to 0.
	 *
	 * The reason for the length being 4 is that in this branch of Asterisk, the only media types supported are 
	 * image, audio, text, and video. Therefore we need to keep track of which types of media were offered.
	 *
	 * Note that if we wanted to be 100% correct, we would keep a list of all media streams offered. That way we could respond
	 * even to unknown media types, and we could respond to multiple streams of the same type. Such large-scale changes
	 * are not a good idea for released branches, though, so we're compromising by just making sure that for the common cases:
	 * audio and video, audio and T.38, and audio and text, we give the appropriate response to both media streams.
	 *
	 * The large-scale changes would be a good idea for implementing during an SDP rewrite.
	 */
	struct offered_media offered_media[4];
}; 


/*! Max entires in the history list for a sip_pvt */
#define MAX_HISTORY_ENTRIES 50

/*! \brief
 * Here we implement the container for dialogs (sip_pvt), defining
 * generic wrapper functions to ease the transition from the current
 * implementation (a single linked list) to a different container.
 * In addition to a reference to the container, we need functions to lock/unlock
 * the container and individual items, and functions to add/remove
 * references to the individual items.
 */
static struct sip_pvt *dialoglist = NULL;

/*! \brief Protect the SIP dialog list (of sip_pvt's) */
AST_MUTEX_DEFINE_STATIC(dialoglock);

#ifndef DETECT_DEADLOCKS
/*! \brief hide the way the list is locked/unlocked */
static void dialoglist_lock(void)
{
	ast_mutex_lock(&dialoglock);
}

static void dialoglist_unlock(void)
{
	ast_mutex_unlock(&dialoglock);
}
#else
/* we don't want to HIDE the information about where the lock was requested if trying to debug 
 * deadlocks!  So, just make these macros! */
#define dialoglist_lock(x) ast_mutex_lock(&dialoglock)
#define dialoglist_unlock(x) ast_mutex_unlock(&dialoglock)
#endif

#define sip_pvt_lock(x) ao2_lock(x)
#define sip_pvt_trylock(x) ao2_trylock(x)
#define sip_pvt_unlock(x) ao2_unlock(x)

static struct sip_pvt *dialog_ref(struct sip_pvt *p)
{
	if (p)
		ao2_ref(p, 1);
	else
		ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
	return p;
}

static struct sip_pvt *dialog_unref(struct sip_pvt *p)
{
	if (p)
		ao2_ref(p, -1);
	return NULL;
}

/*! \brief sip packet - raw format for outbound packets that are sent or scheduled for transmission
 * Packets are linked in a list, whose head is in the struct sip_pvt they belong to.
 * Each packet holds a reference to the parent struct sip_pvt.
 * This structure is allocated in __sip_reliable_xmit() and only for packets that
 * require retransmissions.
 */
struct sip_pkt {
	struct sip_pkt *next;			/*!< Next packet in linked list */
	int retrans;				/*!< Retransmission number */
	int method;				/*!< SIP method for this packet */
	int seqno;				/*!< Sequence number */
	char is_resp;				/*!< 1 if this is a response packet (e.g. 200 OK), 0 if it is a request */
	char is_fatal;				/*!< non-zero if there is a fatal error */
	int response_code;		/*!< If this is a response, the response code */
	struct sip_pvt *owner;			/*!< Owner AST call */
	int retransid;				/*!< Retransmission ID */
	int timer_a;				/*!< SIP timer A, retransmission timer */
	int timer_t1;				/*!< SIP Timer T1, estimated RTT or 500 ms */
	int packetlen;				/*!< Length of packet */
	char data[0];
};	

/*! \brief Structure for SIP user data. User's place calls to us */
struct sip_user {
	/* Users who can access various contexts */
	ASTOBJ_COMPONENTS(struct sip_user);
	char secret[80];		/*!< Password */
	char md5secret[80];		/*!< Password in md5 */
	char context[AST_MAX_CONTEXT];	/*!< Default context for incoming calls */
	char subscribecontext[AST_MAX_CONTEXT];	/* Default context for subscriptions */
	char cid_num[80];		/*!< Caller ID num */
	char cid_name[80];		/*!< Caller ID name */
	char accountcode[AST_MAX_ACCOUNT_CODE];	/* Account code */
	char language[MAX_LANGUAGE];	/*!< Default language for this user */
	char mohinterpret[MAX_MUSICCLASS];/*!< Music on Hold class */
	char mohsuggest[MAX_MUSICCLASS];/*!< Music on Hold class */
	char useragent[256];		/*!< User agent in SIP request */
	struct ast_codec_pref prefs;	/*!< codec prefs */
	ast_group_t callgroup;		/*!< Call group */
	ast_group_t pickupgroup;	/*!< Pickup Group */
	unsigned int sipoptions;	/*!< Supported SIP options */
	struct ast_flags flags[2];	/*!< SIP_ flags */

	/* things that don't belong in flags */
	char is_realtime;		/*!< this is a 'realtime' user */

	int amaflags;			/*!< AMA flags for billing */
	int callingpres;		/*!< Calling id presentation */
	int capability;			/*!< Codec capability */
	int inUse;			/*!< Number of calls in use */
	int call_limit;			/*!< Limit of concurrent calls */
	int t38_maxdatagram;		/*!< T.38 FaxMaxDatagram override */
	enum transfermodes allowtransfer;	/*! SIP Refer restriction scheme */
	struct ast_ha *ha;		/*!< ACL setting */
	struct ast_variable *chanvars;	/*!< Variables to set for channel created by user */
	int maxcallbitrate;		/*!< Maximum Bitrate for a video call */
	int autoframing;
	struct sip_st_cfg stimer;	/*!< SIP Session-Timers */
};

/*!
 * \brief A peer's mailbox
 *
 * We could use STRINGFIELDS here, but for only two strings, it seems like
 * too much effort ...
 */
struct sip_mailbox {
	char *mailbox;
	char *context;
	/*! Associated MWI subscription */
	struct ast_event_sub *event_sub;
	AST_LIST_ENTRY(sip_mailbox) entry;
};

/*! \brief Structure for SIP peer data, we place calls to peers if registered  or fixed IP address (host) */
/* XXX field 'name' must be first otherwise sip_addrcmp() will fail */
struct sip_peer {
	ASTOBJ_COMPONENTS(struct sip_peer);	/*!< name, refcount, objflags,  object pointers */
					/*!< peer->name is the unique name of this object */
	struct sip_socket socket;	/*!< Socket used for this peer */
	enum sip_transport default_outbound_transport;    /*!< Peer Registration may change the default outbound transport. */
	unsigned int transports:3; /*!< Transports (enum sip_transport) that are acceptable for this peer */
	char secret[80];		/*!< Password */
	char md5secret[80];		/*!< Password in MD5 */
	struct sip_auth *auth;		/*!< Realm authentication list */
	char context[AST_MAX_CONTEXT];	/*!< Default context for incoming calls */
	char subscribecontext[AST_MAX_CONTEXT];	/*!< Default context for subscriptions */
	char username[80];		/*!< Temporary username until registration */ 
	char accountcode[AST_MAX_ACCOUNT_CODE];	/*!< Account code */
	int amaflags;			/*!< AMA Flags (for billing) */
	char tohost[MAXHOSTNAMELEN];	/*!< If not dynamic, IP address */
	char regexten[AST_MAX_EXTENSION]; /*!< Extension to register (if regcontext is used) */
	char fromuser[80];		/*!< From: user when calling this peer */
	char fromdomain[MAXHOSTNAMELEN];	/*!< From: domain when calling this peer */
	char fullcontact[256];		/*!< Contact registered with us (not in sip.conf) */
	char cid_num[80];		/*!< Caller ID num */
	char cid_name[80];		/*!< Caller ID name */
	int callingpres;		/*!< Calling id presentation */
	int inUse;			/*!< Number of calls in use */
	int inRinging;			/*!< Number of calls ringing */
	int onHold;                     /*!< Peer has someone on hold */
	int call_limit;			/*!< Limit of concurrent calls */
	int busy_level;			/*!< Level of active channels where we signal busy */
	int t38_maxdatagram;		/*!< T.38 FaxMaxDatagram override */
	enum transfermodes allowtransfer;	/*! SIP Refer restriction scheme */
	char vmexten[AST_MAX_EXTENSION]; /*!< Dialplan extension for MWI notify message*/
	char language[MAX_LANGUAGE];	/*!<  Default language for prompts */
	char mohinterpret[MAX_MUSICCLASS];/*!<  Music on Hold class */
	char mohsuggest[MAX_MUSICCLASS];/*!<  Music on Hold class */
	char useragent[256];		/*!<  User agent in SIP request (saved from registration) */
	struct ast_codec_pref prefs;	/*!<  codec prefs */
	int lastmsgssent;
	unsigned int sipoptions;	/*!<  Supported SIP options */
	struct ast_flags flags[2];	/*!<  SIP_ flags */

	/*! Mailboxes that this peer cares about */
	AST_LIST_HEAD_NOLOCK(, sip_mailbox) mailboxes;

	/* things that don't belong in flags */
	char is_realtime;		/*!< this is a 'realtime' peer */
	char rt_fromcontact;		/*!< P: copy fromcontact from realtime */
	char host_dynamic;		/*!< P: Dynamic Peers register with Asterisk */
	char selfdestruct;		/*!< P: Automatic peers need to destruct themselves */

	int expire;			/*!<  When to expire this peer registration */
	int capability;			/*!<  Codec capability */
	int rtptimeout;			/*!<  RTP timeout */
	int rtpholdtimeout;		/*!<  RTP Hold Timeout */
	int rtpkeepalive;		/*!<  Send RTP packets for keepalive */
	ast_group_t callgroup;		/*!<  Call group */
	ast_group_t pickupgroup;	/*!<  Pickup group */
	struct sip_proxy *outboundproxy;	/*!< Outbound proxy for this peer */
	struct ast_dnsmgr_entry *dnsmgr;/*!<  DNS refresh manager for peer */
	struct sockaddr_in addr;	/*!<  IP address of peer */
	int maxcallbitrate;		/*!< Maximum Bitrate for a video call */
	unsigned int portinuri:1;	/*!< Whether the port should be included in the URI */

	/* Qualification */
	struct sip_pvt *call;		/*!<  Call pointer */
	int pokeexpire;			/*!<  When to expire poke (qualify= checking) */
	int lastms;			/*!<  How long last response took (in ms), or -1 for no response */
	int maxms;			/*!<  Max ms we will accept for the host to be up, 0 to not monitor */
	int qualifyfreq;		/*!<  Qualification: How often to check for the host to be up */
	struct timeval ps;		/*!<  Time for sending SIP OPTION in sip_pke_peer() */
	struct sockaddr_in defaddr;	/*!<  Default IP address, used until registration */
	struct ast_ha *ha;		/*!<  Access control list */
	struct ast_ha *contactha;       /*!<  Restrict what IPs are allowed in the Contact header (for registration) */
	struct ast_variable *chanvars;	/*!<  Variables to set for channel created by user */
	struct sip_pvt *mwipvt;		/*!<  Subscription for MWI */
	int autoframing;
	struct sip_st_cfg stimer;	/*!<  SIP Session-Timers */
	int timer_t1;			/*!<  The maximum T1 value for the peer */
	int timer_b;			/*!<  The maximum timer B (transaction timeouts) */
	int deprecated_username; /*!< If it's a realtime peer, are they using the deprecated "username" instead of "defaultuser" */
};


/*! \brief Registrations with other SIP proxies
 * Created by sip_register(), the entry is linked in the 'regl' list,
 * and never deleted (other than at 'sip reload' or module unload times).
 * The entry always has a pending timeout, either waiting for an ACK to
 * the REGISTER message (in which case we have to retransmit the request),
 * or waiting for the next REGISTER message to be sent (either the initial one,
 * or once the previously completed registration one expires).
 * The registration can be in one of many states, though at the moment
 * the handling is a bit mixed.
 * Note that the entire evolution of sip_registry (transmissions,
 * incoming packets and timeouts) is driven by one single thread,
 * do_monitor(), so there is almost no synchronization issue.
 * The only exception  is the sip_pvt creation/lookup,
 * as the dialoglist is also manipulated by other threads.
 */
struct sip_registry {
	ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
	AST_DECLARE_STRING_FIELDS(
		AST_STRING_FIELD(callid);	/*!< Global Call-ID */
		AST_STRING_FIELD(realm);	/*!< Authorization realm */
		AST_STRING_FIELD(nonce);	/*!< Authorization nonce */
		AST_STRING_FIELD(opaque);	/*!< Opaque nonsense */
		AST_STRING_FIELD(qop);		/*!< Quality of Protection, since SIP wasn't complicated enough yet. */
		AST_STRING_FIELD(domain);	/*!< Authorization domain */
		AST_STRING_FIELD(username);	/*!< Who we are registering as */
		AST_STRING_FIELD(authuser);	/*!< Who we *authenticate* as */
		AST_STRING_FIELD(hostname);	/*!< Domain or host we register to */
		AST_STRING_FIELD(secret);	/*!< Password in clear text */	
		AST_STRING_FIELD(md5secret);	/*!< Password in md5 */
		AST_STRING_FIELD(callback);	/*!< Contact extension */
		AST_STRING_FIELD(random);
		AST_STRING_FIELD(peername);	/*!< Peer registering to */
	);
	enum sip_transport transport;
	int portno;			/*!<  Optional port override */
	int expire;			/*!< Sched ID of expiration */
	int configured_expiry;		/*!< Configured value to use for the Expires header */
	int expiry;			/*!< Negotiated value used for the Expires header */
	int regattempts;		/*!< Number of attempts (since the last success) */
	int timeout; 			/*!< sched id of sip_reg_timeout */
	int refresh;			/*!< How often to refresh */
	struct sip_pvt *call;		/*!< create a sip_pvt structure for each outbound "registration dialog" in progress */
	enum sipregistrystate regstate;	/*!< Registration state (see above) */
	struct timeval regtime;		/*!< Last successful registration time */
	int callid_valid;		/*!< 0 means we haven't chosen callid for this registry yet. */
	unsigned int ocseq;		/*!< Sequence number we got to for REGISTERs for this registry */
	struct sockaddr_in us;		/*!< Who the server thinks we are */
	int noncecount;			/*!< Nonce-count */
	char lastmsg[256];		/*!< Last Message sent/received */
};

struct sip_threadinfo {
	int stop;
	pthread_t threadid;
	struct ast_tcptls_session_instance *tcptls_session;
	enum sip_transport type;	/* We keep a copy of the type here so we can display it in the connection list */
	AST_LIST_ENTRY(sip_threadinfo) list;
};

/* --- Linked lists of various objects --------*/

/*! \brief  The thread list of TCP threads */
static AST_LIST_HEAD_STATIC(threadl, sip_threadinfo);

/*! \brief  The user list: Users and friends */
static struct ast_user_list {
	ASTOBJ_CONTAINER_COMPONENTS(struct sip_user);
} userl;

/*! \brief  The peer list: Peers and Friends */
static struct ast_peer_list {
	ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer);
} peerl;

/*! \brief  The register list: Other SIP proxies we register with and place calls to */
static struct ast_register_list {
	ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
	int recheck;
} regl;

static int temp_pvt_init(void *);
static void temp_pvt_cleanup(void *);

/*! \brief A per-thread temporary pvt structure */
AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);

#ifdef LOW_MEMORY
static void ts_ast_rtp_destroy(void *);

AST_THREADSTORAGE_CUSTOM(ts_audio_rtp, NULL, ts_ast_rtp_destroy);
AST_THREADSTORAGE_CUSTOM(ts_video_rtp, NULL, ts_ast_rtp_destroy);
AST_THREADSTORAGE_CUSTOM(ts_text_rtp, NULL, ts_ast_rtp_destroy);
#endif

/*! \brief Authentication list for realm authentication 
 * \todo Move the sip_auth list to AST_LIST */
static struct sip_auth *authl = NULL;


/* --- Sockets and networking --------------*/

/*! \brief Main socket for SIP communication.
 *
 * sipsock is shared between the SIP manager thread (which handles reload
 * requests), the io handler (sipsock_read()) and the user routines that
 * issue writes (using __sip_xmit()).
 * The socket is -1 only when opening fails (this is a permanent condition),
 * or when we are handling a reload() that changes its address (this is
 * a transient situation during which we might have a harmless race, see
 * below). Because the conditions for the race to be possible are extremely
 * rare, we don't want to pay the cost of locking on every I/O.
 * Rather, we remember that when the race may occur, communication is
 * bound to fail anyways, so we just live with this event and let
 * the protocol handle this above us.
 */
static int sipsock  = -1;

static struct sockaddr_in bindaddr;	/*!< The address we bind to */

/*! \brief our (internal) default address/port to put in SIP/SDP messages
 *  internip is initialized picking a suitable address from one of the
 * interfaces, and the same port number we bind to. It is used as the
 * default address/port in SIP messages, and as the default address
 * (but not port) in SDP messages.
 */
static struct sockaddr_in internip;

/*! \brief our external IP address/port for SIP sessions.
 * externip.sin_addr is only set when we know we might be behind
 * a NAT, and this is done using a variety of (mutually exclusive)
 * ways from the config file:
 *
 * + with "externip = host[:port]" we specify the address/port explicitly.
 *   The address is looked up only once when (re)loading the config file;
 * 
 * + with "externhost = host[:port]" we do a similar thing, but the
 *   hostname is stored in externhost, and the hostname->IP mapping
 *   is refreshed every 'externrefresh' seconds;
 * 
 * + with "stunaddr = host[:port]" we run queries every externrefresh seconds
 *   to the specified server, and store the result in externip.
 *
 * Other variables (externhost, externexpire, externrefresh) are used
 * to support the above functions.
 */
static struct sockaddr_in externip;		/*!< External IP address if we are behind NAT */

static char externhost[MAXHOSTNAMELEN];		/*!< External host name */
static time_t externexpire;			/*!< Expiration counter for re-resolving external host name in dynamic DNS */
static int externrefresh = 10;
static struct sockaddr_in stunaddr;		/*!< stun server address */

/*! \brief  List of local networks
 * We store "localnet" addresses from the config file into an access list,
 * marked as 'DENY', so the call to ast_apply_ha() will return
 * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
 * (i.e. presumably public) addresses.
 */
static struct ast_ha *localaddr;		/*!< List of local networks, on the same side of NAT as this Asterisk */

static int ourport_tcp;				/*!< The port used for TCP connections */
static int ourport_tls;				/*!< The port used for TCP/TLS connections */
static struct sockaddr_in debugaddr;

static struct ast_config *notify_types = NULL;		/*!< The list of manual NOTIFY types we know how to send */

/*! some list management macros. */
 
#define UNLINK(element, head, prev) do {	\
	if (prev)				\
		(prev)->next = (element)->next;	\
	else					\
		(head) = (element)->next;	\
	} while (0)

enum t38_action_flag {
	SDP_T38_NONE = 0, /*!< Do not modify T38 information at all */
	SDP_T38_INITIATE, /*!< Remote side has requested T38 with us */
	SDP_T38_ACCEPT,   /*!< Remote side accepted our T38 request */
};

/*---------------------------- Forward declarations of functions in chan_sip.c */
/* Note: This is added to help splitting up chan_sip.c into several files
	in coming releases. */

/*--- PBX interface functions */
static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
static int sip_devicestate(void *data);
static int sip_sendtext(struct ast_channel *ast, const char *text);
static int sip_call(struct ast_channel *ast, char *dest, int timeout);
static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
static int sip_hangup(struct ast_channel *ast);
static int sip_answer(struct ast_channel *ast);
static struct ast_frame *sip_read(struct ast_channel *ast);
static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
static int sip_transfer(struct ast_channel *ast, const char *dest);
static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
static int sip_senddigit_begin(struct ast_channel *ast, char digit);
static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
static const char *sip_get_callid(struct ast_channel *chan);

static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin);
static int sip_standard_port(enum sip_transport type, int port);
static int sip_prepare_socket(struct sip_pvt *p);
static int sip_parse_host(char *line, int lineno, char **hostname, int *portnum, enum sip_transport *transport);

/*--- Transmitting responses and requests */
static int sipsock_read(int *id, int fd, short events, void *ignore);
static int __sip_xmit(struct sip_pvt *p, char *data, int len);
static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod);
static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
static int retrans_pkt(const void *data);
static int transmit_sip_request(struct sip_pvt *p, struct sip_request *req);
static int transmit_response_using_temp(ast_string_field callid, struct sockaddr_in *sin, int useglobal_nat, const int intended_method, const struct sip_request *req, const char *msg);
static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp);
static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
static int transmit_response_with_auth(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *rand, enum xmittype reliable, const char *header, int stale);
static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable);
static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
static int transmit_info_with_vidupdate(struct sip_pvt *p);
static int transmit_message_with_text(struct sip_pvt *p, const char *text);
static int transmit_refer(struct sip_pvt *p, const char *dest);
static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten);
static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
static void copy_request(struct sip_request *dst, const struct sip_request *src);
static void receive_message(struct sip_pvt *p, struct sip_request *req);
static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req);
static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only);

/*--- Dialog management */
static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
				 int useglobal_nat, const int intended_method, struct sip_request *req);
static int __sip_autodestruct(const void *data);
static void sip_scheddestroy(struct sip_pvt *p, int ms);
static int sip_cancel_destroy(struct sip_pvt *p);
static struct sip_pvt *sip_destroy(struct sip_pvt *p);
static int __sip_destroy(struct sip_pvt *p, int lockowner);
static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
static void __sip_pretend_ack(struct sip_pvt *p);
static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
static int auto_congest(const void *arg);
static int update_call_counter(struct sip_pvt *fup, int event);
static int hangup_sip2cause(int cause);
static const char *hangup_cause2sip(int cause);
static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
static void free_old_route(struct sip_route *route);
static void list_route(struct sip_route *route);
static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
					      struct sip_request *req, char *uri);
static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
static void check_pendings(struct sip_pvt *p);
static void *sip_park_thread(void *stuff);
static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
static int sip_sipredirect(struct sip_pvt *p, const char *dest);

/*--- Codec handling / SDP */
static void try_suggested_sip_codec(struct sip_pvt *p);
static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
static int find_sdp(struct sip_request *req);
static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
static int process_sdp_o(const char *o, struct sip_pvt *p);
static int process_sdp_c(const char *c, struct ast_hostent *hp);
static int process_sdp_a_sendonly(const char *a, int *sendonly);
static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp *newaudiortp, int *last_rtpmap_codec);
static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp *newvideortp, int *last_rtpmap_codec);
static int process_sdp_a_text(const char *a, struct sip_pvt *p, struct ast_rtp *newtextrtp, int *last_rtpmap_codec);
static int process_sdp_a_image(const char *a, struct sip_pvt *p);
static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
			     struct ast_str **m_buf, struct ast_str **a_buf,
			     int debug, int *min_packet_size);
static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
				struct ast_str **m_buf, struct ast_str **a_buf,
				int debug);
static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
static void do_setnat(struct sip_pvt *p, int natflags);
static void stop_media_flows(struct sip_pvt *p);

/*--- Authentication stuff */
static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
					 const char *secret, const char *md5secret, int sipmethod,
					 char *uri, enum xmittype reliable, int ignore);
static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
					      int sipmethod, char *uri, enum xmittype reliable,
					      struct sockaddr_in *sin, struct sip_peer **authpeer);
static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin);

/*--- Domain handling */
static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
static void clear_sip_domains(void);

/*--- SIP realm authentication */
static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno);
static int clear_realm_authentication(struct sip_auth *authlist);	/* Clear realm authentication list (at reload) */
static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);

/*--- Misc functions */
static int sip_do_reload(enum channelreloadreason reason);
static int reload_config(enum channelreloadreason reason);
static int expire_register(const void *data);
static void *do_monitor(void *data);
static int restart_monitor(void);
static int sip_addrcmp(char *name, struct sip_peer *p2);     /* Support for peer matching */
static int sip_refer_allocate(struct sip_pvt *p);
static void ast_quiet_chan(struct ast_channel *chan);
static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
/*!
 * \brief generic function for determining if a correct transport is being 
 * used to contact a peer
 *
 * this is done as a macro so that the "tmpl" var can be passed either a 
 * sip_request or a sip_peer 
 */
#define check_request_transport(peer, tmpl) ({ \
	int ret = 0; \
	if (peer->socket.type == tmpl->socket.type) \
		; \
	else if (!(peer->transports & tmpl->socket.type)) {\
		ast_log(LOG_ERROR, \
			"'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
			get_transport(tmpl->socket.type), peer->name, get_transport_list(peer) \
			); \
		ret = 1; \
	} else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
		ast_log(LOG_WARNING, \
			"peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
			peer->name, get_transport(tmpl->socket.type) \
		); \
	} else { \
		ast_debug(1, \
			"peer '%s' has contacted us over %s even though we prefer %s.\n", \
			peer->name, get_transport(tmpl->socket.type), get_transport(peer->socket.type) \
		); \
	}\
	(ret); \
})


/*--- Device monitoring and Device/extension state/event handling */
static int cb_extensionstate(char *context, char* exten, int state, void *data);
static int sip_devicestate(void *data);
static int sip_poke_noanswer(const void *data);
static int sip_poke_peer(struct sip_peer *peer);
static void sip_poke_all_peers(void);
static void sip_peer_hold(struct sip_pvt *p, int hold);
static void mwi_event_cb(const struct ast_event *, void *);

/*--- Applications, functions, CLI and manager command helpers */
static const char *sip_nat_mode(const struct sip_pvt *p);
static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
static char *transfermode2str(enum transfermodes mode) attribute_const;
static const char *nat2str(int nat) attribute_const;
static int peer_status(struct sip_peer *peer, char *status, int statuslen);
static char *sip_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
static void  print_group(int fd, ast_group_t group, int crlf);
static const char *dtmfmode2str(int mode) attribute_const;
static int str2dtmfmode(const char *str) attribute_unused;
static const char *insecure2str(int mode) attribute_const;
static void cleanup_stale_contexts(char *new, char *old);
static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
static const char *domain_mode_to_text(const enum domain_mode mode);
static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
static char *sip_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
static char *complete_sip_peer(const char *word, int state, int flags2);
static char *complete_sip_registered_peer(const char *word, int state, int flags2);
static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
static char *complete_sip_user(const char *word, int state, int flags2);
static char *complete_sip_show_user(const char *line, const char *word, int pos, int state);
static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
static char *sip_do_debug_ip(int fd, char *arg);
static char *sip_do_debug_peer(int fd, char *arg);
static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
static char *sip_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
static char *sip_do_history_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
static int sip_dtmfmode(struct ast_channel *chan, void *data);
static int sip_addheader(struct ast_channel *chan, void *data);
static int sip_do_reload(enum channelreloadreason reason);
static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);

/*--- Debugging 
	Functions for enabling debug per IP or fully, or enabling history logging for
	a SIP dialog
*/
static void sip_dump_history(struct sip_pvt *dialog);	/* Dump history to debuglog at end of dialog, before destroying data */
static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
static inline int sip_debug_test_pvt(struct sip_pvt *p);


/*! \brief Append to SIP dialog history 
	\return Always returns 0 */
#define append_history(p, event, fmt , args... )	append_history_full(p, "%-15s " fmt, event, ## args)
static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
static void sip_dump_history(struct sip_pvt *dialog);

/*--- Device object handling */
static struct sip_peer *temp_peer(const char *name);
static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
static struct sip_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime);
static int update_call_counter(struct sip_pvt *fup, int event);
static void sip_destroy_peer(struct sip_peer *peer);
static void sip_destroy_user(struct sip_user *user);
static int sip_poke_peer(struct sip_peer *peer);
static void set_peer_defaults(struct sip_peer *peer);
static struct sip_peer *temp_peer(const char *name);
static void register_peer_exten(struct sip_peer *peer, int onoff);
static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int devstate_only, int transport);
static struct sip_user *find_user(const char *name, int realtime);
static int sip_poke_peer_s(const void *data);
static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
static void reg_source_db(struct sip_peer *peer);
static void destroy_association(struct sip_peer *peer);
static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
static void set_socket_transport(struct sip_socket *socket, int transport);

/* Realtime device support */
static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey, int deprecated_username, int lastms);
static struct sip_user *realtime_user(const char *username);
static void update_peer(struct sip_peer *p, int expiry);
static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername);
static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin, int devstate_only);
static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);

/*--- Internal UA client handling (outbound registrations) */
static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p);
static void sip_registry_destroy(struct sip_registry *reg);
static int sip_register(const char *value, int lineno);
static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
static int sip_reregister(const void *data);
static int __sip_do_register(struct sip_registry *r);
static int sip_reg_timeout(const void *data);
static void sip_send_all_registers(void);

/*--- Parsing SIP requests and responses */
static void append_date(struct sip_request *req);	/* Append date to SIP packet */
static int determine_firstline_parts(struct sip_request *req);
static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
static int find_sip_method(const char *msg);
static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
static int parse_request(struct sip_request *req);
static const char *get_header(const struct sip_request *req, const char *name);
static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
static int method_match(enum sipmethod id, const char *name);
static void parse_copy(struct sip_request *dst, const struct sip_request *src);
static char *get_in_brackets(char *tmp);
static const char *find_alias(const char *name, const char *_default);
static const char *__get_header(const struct sip_request *req, const char *name, int *start);
static int lws2sws(char *msgbuf, int len);
static void extract_uri(struct sip_pvt *p, struct sip_request *req);
static char *remove_uri_parameters(char *uri);
static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
static int set_address_from_contact(struct sip_pvt *pvt);
static void check_via(struct sip_pvt *p, struct sip_request *req);
static char *get_calleridname(const char *input, char *output, size_t outputsize);
static int get_rpid_num(const char *input, char *output, int maxlen);
static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq);
static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
static int get_msg_text(char *buf, int len, struct sip_request *req);
static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);

/*-- TCP connection handling ---*/
static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session);
static void *sip_tcp_worker_fn(void *);

/*--- Constructing requests and responses */
static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
static int init_req(struct sip_request *req, int sipmethod, const char *recip);
static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
static int init_resp(struct sip_request *resp, const char *msg);
static inline int resp_needs_contact(const char *msg, enum sipmethod method);
static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
static void build_via(struct sip_pvt *p);
static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
static int create_addr(struct sip_pvt *dialog, const char *opeer, int newdialog);
static char *generate_random_string(char *buf, size_t size);
static void build_callid_pvt(struct sip_pvt *pvt);
static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
static void make_our_tag(char *tagbuf, size_t len);
static int add_header(struct sip_request *req, const char *var, const char *value);
static int add_header_contentLength(struct sip_request *req, int len);
static int add_line(struct sip_request *req, const char *line);
static int add_text(struct sip_request *req, const char *text);
static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
static int add_vidupdate(struct sip_request *req);
static void add_route(struct sip_request *req, struct sip_route *route);
static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
static void set_destination(struct sip_pvt *p, char *uri);
static void append_date(struct sip_request *req);
static void build_contact(struct sip_pvt *p);
static void build_rpid(struct sip_pvt *p);

/*------Request handling functions */
static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *recount, char *e, int *nounlock);
static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *nounlock);
static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno);

/*------Response handling functions */
static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);

/*----- RTP interface functions */
static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp,  struct ast_rtp *trtp, int codecs, int nat_active);
static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
static int sip_get_codec(struct ast_channel *chan);
static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect);

/*------ T38 Support --------- */
static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
static void change_t38_state(struct sip_pvt *p, int state);

/*------ Session-Timers functions --------- */
static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
static int  proc_session_timer(const void *vp);
static void stop_session_timer(struct sip_pvt *p);
static void start_session_timer(struct sip_pvt *p);
static void restart_session_timer(struct sip_pvt *p);
static const char *strefresher2str(enum st_refresher r);
static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref);
static int parse_minse(const char *p_hdrval, int *const p_interval);
static int st_get_se(struct sip_pvt *, int max);
static enum st_refresher st_get_refresher(struct sip_pvt *);
static enum st_mode st_get_mode(struct sip_pvt *);
static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);


/*! \brief Definition of this channel for PBX channel registration */
static const struct ast_channel_tech sip_tech = {
	.type = "SIP",
	.description = "Session Initiation Protocol (SIP)",
	.capabilities = AST_FORMAT_AUDIO_MASK,	/* all audio formats */
	.properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
	.requester = sip_request_call,			/* called with chan unlocked */
	.devicestate = sip_devicestate,			/* called with chan unlocked (not chan-specific) */
	.call = sip_call,			/* called with chan locked */
	.send_html = sip_sendhtml,
	.hangup = sip_hangup,			/* called with chan locked */
	.answer = sip_answer,			/* called with chan locked */
	.read = sip_read,			/* called with chan locked */
	.write = sip_write,			/* called with chan locked */
	.write_video = sip_write,		/* called with chan locked */
	.write_text = sip_write,
	.indicate = sip_indicate,		/* called with chan locked */
	.transfer = sip_transfer,		/* called with chan locked */
	.fixup = sip_fixup,			/* called with chan locked */
	.send_digit_begin = sip_senddigit_begin,	/* called with chan unlocked */
	.send_digit_end = sip_senddigit_end,
	.bridge = ast_rtp_bridge,			/* XXX chan unlocked ? */
	.early_bridge = ast_rtp_early_bridge,
	.send_text = sip_sendtext,		/* called with chan locked */
	.func_channel_read = acf_channel_read,
	.queryoption = sip_queryoption,
	.get_pvt_uniqueid = sip_get_callid,
};

/*! \brief This version of the sip channel tech has no send_digit_begin
 * callback so that the core knows that the channel does not want
 * DTMF BEGIN frames.
 * The struct is initialized just before registering the channel driver,
 * and is for use with channels using SIP INFO DTMF.
 */
static struct ast_channel_tech sip_tech_info;


/*! \brief Working TLS connection configuration */
static struct ast_tls_config sip_tls_cfg;

/*! \brief Default TLS connection configuration */
static struct ast_tls_config default_tls_cfg;

/*! \brief The TCP server definition */
static struct server_args sip_tcp_desc = {
	.accept_fd = -1,
	.master = AST_PTHREADT_NULL,
	.tls_cfg = NULL,
	.poll_timeout = -1,
	.name = "sip tcp server",
	.accept_fn = ast_tcptls_server_root,
	.worker_fn = sip_tcp_worker_fn,
};

/*! \brief The TCP/TLS server definition */
static struct server_args sip_tls_desc = {
	.accept_fd = -1,
	.master = AST_PTHREADT_NULL,
	.tls_cfg = &sip_tls_cfg,
	.poll_timeout = -1,
	.name = "sip tls server",
	.accept_fn = ast_tcptls_server_root,
	.worker_fn = sip_tcp_worker_fn,
};

/* wrapper macro to tell whether t points to one of the sip_tech descriptors */
#define IS_SIP_TECH(t)  ((t) == &sip_tech || (t) == &sip_tech_info)

/*! \brief map from an integer value to a string.
 * If no match is found, return errorstring
 */
static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
{
	const struct _map_x_s *cur;

	for (cur = table; cur->s; cur++)
		if (cur->x == x)
			return cur->s;
	return errorstring;
}

/*! \brief map from a string to an integer value, case insensitive.
 * If no match is found, return errorvalue.
 */
static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
{
	const struct _map_x_s *cur;

	for (cur = table; cur->s; cur++)
		if (!strcasecmp(cur->s, s))
			return cur->x;
	return errorvalue;
}


/*! \brief Interface structure with callbacks used to connect to RTP module */
static struct ast_rtp_protocol sip_rtp = {
	.type = "SIP",
	.get_rtp_info = sip_get_rtp_peer,
	.get_vrtp_info = sip_get_vrtp_peer,
	.get_trtp_info = sip_get_trtp_peer,
	.set_rtp_peer = sip_set_rtp_peer,
	.get_codec = sip_get_codec,
};


/*! \brief SIP TCP connection handler */
static void *sip_tcp_worker_fn(void *data)
{
	struct ast_tcptls_session_instance *tcptls_session = data;

	return _sip_tcp_helper_thread(NULL, tcptls_session);
}

/*! \brief SIP TCP thread management function */
static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session) 
{
	int res, cl;
	struct sip_request req = { 0, } , reqcpy = { 0, };
	struct sip_threadinfo *me;
	char buf[1024] = "";

	me = ast_calloc(1, sizeof(*me));

	if (!me)
		goto cleanup2;

	me->threadid = pthread_self();
	me->tcptls_session = tcptls_session;
	if (tcptls_session->ssl)
		me->type = SIP_TRANSPORT_TLS;
	else
		me->type = SIP_TRANSPORT_TCP;

	ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");

	AST_LIST_LOCK(&threadl);
	AST_LIST_INSERT_TAIL(&threadl, me, list);
	AST_LIST_UNLOCK(&threadl);


	for (;;) {
		memset(req.data, 0, sizeof(req.data));
		req.len = 0;
		req.ignore = 0;
		req.debug = 0;

		memset(buf, 0, sizeof(buf));

		if (tcptls_session->ssl) {
			set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
			req.socket.port = htons(ourport_tls);
		} else {
			set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
			req.socket.port = htons(ourport_tcp);
		}
		req.socket.fd = tcptls_session->fd;
		res = ast_wait_for_input(tcptls_session->fd, -1);
		if (res < 0) {
			ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
			goto cleanup;
		}

		/* Read in headers one line at a time */
		while (req.len < 4 || strncmp((char *)&req.data + req.len - 4, "\r\n\r\n", 4)) {
			ast_mutex_lock(&tcptls_session->lock);
			if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
				ast_mutex_unlock(&tcptls_session->lock);
				goto cleanup;
			}
			ast_mutex_unlock(&tcptls_session->lock);
			if (me->stop) 
				 goto cleanup;
			strncat(req.data, buf, sizeof(req.data) - req.len - 1);
			req.len = strlen(req.data);
		}
		parse_copy(&reqcpy, &req);
		if (sscanf(get_header(&reqcpy, "Content-Length"), "%30d", &cl)) {
			while (cl > 0) {
				size_t bytes_read;
				ast_mutex_lock(&tcptls_session->lock);
				if (!(bytes_read = fread(buf, 1, MIN(sizeof(buf) - 1, cl), tcptls_session->f))) {
					ast_mutex_unlock(&tcptls_session->lock);
					goto cleanup;
				}
				buf[bytes_read] = '\0';
				ast_mutex_unlock(&tcptls_session->lock);
				if (me->stop)
					goto cleanup;
				cl -= strlen(buf);
				strncat(req.data, buf, sizeof(req.data) - req.len - 1);
				req.len = strlen(req.data);
			}
		}
		req.socket.tcptls_session = tcptls_session;
		handle_request_do(&req, &tcptls_session->requestor);
	}

cleanup:
	AST_LIST_LOCK(&threadl);
	AST_LIST_REMOVE(&threadl, me, list);
	AST_LIST_UNLOCK(&threadl);
	ast_free(me);
cleanup2:
	fclose(tcptls_session->f);
	tcptls_session->f = NULL;
	tcptls_session->fd = -1;

	ast_debug(2, "Shutting down thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
	
	ao2_ref(tcptls_session, -1);
	tcptls_session = NULL;

	return NULL;
}


/*!
 * helper functions to unreference various types of objects.
 * By handling them this way, we don't have to declare the
 * destructor on each call, which removes the chance of errors.
 */
static void unref_peer(struct sip_peer *peer)
{
	ASTOBJ_UNREF(peer, sip_destroy_peer);
}

static void unref_user(struct sip_user *user)
{
	ASTOBJ_UNREF(user, sip_destroy_user);
}

static void *registry_unref(struct sip_registry *reg)
{
	ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
	ASTOBJ_UNREF(reg, sip_registry_destroy);
	return NULL;
}

/*! \brief Add object reference to SIP registry */
static struct sip_registry *registry_addref(struct sip_registry *reg)
{
	ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
	return ASTOBJ_REF(reg);	/* Add pointer to registry in packet */
}


static int dialog_check_destroy(struct sip_pvt *p)
{
/* We absolutely cannot destroy the rtp struct while a bridge is active or we WILL crash */
	if (p->rtp && ast_rtp_get_bridged(p->rtp)) {
		ast_debug(2, "Bridge still active.  Delaying destroy of SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
		return -1;
	}

	if (p->vrtp && ast_rtp_get_bridged(p->vrtp)) {
		ast_debug(2, "Bridge still active.  Delaying destroy of SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
		return -1;
	}
	return 0;
}


/*!
 * \brief Destroys a dialog by safely removing all existing references.
 */
static int dialog_cleanup_and_destroy(struct sip_pvt *p)
{
	struct sip_pvt *cur, *prev = NULL;
	/* if dialog_check_destroy() fails, a bridge is still active,
	 * after that bridge is closed, cleanup_and_destroy is called
	 * again. */
	if (dialog_check_destroy(p)) {
		return -1;
	}

	/* Lock dialog list before removing ourselves from the list */
	dialoglist_lock();
	for (prev = NULL, cur = dialoglist; cur; prev = cur, cur = cur->next) {
		if (cur == p) {
			UNLINK(cur, dialoglist, prev);
			break;
		}
	}
	dialoglist_unlock();
	if (!cur) {
		ast_log(LOG_WARNING, "Trying to destroy \"%s\", not found in dialog list?!?! \n", p->callid);
		return 0;
	}

	/* All scheduled items holding a dialog ref must be deleted
	 * and unrefed here before destruction can take place. */

	/* Destroy Session-Timers if allocated */
	if (p->stimer) {
		p->stimer->quit_flag = 1;
		if (p->stimer->st_active == TRUE && p->stimer->st_schedid > -1) {
			AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid, if (_count < 10) dialog_unref(p));
		}
	}
	/* this is the last dialog ref */
	dialog_unref(p);
	return 0;
}


/*! \brief Interface structure with callbacks used to connect to UDPTL module*/
static struct ast_udptl_protocol sip_udptl = {
	type: "SIP",
	get_udptl_info: sip_get_udptl_peer,
	set_udptl_peer: sip_set_udptl_peer,
};

static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
	__attribute__((format(printf, 2, 3)));


/*! \brief Convert transfer status to string */
static const char *referstatus2str(enum referstatus rstatus)
{
	return map_x_s(referstatusstrings, rstatus, "");
}

/*! \brief Initialize the initital request packet in the pvt structure.
 	This packet is used for creating replies and future requests in
	a dialog */
static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
{
	if (p->initreq.headers)
		ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
	else
		ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
	/* Use this as the basis */
	copy_request(&p->initreq, req);
	parse_request(&p->initreq);
	if (req->debug)
		ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
}

/*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
static void sip_alreadygone(struct sip_pvt *dialog)
{
	ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
	dialog->alreadygone = 1;
}

/*! Resolve DNS srv name or host name in a sip_proxy structure */
static int proxy_update(struct sip_proxy *proxy)
{
	/* if it's actually an IP address and not a name,
           there's no need for a managed lookup */
	if (!inet_aton(proxy->name, &proxy->ip.sin_addr)) {
		/* Ok, not an IP address, then let's check if it's a domain or host */
		/* XXX Todo - if we have proxy port, don't do SRV */
		if (ast_get_ip_or_srv(&proxy->ip, proxy->name, global_srvlookup ? "_sip._udp" : NULL) < 0) {
			ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
			return FALSE;
		}
	}
	proxy->last_dnsupdate = time(NULL);
	return TRUE;
}

/*! \brief converts ascii port to int representation. If no
 *  pt buffer is provided or the pt has errors when being converted
 *  to an int value, the port provided as the standard is used.
 */
static int port_str2int(const char *pt, unsigned int standard)
{
	int port = standard;
	if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
		port = standard;
	}

	return port;
}

/*! \brief Allocate and initialize sip proxy */
static struct sip_proxy *proxy_allocate(char *name, char *port, int force)
{
	struct sip_proxy *proxy;

	if (ast_strlen_zero(name)) {
		return NULL;
	}

	proxy = ast_calloc(1, sizeof(*proxy));
	if (!proxy)
		return NULL;
	proxy->force = force;
	ast_copy_string(proxy->name, name, sizeof(proxy->name));
	proxy->ip.sin_port = htons(port_str2int(port, STANDARD_SIP_PORT));
	proxy_update(proxy);
	return proxy;
}

/*! \brief Get default outbound proxy or global proxy */
static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
{
	if (peer && peer->outboundproxy) {
		if (sipdebug)
			ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
		append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
		return peer->outboundproxy;
	}
	if (global_outboundproxy.name[0]) {
		if (sipdebug)
			ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
		append_history(dialog, "OBproxy", "Using global obproxy %s", global_outboundproxy.name);
		return &global_outboundproxy;
	}
	if (sipdebug)
		ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
	return NULL;
}

/*! \brief returns true if 'name' (with optional trailing whitespace)
 * matches the sip method 'id'.
 * Strictly speaking, SIP methods are case SENSITIVE, but we do
 * a case-insensitive comparison to be more tolerant.
 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
 */
static int method_match(enum sipmethod id, const char *name)
{
	int len = strlen(sip_methods[id].text);
	int l_name = name ? strlen(name) : 0;
	/* true if the string is long enough, and ends with whitespace, and matches */
	return (l_name >= len && name[len] < 33 &&
		!strncasecmp(sip_methods[id].text, name, len));
}

/*! \brief  find_sip_method: Find SIP method from header */
static int find_sip_method(const char *msg)
{
	int i, res = 0;
	
	if (ast_strlen_zero(msg))
		return 0;
	for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
		if (method_match(i, msg))
			res = sip_methods[i].id;
	}
	return res;
}

/*! \brief Parse supported header in incoming packet */
static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
{
	char *next, *sep;
	char *temp;
	unsigned int profile = 0;
	int i, found;

	if (ast_strlen_zero(supported) )
		return 0;
	temp = ast_strdupa(supported);

	if (sipdebug)
		ast_debug(3, "Begin: parsing SIP \"Supported: %s\"\n", supported);

	for (next = temp; next; next = sep) {
		found = FALSE;
		if ( (sep = strchr(next, ',')) != NULL)
			*sep++ = '\0';
		next = ast_skip_blanks(next);
		if (sipdebug)
			ast_debug(3, "Found SIP option: -%s-\n", next);
		for (i = 0; i < ARRAY_LEN(sip_options); i++) {
			if (!strcasecmp(next, sip_options[i].text)) {
				profile |= sip_options[i].id;
				found = TRUE;
				if (sipdebug)
					ast_debug(3, "Matched SIP option: %s\n", next);
				break;
			}
		}

		/* This function is used to parse both Suported: and Require: headers.
		Let the caller of this function know that an unknown option tag was 
		encountered, so that if the UAC requires it then the request can be 
		rejected with a 420 response. */
		if (!found)
			profile |= SIP_OPT_UNKNOWN;

		if (!found && sipdebug) {
			if (!strncasecmp(next, "x-", 2))
				ast_debug(3, "Found private SIP option, not supported: %s\n", next);
			else
				ast_debug(3, "Found no match for SIP option: %s (Please file bug report!)\n", next);
		}
	}

	if (pvt)
		pvt->sipoptions = profile;
	return profile;
}

/*! \brief See if we pass debug IP filter */
static inline int sip_debug_test_addr(const struct sockaddr_in *addr) 
{
	if (!sipdebug)
		return 0;
	if (debugaddr.sin_addr.s_addr) {
		if (((ntohs(debugaddr.sin_port) != 0)
			&& (debugaddr.sin_port != addr->sin_port))
			|| (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
			return 0;
	}
	return 1;
}

/*! \brief The real destination address for a write */
static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
{
	if (p->outboundproxy)
		return &p->outboundproxy->ip;

	return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
}

/*! \brief Display SIP nat mode */
static const char *sip_nat_mode(const struct sip_pvt *p)
{
	return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
}

/*! \brief Test PVT for debugging output */
static inline int sip_debug_test_pvt(struct sip_pvt *p) 
{
	if (!sipdebug)
		return 0;
	return sip_debug_test_addr(sip_real_dst(p));
}
	/*! \brief Return int representing a bit field of transport types found in const char *transport */
	static int get_transport_str2enum(const char *transport)
	{
	int res = 0;

	if (ast_strlen_zero(transport)) {
		return res;
	}

	if (!strcasecmp(transport, "udp")) {
		res |= SIP_TRANSPORT_UDP;
	}
	if (!strcasecmp(transport, "tcp")) {
		res |= SIP_TRANSPORT_TCP;
	}
	if (!strcasecmp(transport, "tls")) {
		res |= SIP_TRANSPORT_TLS;
	}

	return res;
}

static inline const char *get_transport_list(struct sip_peer *peer) {
	switch (peer->transports) {
		case SIP_TRANSPORT_UDP:
			return "UDP";
		case SIP_TRANSPORT_TCP:
			return "TCP";
		case SIP_TRANSPORT_TLS:
			return "TLS";
		case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
			return "TCP,UDP";
		case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
			return "TLS,UDP";
		case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
			return "TLS,TCP";
		default:
			return peer->transports ? 
				"TLS,TCP,UDP" : "UNKNOWN";	
	}
}

static inline const char *get_transport(enum sip_transport t)
{
	switch (t) {
	case SIP_TRANSPORT_UDP:
		return "UDP";
	case SIP_TRANSPORT_TCP:
		return "TCP";
	case SIP_TRANSPORT_TLS:
		return "TLS";
	}

	return "UNKNOWN";
}

static inline const char *get_transport_pvt(struct sip_pvt *p)
{
	if (p->outboundproxy && p->outboundproxy->transport) {
		set_socket_transport(&p->socket, p->outboundproxy->transport);
	}

	return get_transport(p->socket.type);
}

/*! \brief Transmit SIP message 
	Sends a SIP request or response on a given socket (in the pvt)
	Called by retrans_pkt, send_request, send_response and 
	__sip_reliable_xmit
*/
static int __sip_xmit(struct sip_pvt *p, char *data, int len)
{
	int res = 0;
	const struct sockaddr_in *dst = sip_real_dst(p);

	ast_debug(1, "Trying to put '%.11s' onto %s socket destined for %s:%d\n", data, get_transport_pvt(p), ast_inet_ntoa(dst->sin_addr), htons(dst->sin_port));

	if (sip_prepare_socket(p) < 0)
		return XMIT_ERROR;

	if (p->socket.tcptls_session)
		ast_mutex_lock(&p->socket.tcptls_session->lock);

	if (p->socket.type & SIP_TRANSPORT_UDP) {
		res = sendto(p->socket.fd, data, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
	} else if (p->socket.tcptls_session) {
		if (p->socket.tcptls_session->f) {
			res = ast_tcptls_server_write(p->socket.tcptls_session, data, len);
		} else {
			ast_debug(2, "No p->socket.tcptls_session->f len=%d\n", len);
			return XMIT_ERROR;
		}
	} else {
		ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
		return XMIT_ERROR;
	}

	if (p->socket.tcptls_session)
		ast_mutex_unlock(&p->socket.tcptls_session->lock);

	if (res == -1) {
		switch (errno) {
		case EBADF: 		/* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
		case EHOSTUNREACH: 	/* Host can't be reached */
		case ENETDOWN: 		/* Inteface down */
		case ENETUNREACH:	/* Network failure */
		case ECONNREFUSED:      /* ICMP port unreachable */ 
			res = XMIT_ERROR;	/* Don't bother with trying to transmit again */
		}
	}
	if (res != len)
		ast_log(LOG_WARNING, "sip_xmit of %p (len %d) to %s:%d returned %d: %s\n", data, len, ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), res, strerror(errno));

	return res;
}

/*! \brief Build a Via header for a request */
static void build_via(struct sip_pvt *p)
{
	/* Work around buggy UNIDEN UIP200 firmware */
	const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";

	/* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
	snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s:%d;branch=z9hG4bK%08x%s",
		 get_transport_pvt(p),
		 ast_inet_ntoa(p->ourip.sin_addr),
		 ntohs(p->ourip.sin_port), (int) p->branch, rport);
}

/*! \brief NAT fix - decide which IP address to use for Asterisk server?
 *
 * Using the localaddr structure built up with localnet statements in sip.conf
 * apply it to their address to see if we need to substitute our
 * externip or can get away with our internal bindaddr
 * 'us' is always overwritten.
 */
static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p)
{
	struct sockaddr_in theirs;
	/* Set want_remap to non-zero if we want to remap 'us' to an externally
	 * reachable IP address and port. This is done if:
	 * 1. we have a localaddr list (containing 'internal' addresses marked
	 *    as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
	 *    and AST_SENSE_ALLOW on 'external' ones);
	 * 2. either stunaddr or externip is set, so we know what to use as the
	 *    externally visible address;
	 * 3. the remote address, 'them', is external;
	 * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
	 *    when passed to ast_apply_ha() so it does need to be remapped.
	 *    This fourth condition is checked later.
	 */
	int want_remap;

	*us = internip;		/* starting guess for the internal address */
	/* now ask the system what would it use to talk to 'them' */
	ast_ouraddrfor(them, &us->sin_addr);
	theirs.sin_addr = *them;

	want_remap = localaddr &&
		(externip.sin_addr.s_addr || stunaddr.sin_addr.s_addr) &&
		ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;

	if (want_remap &&
	    (!global_matchexterniplocally || !ast_apply_ha(localaddr, us)) ) {
		/* if we used externhost or stun, see if it is time to refresh the info */
		if (externexpire && time(NULL) >= externexpire) {
			if (stunaddr.sin_addr.s_addr) {
				ast_stun_request(sipsock, &stunaddr, NULL, &externip);
			} else {
				if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
					ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
			}
			externexpire = time(NULL) + externrefresh;
		}
		if (externip.sin_addr.s_addr)
			*us = externip;
		else
			ast_log(LOG_WARNING, "stun failed\n");
		ast_debug(1, "Target address %s is not local, substituting externip\n", 
			ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
	} else if (p) {
		/* no remapping, but we bind to a specific address, so use it. */
		switch (p->socket.type) {
		case SIP_TRANSPORT_TCP:
			if (sip_tcp_desc.sin.sin_addr.s_addr) {
				*us = sip_tcp_desc.sin;
			} else {
				us->sin_port = sip_tcp_desc.sin.sin_port;
			}
			break;
		case SIP_TRANSPORT_TLS:
			if (sip_tls_desc.sin.sin_addr.s_addr) {
				*us = sip_tls_desc.sin;
			} else {
				us->sin_port = sip_tls_desc.sin.sin_port;
			}
				break;
		case SIP_TRANSPORT_UDP:
			/* fall through on purpose */
		default:
			if (bindaddr.sin_addr.s_addr) {
				*us = bindaddr;
			}
		}
	} else if (bindaddr.sin_addr.s_addr) {
		*us = bindaddr;
	}
	ast_debug(3, "Setting SIP_TRANSPORT_%s with address %s:%d\n", get_transport(p->socket.type), ast_inet_ntoa(us->sin_addr), ntohs(us->sin_port));
}

/*! \brief Append to SIP dialog history with arg list  */
static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
{
	char buf[80], *c = buf; /* max history length */
	struct sip_history *hist;
	int l;

	vsnprintf(buf, sizeof(buf), fmt, ap);
	strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
	l = strlen(buf) + 1;
	if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
		return;
	if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
		ast_free(hist);
		return;
	}
	memcpy(hist->event, buf, l);
	if (p->history_entries == MAX_HISTORY_ENTRIES) {
		struct sip_history *oldest;
		oldest = AST_LIST_REMOVE_HEAD(p->history, list);
		p->history_entries--;
		ast_free(oldest);
	}
	AST_LIST_INSERT_TAIL(p->history, hist, list);
	p->history_entries++;
}

/*! \brief Append to SIP dialog history with arg list  */
static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
{
	va_list ap;

	if (!p)
		return;

	if (!p->do_history && !recordhistory && !dumphistory)
		return;

	va_start(ap, fmt);
	append_history_va(p, fmt, ap);
	va_end(ap);

	return;
}

/*! \brief Retransmit SIP message if no answer (Called from scheduler) */
static int retrans_pkt(const void *data)
{
	struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
	int reschedule = DEFAULT_RETRANS;
	int xmitres = 0;

	/* Lock channel PVT */
	sip_pvt_lock(pkt->owner);

	if (pkt->retrans < MAX_RETRANS) {
		pkt->retrans++;
 		if (!pkt->timer_t1) {	/* Re-schedule using timer_a and timer_t1 */
			if (sipdebug)
 				ast_debug(4, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n", pkt->retransid, sip_methods[pkt->method].text, pkt->method);
		} else {
 			int siptimer_a;

 			if (sipdebug)
 				ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
 			if (!pkt->timer_a)
 				pkt->timer_a = 2 ;
 			else
 				pkt->timer_a = 2 * pkt->timer_a;
 
 			/* For non-invites, a maximum of 4 secs */
 			siptimer_a = pkt->timer_t1 * pkt->timer_a;	/* Double each time */
 			if (pkt->method != SIP_INVITE && siptimer_a > 4000)
 				siptimer_a = 4000;
 		
 			/* Reschedule re-transmit */
			reschedule = siptimer_a;
 			ast_debug(4, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n", pkt->retrans +1, siptimer_a, pkt->timer_t1, pkt->retransid);
 		} 

		if (sip_debug_test_pvt(pkt->owner)) {
			const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
			ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
				pkt->retrans, sip_nat_mode(pkt->owner),
				ast_inet_ntoa(dst->sin_addr),
				ntohs(dst->sin_port), pkt->data);
		}

		append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data);
		xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
		sip_pvt_unlock(pkt->owner);
		if (xmitres == XMIT_ERROR)
			ast_log(LOG_WARNING, "Network error on retransmit in dialog %s\n", pkt->owner->callid);
		else 
			return  reschedule;
	} 
	/* Too many retries */
	if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
		if (pkt->is_fatal || sipdebug)	/* Tell us if it's critical or if we're debugging */
			ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s) -- See doc/sip-retransmit.txt.\n",
				pkt->owner->callid, pkt->seqno,
				pkt->is_fatal ? "Critical" : "Non-critical", pkt->is_resp ? "Response" : "Request");
	} else if (pkt->method == SIP_OPTIONS && sipdebug) {
			ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s)  -- See doc/sip-retransmit.txt.\n", pkt->owner->callid);

	} 
	if (xmitres == XMIT_ERROR) {
		ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
		append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
	} else 
		append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
 		
	pkt->retransid = -1;

	if (pkt->is_fatal) {
		while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
			sip_pvt_unlock(pkt->owner);	/* SIP_PVT, not channel */
			usleep(1);
			sip_pvt_lock(pkt->owner);
		}

		if (pkt->owner->owner && !pkt->owner->owner->hangupcause) 
			pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
		
		if (pkt->owner->owner) {
			sip_alreadygone(pkt->owner);
			ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet (see doc/sip-retransmit.txt).\n", pkt->owner->callid);
			ast_queue_hangup(pkt->owner->owner);
			ast_channel_unlock(pkt->owner->owner);
		} else {
			/* If no channel owner, destroy now */

			/* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
			if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
				pkt->owner->needdestroy = 1;
				sip_alreadygone(pkt->owner);
				append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
			}
		}
	}

	if (pkt->method == SIP_BYE) {
		/* We're not getting answers on SIP BYE's.  Tear down the call anyway. */
		if (pkt->owner->owner) 
			ast_channel_unlock(pkt->owner->owner);
		append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
		pkt->owner->needdestroy = 1;
	}

	/* Remove the packet */
	for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
		if (cur == pkt) {
			UNLINK(cur, pkt->owner->packets, prev);
			sip_pvt_unlock(pkt->owner);
			ast_free(pkt);
			return 0;
		}
	}
	/* error case */
	ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
	sip_pvt_unlock(pkt->owner);
	return 0;
}

/*! \brief Transmit packet with retransmits 
	\return 0 on success, -1 on failure to allocate packet 
*/
static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod)
{
	struct sip_pkt *pkt = NULL;
	int siptimer_a = DEFAULT_RETRANS;
	int xmitres = 0;
	int respid;

	if (sipmethod == SIP_INVITE) {
		/* Note this is a pending invite */
		p->pendinginvite = seqno;
	}

	/* If the transport is something reliable (TCP or TLS) then don't really send this reliably */
	/* I removed the code from retrans_pkt that does the same thing so it doesn't get loaded into the scheduler */
	/* According to the RFC some packets need to be retransmitted even if its TCP, so this needs to get revisited */
	if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
		xmitres = __sip_xmit(p, data, len);	/* Send packet */
		if (xmitres == XMIT_ERROR) {	/* Serious network trouble, no need to try again */
			append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
			return AST_FAILURE;
		} else
			return AST_SUCCESS;
	}

	if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
		return AST_FAILURE;
	/* copy data, add a terminator and save length */
	memcpy(pkt->data, data, len);
	pkt->data[len] = '\0';
	pkt->packetlen = len;
	/* copy other parameters from the caller */
	pkt->method = sipmethod;
	pkt->seqno = seqno;
	pkt->is_resp = resp;
	pkt->is_fatal = fatal;
	pkt->owner = p;
	pkt->next = p->packets;
	p->packets = pkt;	/* Add it to the queue */
	if (resp) {
		/* Parse out the response code */
		if (sscanf(pkt->data, "SIP/2.0 %30u", &respid) == 1) {
			pkt->response_code = respid;
		}
	}
	pkt->timer_t1 = p->timer_t1;	/* Set SIP timer T1 */
	pkt->retransid = -1;
	if (pkt->timer_t1)
		siptimer_a = pkt->timer_t1 * 2;

	/* Schedule retransmission */
	AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
	if (sipdebug)
		ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id  #%d\n", pkt->retransid);

	xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);	/* Send packet */

	if (xmitres == XMIT_ERROR) {	/* Serious network trouble, no need to try again */
		append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
		ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
		AST_SCHED_DEL(sched, pkt->retransid);
		p->packets = pkt->next;
		ast_free(pkt);
		return AST_FAILURE;
	} else {
		return AST_SUCCESS;
	}
}

/*! \brief Kill a SIP dialog (called only by the scheduler) */
static int __sip_autodestruct(const void *data)
{
	struct sip_pvt *p = (struct sip_pvt *)data;

	/* If this is a subscription, tell the phone that we got a timeout */
	if (p->subscribed) {
		transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);	/* Send last notification */
		p->subscribed = NONE;
		append_history(p, "Subscribestatus", "timeout");
		ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
		return 10000;	/* Reschedule this destruction so that we know that it's gone */
	}

	/* If there are packets still waiting for delivery, delay the destruction */
	if (p->packets) {
		if (!p->needdestroy) {
			char method_str[31];
			ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
			append_history(p, "ReliableXmit", "timeout");
			if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
				if (method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
					p->needdestroy = 1;
				}
			}
			return 10000;
		} else {
			/* They've had their chance to respond. Time to bail */
			__sip_pretend_ack(p);
		}
	}

	if (p->subscribed == MWI_NOTIFICATION)
		if (p->relatedpeer)
			unref_peer(p->relatedpeer);	/* Remove link to peer. If it's realtime, make sure it's gone from memory) */

	/* Reset schedule ID */
	p->autokillid = -1;

	if (p->owner) {
		ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
		ast_queue_hangup(p->owner);
	} else if (p->refer && !p->alreadygone) {
		ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
		transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
		append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
	} else {
		append_history(p, "AutoDestroy", "%s", p->callid);
		ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
		dialog_cleanup_and_destroy(p); /* sip_destroy(p);   Go ahead and destroy dialog. All attempts to recover is done */
		/* sip_destroy also absorbs the reference */
	}
	return 0;
}

/*! \brief Schedule destruction of SIP dialog */
static void sip_scheddestroy(struct sip_pvt *p, int ms)
{
	if (ms < 0) {
		if (p->timer_t1 == 0) {
			p->timer_t1 = global_t1;	/* Set timer T1 if not set (RFC 3261) */
			p->timer_b = global_timer_b;  /* Set timer B if not set (RFC 3261) */
		}
		ms = p->timer_t1 * 64;
	}
	if (sip_debug_test_pvt(p))
		ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
	if (sip_cancel_destroy(p))
		ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");

	if (p->do_history)
		append_history(p, "SchedDestroy", "%d ms", ms);
	p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);

	if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0)
		stop_session_timer(p);
}

/*! \brief Cancel destruction of SIP dialog.
 * Be careful as this also absorbs the reference - if you call it
 * from within the scheduler, this might be the last reference.
 */
static int sip_cancel_destroy(struct sip_pvt *p)
{
	int res = 0;
	if (p->autokillid > -1) {
		if (!(res = ast_sched_del(sched, p->autokillid))) {
			append_history(p, "CancelDestroy", "");
			p->autokillid = -1;
		}
	}
	return res;
}

/*! \brief Acknowledges receipt of a packet and stops retransmission 
 * called with p locked*/
static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
{
	struct sip_pkt *cur, *prev = NULL;
	const char *msg = "Not Found";	/* used only for debugging */
	int res = FALSE;

	/* If we have an outbound proxy for this dialog, then delete it now since
	  the rest of the requests in this dialog needs to follow the routing.
	  If obforcing is set, we will keep the outbound proxy during the whole
	  dialog, regardless of what the SIP rfc says
	*/
	if (p->outboundproxy && !p->outboundproxy->force)
		p->outboundproxy = NULL;

	for (cur = p->packets; cur; prev = cur, cur = cur->next) {
		if (cur->seqno != seqno || cur->is_resp != resp)
			continue;
		if (cur->is_resp || cur->method == sipmethod) {
			res = TRUE;
			msg = "Found";
			if (!resp && (seqno == p->pendinginvite)) {
				ast_debug(1, "Acked pending invite %d\n", p->pendinginvite);
				p->pendinginvite = 0;
			}
			if (cur->retransid > -1) {
				if (sipdebug)
					ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
			}
			/* This odd section is designed to thwart a 
			 * race condition in the packet scheduler. There are
			 * two conditions under which deleting the packet from the
			 * scheduler can fail.
			 *
			 * 1. The packet has been removed from the scheduler because retransmission
			 * is being attempted. The problem is that if the packet is currently attempting
			 * retransmission and we are at this point in the code, then that MUST mean
			 * that retrans_pkt is waiting on p's lock. Therefore we will relinquish the
			 * lock temporarily to allow retransmission.
			 *
			 * 2. The packet has reached its maximum number of retransmissions and has
			 * been permanently removed from the packet scheduler. If this is the case, then
			 * the packet's retransid will be set to -1. The atomicity of the setting and checking
			 * of the retransid to -1 is ensured since in both cases p's lock is held.
			 */
			while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
				sip_pvt_unlock(p);
				usleep(1);
				sip_pvt_lock(p);
			}
			UNLINK(cur, p->packets, prev);
			ast_free(cur);
			break;
		}
	}
	ast_debug(1, "Stopping retransmission on '%s' of %s %d: Match %s\n",
		p->callid, resp ? "Response" : "Request", seqno, msg);
	return res;
}

/*! \brief Pretend to ack all packets
 * called with p locked */
static void __sip_pretend_ack(struct sip_pvt *p)
{
	struct sip_pkt *cur = NULL;

	while (p->packets) {
		int method;
		if (cur == p->packets) {
			ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
			return;
		}
		cur = p->packets;
		method = (cur->method) ? cur->method : find_sip_method(cur->data);
		__sip_ack(p, cur->seqno, cur->is_resp, method);
	}
}

/*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
{
	struct sip_pkt *cur;
	int res = FALSE;

	for (cur = p->packets; cur; cur = cur->next) {
		if (cur->seqno == seqno && cur->is_resp == resp &&
			(cur->is_resp || method_match(sipmethod, cur->data))) {
			/* this is our baby */
			if (cur->retransid > -1) {
				if (sipdebug)
					ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
			}
			AST_SCHED_DEL(sched, cur->retransid);
			res = TRUE;
			break;
		}
	}
	ast_debug(1, "(Provisional) Stopping retransmission (but retaining packet) on '%s' %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res == -1 ? "Not Found" : "Found");
	return res;
}


/*! \brief Copy SIP request, parse it */
static void parse_copy(struct sip_request *dst, const struct sip_request *src)
{
	memset(dst, 0, sizeof(*dst));
	memcpy(dst->data, src->data, sizeof(dst->data));
	dst->len = src->len;
	parse_request(dst);
}

/*! \brief add a blank line if no body */
static void add_blank(struct sip_request *req)
{
	if (!req->lines) {
		/* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
		ast_copy_string(req->data + req->len, "\r\n", sizeof(req->data) - req->len);
		req->len += strlen(req->data + req->len);
	}
}

static int send_provisional_keepalive_full(struct sip_pvt *pvt, int with_sdp)
{
	const char *msg = NULL;

	if (!pvt->last_provisional || !strncasecmp(pvt->last_provisional, "100", 3)) {
		msg = "183 Session Progress";
	}

	if (pvt->invitestate < INV_COMPLETED) {
		if (with_sdp) {
			transmit_response_with_sdp(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq, XMIT_UNRELIABLE, FALSE);
		} else {
			transmit_response(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq);
		}
		return PROVIS_KEEPALIVE_TIMEOUT;
	}

	return 0;
}

static int send_provisional_keepalive(const void *data) {
	struct sip_pvt *pvt = (struct sip_pvt *) data;

	return send_provisional_keepalive_full(pvt, 0);
}

static int send_provisional_keepalive_with_sdp(const void *data) {
	struct sip_pvt *pvt = (void *)data;

	return send_provisional_keepalive_full(pvt, 1);
}

static void update_provisional_keepalive(struct sip_pvt *pvt, int with_sdp)
{
	AST_SCHED_DEL_UNREF(sched, pvt->provisional_keepalive_sched_id, dialog_unref(pvt));

	pvt->provisional_keepalive_sched_id = ast_sched_add(sched, PROVIS_KEEPALIVE_TIMEOUT,
		with_sdp ? send_provisional_keepalive_with_sdp : send_provisional_keepalive, pvt);
	if (pvt->provisional_keepalive_sched_id > 0) {
		dialog_ref(pvt);
	}
}

/*! \brief Transmit response on SIP request*/
static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
{
	int res;

	add_blank(req);
	if (sip_debug_test_pvt(p)) {
		const struct sockaddr_in *dst = sip_real_dst(p);

		ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
			reliable ? "Reliably " : "", sip_nat_mode(p),
			ast_inet_ntoa(dst->sin_addr),
			ntohs(dst->sin_port), req->data);
	}
	if (p->do_history) {
		struct sip_request tmp;
		parse_copy(&tmp, req);
		append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"), 
			(tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? tmp.rlPart2 : sip_methods[tmp.method].text);
	}

	/* If we are sending a final response to an INVITE, stop retransmitting provisional responses */
	if (p->initreq.method == SIP_INVITE && reliable == XMIT_CRITICAL) {
		AST_SCHED_DEL_UNREF(sched, p->provisional_keepalive_sched_id, dialog_unref(p));
	}

	res = (reliable) ?
		 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
		__sip_xmit(p, req->data, req->len);
	if (res > 0)
		return 0;
	return res;
}

/*! \brief Send SIP Request to the other part of the dialogue */
static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
{
	int res;

	/* If we have an outbound proxy, reset peer address 
		Only do this once.
	*/
	if (p->outboundproxy) {
		p->sa = p->outboundproxy->ip;
	}

	add_blank(req);
	if (sip_debug_test_pvt(p)) {
		if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
			ast_verbose("%sTransmitting (NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port), req->data);
		else
			ast_verbose("%sTransmitting (no NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port), req->data);
	}
	if (p->do_history) {
		struct sip_request tmp;
		parse_copy(&tmp, req);
		append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
	}
	res = (reliable) ?
		__sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
		__sip_xmit(p, req->data, req->len);
	return res;
}

/*! \brief Query an option on a SIP dialog */
static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
{
	int res = -1;
	enum ast_t38_state state = T38_STATE_UNAVAILABLE;
	struct sip_pvt *p = (struct sip_pvt *) chan->tech_pvt;

	switch (option) {
	case AST_OPTION_T38_STATE:
		/* Make sure we got an ast_t38_state enum passed in */
		if (*datalen != sizeof(enum ast_t38_state)) {
			ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option. Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
			return -1;
		}

		sip_pvt_lock(p);

		/* Now if T38 support is enabled we need to look and see what the current state is to get what we want to report back */
		if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
			switch (p->t38.state) {
			case T38_LOCAL_REINVITE:
			case T38_PEER_REINVITE:
				state = T38_STATE_NEGOTIATING;
				break;
			case T38_ENABLED:
				state = T38_STATE_NEGOTIATED;
				break;
			default:
				state = T38_STATE_UNKNOWN;
			}
		}

		sip_pvt_unlock(p);

		*((enum ast_t38_state *) data) = state;
		res = 0;

		break;
	default:
		break;
	}

	return res;
}

/*! \brief Locate closing quote in a string, skipping escaped quotes.
 * optionally with a limit on the search.
 * start must be past the first quote.
 */
static const char *find_closing_quote(const char *start, const char *lim)
{
	char last_char = '\0';
	const char *s;
	for (s = start; *s && s != lim; last_char = *s++) {
		if (*s == '"' && last_char != '\\')
			break;
	}
	return s;
}

/*! \brief Pick out text in brackets from character string
	\return pointer to terminated stripped string
	\param tmp input string that will be modified
	Examples:
\verbatim
	"foo" <bar>	valid input, returns bar
	foo		returns the whole string
	< "foo ... >	returns the string between brackets
	< "foo...	bogus (missing closing bracket), returns the whole string
			XXX maybe should still skip the opening bracket
\endverbatim
 */
static char *get_in_brackets(char *tmp)
{
	const char *parse = tmp;
	char *first_bracket;

	/*
	 * Skip any quoted text until we find the part in brackets.
	* On any error give up and return the full string.
	*/
	while ( (first_bracket = strchr(parse, '<')) ) {
		char *first_quote = strchr(parse, '"');

		if (!first_quote || first_quote > first_bracket)
			break; /* no need to look at quoted part */
		/* the bracket is within quotes, so ignore it */
		parse = find_closing_quote(first_quote + 1, NULL);
		if (!*parse) { /* not found, return full string ? */
			/* XXX or be robust and return in-bracket part ? */
			ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
			break;
		}
		parse++;
	}
	if (first_bracket) {
		char *second_bracket = strchr(first_bracket + 1, '>');
		if (second_bracket) {
			*second_bracket = '\0';
			tmp = first_bracket + 1;
		} else {
			ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
		}
	}
	
	return tmp;
}

/*! \brief * parses a URI in its components.
 *
 * \note 
 * - If scheme is specified, drop it from the top.
 * - If a component is not requested, do not split around it.
 * - Multiple scheme's can be specified ',' delimited. ex: "sip:,sips:"
 *
 * This means that if we don't have domain, we cannot split
 * name:pass and domain:port.
 * It is safe to call with ret_name, pass, domain, port
 * pointing all to the same place.
 * Init pointers to empty string so we never get NULL dereferencing.
 * Overwrites the string.
 * return 0 on success, other values on error.
 * \verbatim 
 * general form we are expecting is sip[s]:username[:password][;parameter]@host[:port][;...] 
 * \endverbatim
 */
static int parse_uri(char *uri, const char *scheme,
	char **ret_name, char **pass, char **domain, char **port, char **options, char **transport)
{
	char *name = NULL;
	int error = 0;

	/* init field as required */
	if (pass)
		*pass = "";
	if (port)
		*port = "";
	if (scheme) {
		int l;
		char *scheme2 = ast_strdupa(scheme);
		char *cur = strsep(&scheme2, ",");
		for (; !ast_strlen_zero(cur); cur = strsep(&scheme2, ",")) {
			l = strlen(cur);
			if (!strncasecmp(uri, cur, l)) {
				uri += l;
				break;
			}
		}
		if (ast_strlen_zero(cur)) {
			ast_debug(1, "No supported scheme found in '%s' using the scheme[s] %s\n", uri, scheme);
			error = -1;
		}
	}
	if (transport) {
		char *t, *type = "";
		*transport = "";
		if ((t = strstr(uri, "transport="))) {
			strsep(&t, "=");
			if ((type = strsep(&t, ";"))) {
				*transport = type;
			}
		}
	}

	if (!domain) {
		/* if we don't want to split around domain, keep everything as a name,
		 * so we need to do nothing here, except remember why.
		 */
	} else {
		/* store the result in a temp. variable to avoid it being
		 * overwritten if arguments point to the same place.
		 */
		char *c, *dom = "";

		if ((c = strchr(uri, '@')) == NULL) {
			/* domain-only URI, according to the SIP RFC. */
			dom = uri;
			name = "";
		} else {
			*c++ = '\0';
			dom = c;
			name = uri;
		}

		/* Remove options in domain and name */
		dom = strsep(&dom, ";");
		name = strsep(&name, ";");

		if (port && (c = strchr(dom, ':'))) { /* Remove :port */
			*c++ = '\0';
			*port = c;
		}
		if (pass && (c = strchr(name, ':'))) {	/* user:password */
			*c++ = '\0';
			*pass = c;
		}
		*domain = dom;
	}
	if (ret_name)	/* same as for domain, store the result only at the end */
		*ret_name = name;
	if (options)
		*options = uri ? uri : "";

	return error;
}

/*! \brief Send message with Access-URL header, if this is an HTML URL only! */
static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
{
	struct sip_pvt *p = chan->tech_pvt;

	if (subclass != AST_HTML_URL)
		return -1;

	ast_string_field_build(p, url, "<%s>;mode=active", data);

	if (sip_debug_test_pvt(p))
		ast_debug(1, "Send URL %s, state = %d!\n", data, chan->_state);

	switch (chan->_state) {
	case AST_STATE_RING:
		transmit_response(p, "100 Trying", &p->initreq);
		break;
	case AST_STATE_RINGING:
		transmit_response(p, "180 Ringing", &p->initreq);
		break;
	case AST_STATE_UP:
		if (!p->pendinginvite) {		/* We are up, and have no outstanding invite */
			transmit_reinvite_with_sdp(p, FALSE, FALSE);
		} else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
			ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);	
		}	
		break;
	default:
		ast_log(LOG_WARNING, "Don't know how to send URI when state is %d!\n", chan->_state);
	}

	return 0;
}

/*! \brief Deliver SIP call ID for the call */
static const char *sip_get_callid(struct ast_channel *chan)
{
	return chan->tech_pvt ? ((struct sip_pvt *) chan->tech_pvt)->callid : "";
}

/*! \brief Send SIP MESSAGE text within a call
	Called from PBX core sendtext() application */
static int sip_sendtext(struct ast_channel *ast, const char *text)
{
	struct sip_pvt *p = ast->tech_pvt;
	int debug = sip_debug_test_pvt(p);

	if (debug)
		ast_verbose("Sending text %s on %s\n", text, ast->name);
	if (!p)
		return -1;
	/* NOT ast_strlen_zero, because a zero-length message is specifically
	 * allowed by RFC 3428 (See section 10, Examples) */
	if (!text)
		return 0;
	if (debug)
		ast_verbose("Really sending text %s on %s\n", text, ast->name);
	transmit_message_with_text(p, text);
	return 0;	
}

/*! \brief Update peer object in realtime storage 
	If the Asterisk system name is set in asterisk.conf, we will use
	that name and store that in the "regserver" field in the sippeers
	table to facilitate multi-server setups.
*/
static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *defaultuser, const char *fullcontact, int expirey, int deprecated_username, int lastms)
{
	char port[10];
	char ipaddr[INET_ADDRSTRLEN];
	char regseconds[20];
	char *tablename = NULL;
	char str_lastms[20];

	const char *sysname = ast_config_AST_SYSTEM_NAME;
	char *syslabel = NULL;

	time_t nowtime = time(NULL) + expirey;
	const char *fc = fullcontact ? "fullcontact" : NULL;

	int realtimeregs = ast_check_realtime("sipregs");

	tablename = realtimeregs ? "sipregs" : "sippeers";
	

	snprintf(str_lastms, sizeof(str_lastms), "%d", lastms);
	snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);	/* Expiration time */
	ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
	snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
	
	if (ast_strlen_zero(sysname))	/* No system name, disable this */
		sysname = NULL;
	else if (sip_cfg.rtsave_sysname)
		syslabel = "regserver";

	if (fc)
		ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
			"port", port, "regseconds", regseconds,
			deprecated_username ? "username" : "defaultuser", defaultuser, fc, fullcontact, syslabel, sysname, NULL); /* note fc and syslabel _can_ be NULL */
	else
		ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
			"port", port, "regseconds", regseconds,
			deprecated_username ? "username" : "defaultuser", defaultuser, syslabel, sysname, NULL); /* note syslabel _can_ be NULL */
	/* We cannot do this in the same statement as above, because the lack of
	 * this field could cause the whole statement to fail. */
	ast_update_realtime(tablename, "name", peername, "lastms", str_lastms, NULL);
}

/*! \brief Automatically add peer extension to dial plan */
static void register_peer_exten(struct sip_peer *peer, int onoff)
{
	char multi[256];
	char *stringp, *ext, *context;
	struct pbx_find_info q = { .stacklen = 0 };

	/* XXX note that global_regcontext is both a global 'enable' flag and
	 * the name of the global regexten context, if not specified
	 * individually.
	 */
	if (ast_strlen_zero(global_regcontext))
		return;

	ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
	stringp = multi;
	while ((ext = strsep(&stringp, "&"))) {
		if ((context = strchr(ext, '@'))) {
			*context++ = '\0';	/* split ext@context */
			if (!ast_context_find(context)) {
				ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
				continue;
			}
		} else {
			context = global_regcontext;
		}
		if (onoff) {
			if (!ast_exists_extension(NULL, context, ext, 1, NULL)) {
				ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
					 ast_strdup(peer->name), ast_free_ptr, "SIP");
			}
		} else if (pbx_find_extension(NULL, NULL, &q, context, ext, 1, NULL, "", E_MATCH)) {
			ast_context_remove_extension(context, ext, 1, NULL);
		}
	}
}

/*! Destroy mailbox subscriptions */
static void destroy_mailbox(struct sip_mailbox *mailbox)
{
	if (mailbox->mailbox)
		ast_free(mailbox->mailbox);
	if (mailbox->context)
		ast_free(mailbox->context);
	if (mailbox->event_sub)
		ast_event_unsubscribe(mailbox->event_sub);
	ast_free(mailbox);
}

/*! Destroy all peer-related mailbox subscriptions */
static void clear_peer_mailboxes(struct sip_peer *peer)
{
	struct sip_mailbox *mailbox;

	while ((mailbox = AST_LIST_REMOVE_HEAD(&peer->mailboxes, entry)))
		destroy_mailbox(mailbox);
}

/*! \brief Destroy peer object from memory */
static void sip_destroy_peer(struct sip_peer *peer)
{
	ast_debug(3, "Destroying SIP peer %s\n", peer->name);

	if (peer->outboundproxy)
		ast_free(peer->outboundproxy);
	peer->outboundproxy = NULL;

	/* Delete it, it needs to disappear */
	if (peer->call) {
		dialog_cleanup_and_destroy(peer->call);
		peer->call = NULL; /* sip_destroy(peer->call);*/
	}

	if (peer->mwipvt) {    /* We have an active subscription, delete it */
		dialog_cleanup_and_destroy(peer->mwipvt);
		peer->mwipvt = NULL;   /*sip_destroy(peer->mwipvt);*/
	}

	if (peer->chanvars) {
		ast_variables_destroy(peer->chanvars);
		peer->chanvars = NULL;
	}

	/* If the schedule delete fails, that means the schedule is currently
	 * running, which means we should wait for that thread to complete.
	 * Otherwise, there's a crashable race condition.
	 *
	 * NOTE: once peer is refcounted, this probably is no longer necessary.
	 */
	AST_SCHED_DEL(sched, peer->expire);
	AST_SCHED_DEL(sched, peer->pokeexpire);

	register_peer_exten(peer, FALSE);
	ast_free_ha(peer->ha);
	if (peer->selfdestruct)
		apeerobjs--;
	else if (peer->is_realtime) {
		rpeerobjs--;
		ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
	} else
		speerobjs--;
	clear_realm_authentication(peer->auth);
	peer->auth = NULL;
	if (peer->dnsmgr)
		ast_dnsmgr_release(peer->dnsmgr);
	clear_peer_mailboxes(peer);

	if (peer->socket.tcptls_session) {
		ao2_ref(peer->socket.tcptls_session, -1);
		peer->socket.tcptls_session = NULL;
	}
	ast_free(peer);
}

/*! \brief Update peer data in database (if used) */
static void update_peer(struct sip_peer *p, int expiry)
{
	int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
	if (sip_cfg.peer_rtupdate &&
	    (p->is_realtime || rtcachefriends)) {
		realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, expiry, p->deprecated_username, p->lastms);
	}
}

static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config)
{
	struct ast_variable *var = NULL;
	struct ast_flags flags = {0};
	char *cat = NULL;
	const char *insecure;
	while ((cat = ast_category_browse(config, cat))) {
		insecure = ast_variable_retrieve(config, cat, "insecure");
		set_insecure_flags(&flags, insecure, -1);
		if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
			var = ast_category_root(config, cat);
			break;
		}
	}
	return var;
}

static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername)
{
	struct ast_variable *tmp;
	for (tmp = var; tmp; tmp = tmp->next) {
		if (!newpeername && !strcasecmp(tmp->name, "name"))
			newpeername = tmp->value;
	}
	return newpeername;
}

/*! \brief  realtime_peer: Get peer from realtime storage
 * Checks the "sippeers" realtime family from extconfig.conf 
 * Checks the "sipregs" realtime family from extconfig.conf if it's configured.
*/
static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin, int devstate_only)
{
	struct sip_peer *peer;
	struct ast_variable *var = NULL;
	struct ast_variable *varregs = NULL;
	struct ast_variable *tmp;
	struct ast_config *peerlist = NULL;
	char ipaddr[INET_ADDRSTRLEN];
	char portstring[6]; /*up to 5 digits plus null terminator*/
	char *cat = NULL;
	unsigned short portnum;
	int realtimeregs = ast_check_realtime("sipregs");

	/* First check on peer name */
	if (newpeername) {
		if (realtimeregs)
			varregs = ast_load_realtime("sipregs", "name", newpeername, NULL);

		var = ast_load_realtime("sippeers", "name", newpeername, "host", "dynamic", NULL);
		if (!var && sin)
			var = ast_load_realtime("sippeers", "name", newpeername, "host", ast_inet_ntoa(sin->sin_addr), NULL);
		if (!var) {
			var = ast_load_realtime("sippeers", "name", newpeername, NULL);
			/*!\note
			 * If this one loaded something, then we need to ensure that the host
			 * field matched.  The only reason why we can't have this as a criteria
			 * is because we only have the IP address and the host field might be
			 * set as a name (and the reverse PTR might not match).
			 */
			if (var && sin) {
				for (tmp = var; tmp; tmp = tmp->next) {
					if (!strcasecmp(tmp->name, "host")) {
						struct hostent *hp;
						struct ast_hostent ahp;
						if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
							/* No match */
							ast_variables_destroy(var);
							var = NULL;
						}
						break;
					}
				}
			}
		}
	}

	if (!var && sin) {	/* Then check on IP address for dynamic peers */
		ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
		portnum = ntohs(sin->sin_port);
		sprintf(portstring, "%u", portnum);
		var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, NULL);	/* First check for fixed IP hosts */
		if (var) {
			if (realtimeregs) {
				newpeername = get_name_from_variable(var, newpeername);
				varregs = ast_load_realtime("sipregs", "name", newpeername, NULL);
			}
		} else {
			if (realtimeregs)
				varregs = ast_load_realtime("sipregs", "ipaddr", ipaddr, "port", portstring, NULL); /* Then check for registered hosts */
			else
				var = ast_load_realtime("sippeers", "ipaddr", ipaddr, "port", portstring, NULL); /* Then check for registered hosts */
			if (varregs) {
				newpeername = get_name_from_variable(varregs, newpeername);
				var = ast_load_realtime("sippeers", "name", newpeername, NULL);
			}
		}
		if (!var) { /*We couldn't match on ipaddress and port, so we need to check if port is insecure*/
			peerlist = ast_load_realtime_multientry("sippeers", "host", ipaddr, NULL);
			if (peerlist) {
				var = get_insecure_variable_from_config(peerlist);
				if(var) {
					if (realtimeregs) {
						newpeername = get_name_from_variable(var, newpeername);
						varregs = ast_load_realtime("sipregs", "name", newpeername, NULL);
					}
				} else { /*var wasn't found in the list of "hosts", so try "ipaddr"*/
					peerlist = NULL;
					cat = NULL;
					peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, NULL);
					if(peerlist) {
						var = get_insecure_variable_from_config(peerlist);
						if(var) {
							if (realtimeregs) {
								newpeername = get_name_from_variable(var, newpeername);
								varregs = ast_load_realtime("sipregs", "name", newpeername, NULL);
							}
						}
					}
				}
			} else {
				if (realtimeregs) {
					peerlist = ast_load_realtime_multientry("sipregs", "ipaddr", ipaddr, NULL);
					if (peerlist) {
						varregs = get_insecure_variable_from_config(peerlist);
						if (varregs) {
							newpeername = get_name_from_variable(varregs, newpeername);
							var = ast_load_realtime("sippeers", "name", newpeername, NULL);
						}
					}
				} else {
					peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, NULL);
					if (peerlist) {
						var = get_insecure_variable_from_config(peerlist);
						if (var) {
							newpeername = get_name_from_variable(var, newpeername);
							varregs = ast_load_realtime("sipregs", "name", newpeername, NULL);
						}
					}
				}
			}
		}
	}

	if (!var) {
		if (peerlist)
			ast_config_destroy(peerlist);
		return NULL;
	}

	for (tmp = var; tmp; tmp = tmp->next) {
		/* If this is type=user, then skip this object. */
		if (!strcasecmp(tmp->name, "type") &&
		    !strcasecmp(tmp->value, "user")) {
			if(peerlist)
				ast_config_destroy(peerlist);
			else {
				ast_variables_destroy(var);
				ast_variables_destroy(varregs);
			}
			return NULL;
		} else if (!newpeername && !strcasecmp(tmp->name, "name")) {
			newpeername = tmp->value;
		}
	}
	
	if (!newpeername) {	/* Did not find peer in realtime */
		ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", ipaddr);
		if(peerlist)
			ast_config_destroy(peerlist);
		else
			ast_variables_destroy(var);
		return NULL;
	}


	/* Peer found in realtime, now build it in memory */
	peer = build_peer(newpeername, var, varregs, 1, devstate_only);
	if (!peer) {
		if(peerlist)
			ast_config_destroy(peerlist);
		else {
			ast_variables_destroy(var);
			ast_variables_destroy(varregs);
		}
		return NULL;
	}

	ast_debug(3, "-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);

	if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && !devstate_only) {
		/* Cache peer */
		ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
		if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
			AST_SCHED_REPLACE(peer->expire, sched, global_rtautoclear * 1000, expire_register, (void *) peer);
		}
		ASTOBJ_CONTAINER_LINK(&peerl, peer);
	}
	peer->is_realtime = 1;
	if (peerlist)
		ast_config_destroy(peerlist);
	else {
		ast_variables_destroy(var);
		ast_variables_destroy(varregs);
	}

	return peer;
}

/*! \brief Support routine for find_peer */
static int sip_addrcmp(char *name, struct sip_peer *p2)
{
	/* We know name is the first field, so we can cast */
	struct sip_peer *p = (struct sip_peer *) name;
	char tcptls = (p->transports & p2->transports) & (SIP_TRANSPORT_TLS | SIP_TRANSPORT_TCP);

	/* first check to see if it is a perfect ip port match.
	 * if not, check to see if it valid for the peer to be matched only by ip */
	if (!inaddrcmp(&p->addr, &p2->addr)) {
		return 0;
	} else if ((tcptls || ast_test_flag(&p->flags[0], SIP_INSECURE_PORT)) && (p->addr.sin_addr.s_addr == p2->addr.sin_addr.s_addr)) {
		return 0;
	}

	return 1;
}

/*! \brief Locate peer by name or ip address 
 *	This is used on incoming SIP message to find matching peer on ip
	or outgoing message to find matching peer on name 
	\note Avoid using this function in new functions if there's a way to avoid it, i
	since it causes a database lookup or a traversal of the in-memory peer list.
*/
static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int devstate_only, int transport)
{
	struct sip_peer *p = NULL;
	struct sip_peer tmp_peer;

	if (peer) {
		p = ASTOBJ_CONTAINER_FIND(&peerl, peer);
	} else {
		tmp_peer.addr.sin_addr.s_addr = sin->sin_addr.s_addr;
		tmp_peer.addr.sin_port = sin->sin_port;
		tmp_peer.flags[0].flags = 0;
		tmp_peer.transports = transport;

		p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, &tmp_peer, name, sip_addr_hashfunc, 1, sip_addrcmp);
	}

	if (!p && realtime)
		p = realtime_peer(peer, sin, devstate_only);

	return p;
}

/*! \brief Remove user object from in-memory storage */
static void sip_destroy_user(struct sip_user *user)
{
	ast_debug(3, "Destroying user object from memory: %s\n", user->name);

	ast_free_ha(user->ha);
	if (user->chanvars) {
		ast_variables_destroy(user->chanvars);
		user->chanvars = NULL;
	}
	if (user->is_realtime)
		ruserobjs--;
	else
		suserobjs--;
	ast_free(user);
}

/*! \brief Load user from realtime storage
 * Loads user from "sipusers" category in realtime (extconfig.conf)
 * Users are matched on From: user name (the domain in skipped) */
static struct sip_user *realtime_user(const char *username)
{
	struct ast_variable *var;
	struct ast_variable *tmp;
	struct sip_user *user = NULL;

	var = ast_load_realtime("sipusers", "name", username, NULL);

	if (!var)
		return NULL;

	for (tmp = var; tmp; tmp = tmp->next) {
		if (!strcasecmp(tmp->name, "type") &&
			!strcasecmp(tmp->value, "peer")) {
			ast_variables_destroy(var);
			return NULL;
		}
	}

	user = build_user(username, var, NULL, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
	
	if (!user) {	/* No user found */
		ast_variables_destroy(var);
		return NULL;
	}

	if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
		ast_set_flag(&user->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
		suserobjs++;
		ASTOBJ_CONTAINER_LINK(&userl, user);
	} else {
		/* Move counter from s to r... */
		suserobjs--;
		ruserobjs++;
		user->is_realtime = 1;
	}
	ast_variables_destroy(var);
	return user;
}

/*! \brief Locate user by name 
 * Locates user by name (From: sip uri user name part) first
 * from in-memory list (static configuration) then from 
 * realtime storage (defined in extconfig.conf) */
static struct sip_user *find_user(const char *name, int realtime)
{
	struct sip_user *u = ASTOBJ_CONTAINER_FIND(&userl, name);
	if (!u && realtime)
		u = realtime_user(name);
	return u;
}

/*! \brief Set nat mode on the various data sockets */
static void do_setnat(struct sip_pvt *p, int natflags)
{
	const char *mode = natflags ? "On" : "Off";

	if (p->rtp) {
		ast_debug(1, "Setting NAT on RTP to %s\n", mode);
		ast_rtp_setnat(p->rtp, natflags);
	}
	if (p->vrtp) {
		ast_debug(1, "Setting NAT on VRTP to %s\n", mode);
		ast_rtp_setnat(p->vrtp, natflags);
	}
	if (p->udptl) {
		ast_debug(1, "Setting NAT on UDPTL to %s\n", mode);
		ast_udptl_setnat(p->udptl, natflags);
	}
	if (p->trtp) {
		ast_debug(1, "Setting NAT on TRTP to %s\n", mode);
		ast_rtp_setnat(p->trtp, natflags);
	}
}

/*! \brief Change the T38 state on a SIP dialog */
static void change_t38_state(struct sip_pvt *p, int state)
{
	int old = p->t38.state;
	struct ast_channel *chan = p->owner;
	struct ast_control_t38_parameters parameters = { .request_response = 0 };

	/* Don't bother changing if we are already in the state wanted */
	if (old == state)
		return;

	p->t38.state = state;
	ast_debug(2, "T38 state changed to %d on channel %s\n", p->t38.state, chan ? chan->name : "<none>");

	/* If no channel was provided we can't send off a control frame */
	if (!chan)
		return;

	/* Given the state requested and old state determine what control frame we want to queue up */
	switch (state) {
	case T38_PEER_REINVITE:
		parameters = p->t38.their_parms;
		parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
		parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
		ast_udptl_set_tag(p->udptl, "SIP/%s", p->username);
		break;
	case T38_ENABLED:
		parameters = p->t38.their_parms;
		parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
		parameters.request_response = AST_T38_NEGOTIATED;
		ast_udptl_set_tag(p->udptl, "SIP/%s", p->username);
		break;
	case T38_DISABLED:
		if (old == T38_ENABLED) {
			parameters.request_response = AST_T38_TERMINATED;
		} else if (old == T38_LOCAL_REINVITE) {
			parameters.request_response = AST_T38_REFUSED;
		}
		break;
	case T38_LOCAL_REINVITE:
		/* wait until we get a peer response before responding to local reinvite */
		break;
	}

	/* Woot we got a message, create a control frame and send it on! */
	if (parameters.request_response)
		ast_queue_control_data(chan, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
}

/*! \brief Set the global T38 capabilities on a SIP dialog structure */
static void set_t38_capabilities(struct sip_pvt *p)
{
	if (p->udptl) {
		if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY) {
                        ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
		} else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_FEC) {
			ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
		} else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL) {
			ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
		}
	}
}

static void copy_socket_data(struct sip_socket *to_sock, const struct sip_socket *from_sock)
{
	if (to_sock->tcptls_session) {
		ao2_ref(to_sock->tcptls_session, -1);
		to_sock->tcptls_session = NULL;
	}

	if (from_sock->tcptls_session) {
		ao2_ref(from_sock->tcptls_session, +1);
	}

	*to_sock = *from_sock;
}

/*! \brief Create address structure from peer reference.
 *	This function copies data from peer to the dialog, so we don't have to look up the peer
 *	again from memory or database during the life time of the dialog.
 *
 * \return -1 on error, 0 on success.
 */
static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
{
	/* this checks that the dialog is contacting the peer on a valid
	 * transport type based on the peers transport configuration,
	 * otherwise, this function bails out */
	if (dialog->socket.type && check_request_transport(peer, dialog))
		return -1;
	copy_socket_data(&dialog->socket, &peer->socket);

	if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
	    (!peer->maxms || ((peer->lastms >= 0)  && (peer->lastms <= peer->maxms)))) {
		dialog->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
		dialog->recv = dialog->sa;
	} else 
		return -1;

	ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
	ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
	dialog->capability = peer->capability;
	if ((!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(dialog->capability & AST_FORMAT_VIDEO_MASK)) && dialog->vrtp) {
		ast_rtp_destroy(dialog->vrtp);
		dialog->vrtp = NULL;
	}
	if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT) && dialog->trtp) {
		ast_rtp_destroy(dialog->trtp);
		dialog->trtp = NULL;
	}
	dialog->prefs = peer->prefs;
	if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
		if (!dialog->udptl) {
			/* t38pt_udptl was enabled in the peer and not in [general] */
			dialog->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr);
		}
		dialog->t38_maxdatagram = peer->t38_maxdatagram;
		set_t38_capabilities(dialog);
	} else if (dialog->udptl) {
		ast_udptl_destroy(dialog->udptl);
		dialog->udptl = NULL;
	}
	do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE);

	if (dialog->rtp) { /* Audio */
		ast_rtp_setdtmf(dialog->rtp, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
		ast_rtp_setdtmfcompensate(dialog->rtp, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
		ast_rtp_set_rtptimeout(dialog->rtp, peer->rtptimeout);
		ast_rtp_set_rtpholdtimeout(dialog->rtp, peer->rtpholdtimeout);
		ast_rtp_set_rtpkeepalive(dialog->rtp, peer->rtpkeepalive);
		/* Set Frame packetization */
		ast_rtp_codec_setpref(dialog->rtp, &dialog->prefs);
		dialog->autoframing = peer->autoframing;
	}
	if (dialog->vrtp) { /* Video */
		ast_rtp_setdtmf(dialog->vrtp, 0);
		ast_rtp_setdtmfcompensate(dialog->vrtp, 0);
		ast_rtp_set_rtptimeout(dialog->vrtp, peer->rtptimeout);
		ast_rtp_set_rtpholdtimeout(dialog->vrtp, peer->rtpholdtimeout);
		ast_rtp_set_rtpkeepalive(dialog->vrtp, peer->rtpkeepalive);
	}
	if (dialog->trtp) { /* Realtime text */
		ast_rtp_setdtmf(dialog->trtp, 0);
		ast_rtp_setdtmfcompensate(dialog->trtp, 0);
		ast_rtp_set_rtptimeout(dialog->trtp, peer->rtptimeout);
		ast_rtp_set_rtpholdtimeout(dialog->trtp, peer->rtpholdtimeout);
		ast_rtp_set_rtpkeepalive(dialog->trtp, peer->rtpkeepalive);
	}

	ast_string_field_set(dialog, peername, peer->name);
	ast_string_field_set(dialog, authname, peer->username);
	ast_string_field_set(dialog, username, peer->username);
	ast_string_field_set(dialog, peersecret, peer->secret);
	ast_string_field_set(dialog, peermd5secret, peer->md5secret);
	ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
	ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
	ast_string_field_set(dialog, tohost, peer->tohost);
	ast_string_field_set(dialog, fullcontact, peer->fullcontact);
	ast_string_field_set(dialog, context, peer->context);
	dialog->outboundproxy = obproxy_get(dialog, peer);
	dialog->callgroup = peer->callgroup;
	dialog->pickupgroup = peer->pickupgroup;
	dialog->allowtransfer = peer->allowtransfer;
	dialog->jointnoncodeccapability = dialog->noncodeccapability;
	dialog->rtptimeout = peer->rtptimeout;
	dialog->peerauth = peer->auth;
	dialog->maxcallbitrate = peer->maxcallbitrate;
	if (!dialog->portinuri)
		dialog->portinuri = peer->portinuri;
	if (ast_strlen_zero(dialog->tohost))
		ast_string_field_set(dialog, tohost, ast_inet_ntoa(dialog->sa.sin_addr));
	if (!ast_strlen_zero(peer->fromdomain)) {
		ast_string_field_set(dialog, fromdomain, peer->fromdomain);
		if (!dialog->initreq.headers) {
			char *c;
			char *tmpcall = ast_strdupa(dialog->callid);

			c = strchr(tmpcall, '@');
			if (c) {
				*c = '\0';
				ast_string_field_build(dialog, callid, "%s@%s", tmpcall, peer->fromdomain);
			}
		}
	}
	if (!ast_strlen_zero(peer->fromuser)) 
		ast_string_field_set(dialog, fromuser, peer->fromuser);
	if (!ast_strlen_zero(peer->language))
		ast_string_field_set(dialog, language, peer->language);
	/* Set timer T1 to RTT for this peer (if known by qualify=) */
	/* Minimum is settable or default to 100 ms */
	/* If there is a maxms and lastms from a qualify use that over a manual T1
	   value. Otherwise, use the peer's T1 value. */
	if (peer->maxms && peer->lastms)
		dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
	else
		dialog->timer_t1 = peer->timer_t1;

	/* Set timer B to control transaction timeouts, the peer setting is the default and overrides
	   the known timer */
	if (peer->timer_b)
		dialog->timer_b = peer->timer_b;
	else
		dialog->timer_b = 64 * dialog->timer_t1;

	if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
	    (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
		dialog->noncodeccapability |= AST_RTP_DTMF;
	else
		dialog->noncodeccapability &= ~AST_RTP_DTMF;
	if (peer->call_limit)
		ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
	
	return 0;
}

/*! \brief create address structure from peer name
 *      Or, if peer not found, find it in the global DNS 
 *      returns TRUE (-1) on failure, FALSE on success */
static int create_addr(struct sip_pvt *dialog, const char *opeer, int newdialog)
{
	struct hostent *hp;
	struct ast_hostent ahp;
	struct sip_peer *peer;
	char *port;
	int portno = 0;
	char host[MAXHOSTNAMELEN], *hostn;
	char peername[256];

	ast_copy_string(peername, opeer, sizeof(peername));
	port = strchr(peername, ':');
	if (port) {
		*port++ = '\0';
		dialog->portinuri = 1;
	}
	dialog->sa.sin_family = AF_INET;
	dialog->timer_t1 = global_t1; /* Default SIP retransmission timer T1 (RFC 3261) */
	dialog->timer_b = global_timer_b; /* Default SIP transaction timer B (RFC 3261) */
	peer = find_peer(peername, NULL, 1, 0, 0);

	if (peer) {
		int res;
		if (newdialog) {
			set_socket_transport(&dialog->socket, 0);
		}
		res = create_addr_from_peer(dialog, peer);
		unref_peer(peer);
		if (!ast_strlen_zero(port)) {
			if ((portno = atoi(port))) {
				dialog->sa.sin_port = dialog->recv.sin_port = htons(portno);
			}
		}
		return res;
	}

	do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE);

	ast_string_field_set(dialog, tohost, peername);

	/* Get the outbound proxy information */
	dialog->outboundproxy = obproxy_get(dialog, NULL);

	/* Let's see if we can find the host in DNS. First try DNS SRV records,
	   then hostname lookup */
	/*! \todo Fix this function. When we ask SRC, we should check all transports 
	  In the future, we should first check NAPTR to find out transport preference
	*/

	hostn = peername;
	/* Section 4.2 of RFC 3263 specifies that if a port number is specified, then
	 * an A record lookup should be used instead of SRV.
	 */
	if (!port && global_srvlookup) {
		char service[MAXHOSTNAMELEN];
		int tportno;
		int ret;

		snprintf(service, sizeof(service), "_sip._%s.%s", get_transport(dialog->socket.type), peername);
		ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
		if (ret > 0) {
			hostn = host;
			portno = tportno;
		}
	}
	if (!portno)
		portno = port_str2int(port, (dialog->socket.type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
	hp = ast_gethostbyname(hostn, &ahp);
	if (!hp) {
		ast_log(LOG_WARNING, "No such host: %s\n", peername);
		return -1;
	}
	memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
	if (ast_strlen_zero(port) || sscanf(port, "%5u", &portno) != 1) {
		portno = (dialog->socket.type & SIP_TRANSPORT_TLS) ? 
			STANDARD_TLS_PORT : STANDARD_SIP_PORT;
	}

	if (!dialog->socket.type)
		set_socket_transport(&dialog->socket, SIP_TRANSPORT_UDP);
	if (!dialog->socket.port)
		dialog->socket.port = bindaddr.sin_port;

	dialog->sa.sin_port = htons(portno);
	dialog->recv = dialog->sa;
	return 0;
}

/*! \brief Scheduled congestion on a call.
 * Only called by the scheduler, must return the reference when done.
 */
static int auto_congest(const void *arg)
{
	struct sip_pvt *p = (struct sip_pvt *)arg;

	sip_pvt_lock(p);
	p->initid = -1;	/* event gone, will not be rescheduled */
	if (p->owner) {
		/* XXX fails on possible deadlock */
		if (!ast_channel_trylock(p->owner)) {
			ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
			append_history(p, "Cong", "Auto-congesting (timer)");
			ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
			ast_channel_unlock(p->owner);
		}

		/* Give the channel a chance to act before we proceed with destruction */
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
	}
	sip_pvt_unlock(p);
	return 0;
}


/*! \brief Initiate SIP call from PBX 
 *      used from the dial() application      */
static int sip_call(struct ast_channel *ast, char *dest, int timeout)
{
	int res;
	struct sip_pvt *p = ast->tech_pvt;	/* chan is locked, so the reference cannot go away */
	struct varshead *headp;
	struct ast_var_t *current;
	const char *referer = NULL;   /* SIP referrer */

	if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
		ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
		return -1;
	}

	/* Check whether there is vxml_url, distinctive ring variables */
	headp=&ast->varshead;
	AST_LIST_TRAVERSE(headp, current, entries) {
		/* Check whether there is a VXML_URL variable */
		if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
			p->options->vxml_url = ast_var_value(current);
		} else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
			p->options->uri_options = ast_var_value(current);
		} else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
			/* Check whether there is a variable with a name starting with SIPADDHEADER */
			p->options->addsipheaders = 1;
		} else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
			/* This is a transfered call */
			p->options->transfer = 1;
		} else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
			/* This is the referrer */
			referer = ast_var_value(current);
		} else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
			/* We're replacing a call. */
			p->options->replaces = ast_var_value(current);
		}
	}

	res = 0;
	ast_set_flag(&p->flags[0], SIP_OUTGOING);

	if (p->options->transfer) {
		char buf[SIPBUFSIZE/2];

		if (referer) {
			if (sipdebug)
				ast_debug(3, "Call for %s transfered by %s\n", p->username, referer);
			snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
		} else 
			snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
		ast_string_field_set(p, cid_name, buf);
	} 
	ast_debug(1, "Outgoing Call for %s\n", p->username);

	res = update_call_counter(p, INC_CALL_RINGING);

	if (res == -1) {
		ast->hangupcause = AST_CAUSE_USER_BUSY;
		return res;
	}
	p->callingpres = ast->cid.cid_pres;
	p->jointcapability = ast_translate_available_formats(p->capability, p->prefcodec);
	p->jointnoncodeccapability = p->noncodeccapability;

	/* If there are no audio formats left to offer, punt */
	if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
		ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
		res = -1;
	} else {
		int xmitres;

		xmitres = transmit_invite(p, SIP_INVITE, 1, 2);
		if (xmitres == XMIT_ERROR)
			return -1;
		p->invitestate = INV_CALLING;
	
		/* Initialize auto-congest time */
		AST_SCHED_REPLACE(p->initid, sched, p->timer_b, auto_congest, p);
	}

	return res;
}

/*! \brief Destroy registry object
	Objects created with the register= statement in static configuration */
static void sip_registry_destroy(struct sip_registry *reg)
{
	/* Really delete */
	ast_debug(3, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);

	if (reg->call) {
		/* Clear registry before destroying to ensure
		   we don't get reentered trying to grab the registry lock */
		reg->call->registry = NULL;
		ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
		dialog_cleanup_and_destroy(reg->call);
		reg->call = NULL; /*sip_destroy(reg->call);*/
	}
	AST_SCHED_DEL(sched, reg->expire);
	AST_SCHED_DEL(sched, reg->timeout);
	ast_string_field_free_memory(reg);
	regobjs--;
	ast_free(reg);
}

/*! \brief Execute destruction of SIP dialog structure, release memory */
static int __sip_destroy(struct sip_pvt *p, int lockowner)
{
	struct sip_pkt *cp;
	struct sip_request *req;

	if (p->stimer) {
		ast_free(p->stimer);
		p->stimer = NULL;
	}

	if (sip_debug_test_pvt(p))
		ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);

	if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
		update_call_counter(p, DEC_CALL_LIMIT);
		ast_debug(2, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
	}

	/* Unlink us from the owner if we have one */
	if (p->owner) {
		if (lockowner)
			ast_channel_lock(p->owner);
		if (option_debug)
			ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
		p->owner->tech_pvt = NULL;
		/* Make sure that the channel knows its backend is going away */
		p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
		if (lockowner)
			ast_channel_unlock(p->owner);
		/* Give the channel a chance to react before deallocation */
		usleep(1);
	}

	/* Remove link from peer to subscription of MWI */
	if (p->relatedpeer && p->relatedpeer->mwipvt == p) 
		p->relatedpeer->mwipvt = NULL;

	if (dumphistory)
		sip_dump_history(p);

	if (p->options)
		ast_free(p->options);

	if (p->stateid > -1)
		ast_extension_state_del(p->stateid, NULL);
	AST_SCHED_DEL(sched, p->initid);
	AST_SCHED_DEL(sched, p->waitid);
	AST_SCHED_DEL(sched, p->autokillid);
	AST_SCHED_DEL(sched, p->request_queue_sched_id);
	AST_SCHED_DEL_UNREF(sched, p->provisional_keepalive_sched_id, dialog_unref(p));
	AST_SCHED_DEL(sched, p->t38id);

	if (p->rtp) {
		ast_rtp_destroy(p->rtp);
	}
	if (p->vrtp) {
		ast_rtp_destroy(p->vrtp);
	}
	if (p->trtp) {
		while (ast_rtp_get_bridged(p->trtp))
			usleep(1);
		ast_rtp_destroy(p->trtp);
	}
	if (p->udptl)
		ast_udptl_destroy(p->udptl);
	if (p->refer)
		ast_free(p->refer);
	if (p->route) {
		free_old_route(p->route);
		p->route = NULL;
	}
	if (p->registry) {
		if (p->registry->call == p)
			p->registry->call = NULL;
		p->registry = registry_unref(p->registry);
	}

	/* Clear history */
	if (p->history) {
		struct sip_history *hist;
		while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
			ast_free(hist);
			p->history_entries--;
		}
		ast_free(p->history);
		p->history = NULL;
	}

	while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
		ast_free(req);
	}

	/* remove all current packets in this dialog */
	while((cp = p->packets)) {
		p->packets = p->packets->next;
		AST_SCHED_DEL(sched, cp->retransid);
		ast_free(cp);
	}
	if (p->chanvars) {
		ast_variables_destroy(p->chanvars);
		p->chanvars = NULL;
	}
	ast_mutex_destroy(&p->pvt_lock);

	ast_string_field_free_memory(p);

	if (p->socket.tcptls_session) {
		ao2_ref(p->socket.tcptls_session, -1);
		p->socket.tcptls_session = NULL;
	}

	return 0;
}

/*! \brief  update_call_counter: Handle call_limit for SIP users 
 * Setting a call-limit will cause calls above the limit not to be accepted.
 *
 * Remember that for a type=friend, there's one limit for the user and
 * another for the peer, not a combined call limit.
 * This will cause unexpected behaviour in subscriptions, since a "friend"
 * is *two* devices in Asterisk, not one.
 *
 * Thought: For realtime, we should probably update storage with inuse counter... 
 *
 * \return 0 if call is ok (no call limit, below threshold)
 *	-1 on rejection of call
 *		
 */
static int update_call_counter(struct sip_pvt *fup, int event)
{
	char name[256];
	int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
	int outgoing = fup->outgoing_call;
	struct sip_user *u = NULL;
	struct sip_peer *p = NULL;
	ast_mutex_t *pu_lock = NULL;

	ast_debug(3, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");


	/* Test if we need to check call limits, in order to avoid 
	   realtime lookups if we do not need it */
	if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
		return 0;

	ast_copy_string(name, fup->username, sizeof(name));

	/* Check the list of users only for incoming calls */
	if (global_limitonpeers == FALSE && !outgoing && (u = find_user(name, 1)))  {
		inuse = &u->inUse;
		call_limit = &u->call_limit;
		inringing = NULL;
		pu_lock = &u->_lock;
	} else if ( (p = find_peer(ast_strlen_zero(fup->peername) ? name : fup->peername, NULL, 1, 0, 0) ) ) { /* Try to find peer */
		inuse = &p->inUse;
		call_limit = &p->call_limit;
		inringing = &p->inRinging;
		ast_copy_string(name, fup->peername, sizeof(name));
		pu_lock = &p->_lock;
	}
	if (!p && !u) {
		ast_debug(2, "%s is not a local device, no call limit\n", name);
		return 0;
	}

	switch(event) {
	/* incoming and outgoing affects the inUse counter */
	case DEC_CALL_LIMIT:
		/* Decrement inuse count if applicable */
		if (inuse) {
			sip_pvt_lock(fup);
			ast_mutex_lock(pu_lock);
			if (*inuse > 0) {
				if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
					(*inuse)--;
					ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
				}
			} else {
				*inuse = 0;
			}
			ast_mutex_unlock(pu_lock);
			sip_pvt_unlock(fup);
		}

		/* Decrement ringing count if applicable */
		if (inringing) {
			sip_pvt_lock(fup);
			ast_mutex_lock(pu_lock);
			if (*inringing > 0) {
				if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
					(*inringing)--;
					ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
				}
			} else {
			   *inringing = 0;
			}
			ast_mutex_unlock(pu_lock);
			sip_pvt_unlock(fup);
		}

		/* Decrement onhold count if applicable */
			sip_pvt_lock(fup);
			ast_mutex_lock(pu_lock);
		if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && global_notifyhold) {
			ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
			ast_mutex_unlock(pu_lock);
			sip_pvt_unlock(fup);
			sip_peer_hold(fup, FALSE);
		} else {
			ast_mutex_unlock(pu_lock);
			sip_pvt_unlock(fup);
		}
		if (sipdebug)
			ast_debug(2, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
		break;

	case INC_CALL_RINGING:
	case INC_CALL_LIMIT:
		/* If call limit is active and we have reached the limit, reject the call */
		if (*call_limit > 0 ) {
			if (*inuse >= *call_limit) {
				ast_log(LOG_ERROR, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
				if (u)
					unref_user(u);
				else
					unref_peer(p);
				return -1; 
			}
		}
		if (inringing && (event == INC_CALL_RINGING)) {
			sip_pvt_lock(fup);
			ast_mutex_lock(pu_lock);
			if (!ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
				(*inringing)++;
				ast_set_flag(&fup->flags[0], SIP_INC_RINGING);
			}
			ast_mutex_unlock(pu_lock);
			sip_pvt_unlock(fup);
		}
		if (inuse) {
			sip_pvt_lock(fup);
			ast_mutex_lock(pu_lock);
			if (!ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
				(*inuse)++;
				ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
			}
			ast_mutex_unlock(pu_lock);
			sip_pvt_unlock(fup);
		}
		if (sipdebug) {
			ast_debug(2, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *inuse, *call_limit);
		}
		break;

	case DEC_CALL_RINGING:
		if (inringing) {
			sip_pvt_lock(fup);
			ast_mutex_lock(pu_lock);
			if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
				if (*inringing > 0) {
					(*inringing)--;
				}
				ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
			}
			ast_mutex_unlock(pu_lock);
			sip_pvt_unlock(fup);
		}
		break;

	default:
		ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
	}

	if (p) {
		ast_device_state_changed("SIP/%s", p->name);
		unref_peer(p);
	} else /* u must be set */
		unref_user(u);
	return 0;
}

/*! the dialog ao2obj destructor function */
static void sip_destroy_fn(void *p)
{
	sip_destroy(p);
}

/*! \brief Destroy SIP call structure.
 * Make it return NULL so the caller can do things like
 *	foo = sip_destroy(foo);
 * and reduce the chance of bugs due to dangling pointers.
 */
static struct sip_pvt * sip_destroy(struct sip_pvt *p)
{
	ast_debug(3, "Destroying SIP dialog %s\n", p->callid);
	__sip_destroy(p, TRUE);
	return NULL;
}

/*! \brief Convert SIP hangup causes to Asterisk hangup causes */
static int hangup_sip2cause(int cause)
{
	/* Possible values taken from causes.h */

	switch(cause) {
		case 401:	/* Unauthorized */
			return AST_CAUSE_CALL_REJECTED;
		case 403:	/* Not found */
			return AST_CAUSE_CALL_REJECTED;
		case 404:	/* Not found */
			return AST_CAUSE_UNALLOCATED;
		case 405:	/* Method not allowed */
			return AST_CAUSE_INTERWORKING;
		case 407:	/* Proxy authentication required */
			return AST_CAUSE_CALL_REJECTED;
		case 408:	/* No reaction */
			return AST_CAUSE_NO_USER_RESPONSE;
		case 409:	/* Conflict */
			return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
		case 410:	/* Gone */
			return AST_CAUSE_NUMBER_CHANGED;
		case 411:	/* Length required */
			return AST_CAUSE_INTERWORKING;
		case 413:	/* Request entity too large */
			return AST_CAUSE_INTERWORKING;
		case 414:	/* Request URI too large */
			return AST_CAUSE_INTERWORKING;
		case 415:	/* Unsupported media type */
			return AST_CAUSE_INTERWORKING;
		case 420:	/* Bad extension */
			return AST_CAUSE_NO_ROUTE_DESTINATION;
		case 480:	/* No answer */
			return AST_CAUSE_NO_ANSWER;
		case 481:	/* No answer */
			return AST_CAUSE_INTERWORKING;
		case 482:	/* Loop detected */
			return AST_CAUSE_INTERWORKING;
		case 483:	/* Too many hops */
			return AST_CAUSE_NO_ANSWER;
		case 484:	/* Address incomplete */
			return AST_CAUSE_INVALID_NUMBER_FORMAT;
		case 485:	/* Ambiguous */
			return AST_CAUSE_UNALLOCATED;
		case 486:	/* Busy everywhere */
			return AST_CAUSE_BUSY;
		case 487:	/* Request terminated */
			return AST_CAUSE_INTERWORKING;
		case 488:	/* No codecs approved */
			return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
		case 491:	/* Request pending */
			return AST_CAUSE_INTERWORKING;
		case 493:	/* Undecipherable */
			return AST_CAUSE_INTERWORKING;
		case 500:	/* Server internal failure */
			return AST_CAUSE_FAILURE;
		case 501:	/* Call rejected */
			return AST_CAUSE_FACILITY_REJECTED;
		case 502:	
			return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
		case 503:	/* Service unavailable */
			return AST_CAUSE_CONGESTION;
		case 504:	/* Gateway timeout */
			return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
		case 505:	/* SIP version not supported */
			return AST_CAUSE_INTERWORKING;
		case 600:	/* Busy everywhere */
			return AST_CAUSE_USER_BUSY;
		case 603:	/* Decline */
			return AST_CAUSE_CALL_REJECTED;
		case 604:	/* Does not exist anywhere */
			return AST_CAUSE_UNALLOCATED;
		case 606:	/* Not acceptable */
			return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
		default:
			return AST_CAUSE_NORMAL;
	}
	/* Never reached */
	return 0;
}

/*! \brief Convert Asterisk hangup causes to SIP codes 
\verbatim
 Possible values from causes.h
        AST_CAUSE_NOTDEFINED    AST_CAUSE_NORMAL        AST_CAUSE_BUSY
        AST_CAUSE_FAILURE       AST_CAUSE_CONGESTION    AST_CAUSE_UNALLOCATED

	In addition to these, a lot of PRI codes is defined in causes.h 
	...should we take care of them too ?
	
	Quote RFC 3398

   ISUP Cause value                        SIP response
   ----------------                        ------------
   1  unallocated number                   404 Not Found
   2  no route to network                  404 Not found
   3  no route to destination              404 Not found
   16 normal call clearing                 --- (*)
   17 user busy                            486 Busy here
   18 no user responding                   408 Request Timeout
   19 no answer from the user              480 Temporarily unavailable
   20 subscriber absent                    480 Temporarily unavailable
   21 call rejected                        403 Forbidden (+)
   22 number changed (w/o diagnostic)      410 Gone
   22 number changed (w/ diagnostic)       301 Moved Permanently
   23 redirection to new destination       410 Gone
   26 non-selected user clearing           404 Not Found (=)
   27 destination out of order             502 Bad Gateway
   28 address incomplete                   484 Address incomplete
   29 facility rejected                    501 Not implemented
   31 normal unspecified                   480 Temporarily unavailable
\endverbatim
*/
static const char *hangup_cause2sip(int cause)
{
	switch (cause) {
		case AST_CAUSE_UNALLOCATED:		/* 1 */
		case AST_CAUSE_NO_ROUTE_DESTINATION:	/* 3 IAX2: Can't find extension in context */
		case AST_CAUSE_NO_ROUTE_TRANSIT_NET:	/* 2 */
			return "404 Not Found";
		case AST_CAUSE_CONGESTION:		/* 34 */
		case AST_CAUSE_SWITCH_CONGESTION:	/* 42 */
			return "503 Service Unavailable";
		case AST_CAUSE_NO_USER_RESPONSE:	/* 18 */
			return "408 Request Timeout";
		case AST_CAUSE_NO_ANSWER:		/* 19 */
		case AST_CAUSE_UNREGISTERED:        /* 20 */
			return "480 Temporarily unavailable";
		case AST_CAUSE_CALL_REJECTED:		/* 21 */
			return "403 Forbidden";
		case AST_CAUSE_NUMBER_CHANGED:		/* 22 */
			return "410 Gone";
		case AST_CAUSE_NORMAL_UNSPECIFIED:	/* 31 */
			return "480 Temporarily unavailable";
		case AST_CAUSE_INVALID_NUMBER_FORMAT:
			return "484 Address incomplete";
		case AST_CAUSE_USER_BUSY:
			return "486 Busy here";
		case AST_CAUSE_FAILURE:
			return "500 Server internal failure";
		case AST_CAUSE_FACILITY_REJECTED:	/* 29 */
			return "501 Not Implemented";
		case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
			return "503 Service Unavailable";
		/* Used in chan_iax2 */
		case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
			return "502 Bad Gateway";
		case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL:	/* Can't find codec to connect to host */
			return "488 Not Acceptable Here";
			
		case AST_CAUSE_NOTDEFINED:
		default:
			ast_debug(1, "AST hangup cause %d (no match found in SIP)\n", cause);
			return NULL;
	}

	/* Never reached */
	return 0;
}


/*! \brief  sip_hangup: Hangup SIP call
 * Part of PBX interface, called from ast_hangup */
static int sip_hangup(struct ast_channel *ast)
{
	struct sip_pvt *p = ast->tech_pvt;
	int needcancel = FALSE;
	int needdestroy = 0;
	struct ast_channel *oldowner = ast;

	if (!p) {
		ast_debug(1, "Asked to hangup channel that was not connected\n");
		return 0;
	}
	if (ast_test_flag(ast, AST_FLAG_ANSWERED_ELSEWHERE)) {
		ast_debug(1, "This call was answered elsewhere");
		append_history(p, "Cancel", "Call answered elsewhere");
		p->answered_elsewhere = TRUE;
	}

	/* Store hangupcause locally in PVT so we still have it before disconnect */
	if (p->owner)
		p->hangupcause = p->owner->hangupcause;

	if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
		if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
			if (sipdebug)
				ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
			update_call_counter(p, DEC_CALL_LIMIT);
		}
		ast_debug(4, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
		if (p->autokillid > -1 && sip_cancel_destroy(p))
			ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
		ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);	/* Really hang up next time */
		p->needdestroy = 0;
		p->owner->tech_pvt = NULL;
		p->owner = NULL;  /* Owner will be gone after we return, so take it away */
		return 0;
	}

	if (ast_test_flag(ast, AST_FLAG_ZOMBIE)) {
		if (p->refer)
			ast_debug(1, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast->name, p->callid);
		else
			ast_debug(1, "Hanging up zombie call. Be scared.\n");
	} else
		ast_debug(1, "Hangup call %s, SIP callid %s\n", ast->name, p->callid);

	sip_pvt_lock(p);
	if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
		if (sipdebug)
			ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
		update_call_counter(p, DEC_CALL_LIMIT);
	}

	/* Determine how to disconnect */
	if (p->owner != ast) {
		ast_log(LOG_WARNING, "Huh?  We aren't the owner? Can't hangup call.\n");
		sip_pvt_unlock(p);
		return 0;
	}
	/* If the call is not UP, we need to send CANCEL instead of BYE */
	/* In case of re-invites, the call might be UP even though we have an incomplete invite transaction */
	if (p->invitestate < INV_COMPLETED && p->owner->_state != AST_STATE_UP) {
		needcancel = TRUE;
		ast_debug(4, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
	}

	stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */

	append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", p->owner ? ast_cause2str(p->hangupcause) : "Unknown");

	/* Disconnect */
	if (p->dsp)
		ast_dsp_free(p->dsp);

	p->owner = NULL;
	ast->tech_pvt = NULL;

	ast_module_unref(ast_module_info->self);
	/* Do not destroy this pvt until we have timeout or
	   get an answer to the BYE or INVITE/CANCEL 
	   If we get no answer during retransmit period, drop the call anyway.
	   (Sorry, mother-in-law, you can't deny a hangup by sending
	   603 declined to BYE...)
	*/
	if (p->alreadygone)
		needdestroy = 1;	/* Set destroy flag at end of this function */
	else if (p->invitestate != INV_CALLING)
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);

	/* Start the process if it's not already started */
	if (!p->alreadygone && !ast_strlen_zero(p->initreq.data)) {
		if (needcancel) {	/* Outgoing call, not up */
			if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
				/* stop retransmitting an INVITE that has not received a response */
				/* if we can't send right now, mark it pending */
				if (p->invitestate == INV_CALLING) {
					/* We can't send anything in CALLING state */
					ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
					__sip_pretend_ack(p);
					/* Do we need a timer here if we don't hear from them at all? Yes we do or else we will get hung dialogs and those are no fun. */
					sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
					append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
				} else {
					struct sip_pkt *cur;

					for (cur = p->packets; cur; cur = cur->next) {
						__sip_semi_ack(p, cur->seqno, cur->is_resp, cur->method ? cur->method : find_sip_method(cur->data));
					}
					p->invitestate = INV_CANCELLED;
					/* Send a new request: CANCEL */
					transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
					/* Actually don't destroy us yet, wait for the 487 on our original 
					   INVITE, but do set an autodestruct just in case we never get it. */
					needdestroy = 0;
					sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
				}
			} else {	/* Incoming call, not up */
				const char *res;
				AST_SCHED_DEL_UNREF(sched, p->provisional_keepalive_sched_id, dialog_unref(p));
				if (p->hangupcause && (res = hangup_cause2sip(p->hangupcause)))
					transmit_response_reliable(p, res, &p->initreq);
				else 
					transmit_response_reliable(p, "603 Declined", &p->initreq);
				p->invitestate = INV_TERMINATED;
			}
		} else {	/* Call is in UP state, send BYE */
			if (p->stimer->st_active == TRUE) {
				stop_session_timer(p);
			}

			if (!p->pendinginvite) {
				char *audioqos = "";
				char *videoqos = "";
				char *textqos = "";
				if (p->rtp)
					audioqos = ast_rtp_get_quality(p->rtp, NULL);
				if (p->vrtp)
					videoqos = ast_rtp_get_quality(p->vrtp, NULL);
				if (p->trtp)
					textqos = ast_rtp_get_quality(p->trtp, NULL);
				/* Send a hangup */
				if (oldowner->_state == AST_STATE_UP) {
					transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
				}

				/* Get RTCP quality before end of call */
				if (p->do_history) {
					if (p->rtp)
						append_history(p, "RTCPaudio", "Quality:%s", audioqos);
					if (p->vrtp)
						append_history(p, "RTCPvideo", "Quality:%s", videoqos);
					if (p->trtp)
						append_history(p, "RTCPtext", "Quality:%s", textqos);
				}
				if (p->rtp && oldowner)
					pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", audioqos);
				if (p->vrtp && oldowner)
					pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", videoqos);
				if (p->trtp && oldowner)
					pbx_builtin_setvar_helper(oldowner, "RTPTEXTQOS", textqos);
			} else {
				/* Note we will need a BYE when this all settles out
				   but we can't send one while we have "INVITE" outstanding. */
				ast_set_flag(&p->flags[0], SIP_PENDINGBYE);	
				ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);	
				AST_SCHED_DEL(sched, p->waitid);
				if (sip_cancel_destroy(p))
					ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
			}
		}
	}
	if (needdestroy)
		p->needdestroy = 1;
	sip_pvt_unlock(p);
	return 0;
}

/*! \brief Try setting codec suggested by the SIP_CODEC channel variable */
static void try_suggested_sip_codec(struct sip_pvt *p)
{
	int fmt;
	const char *codec;

	codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
	if (!codec) 
		return;

	fmt = ast_getformatbyname(codec);
	if (fmt) {
		ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
		if (p->jointcapability & fmt) {
			p->jointcapability &= fmt;
			p->capability &= fmt;
		} else
			ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
	} else
		ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
	return;	
}

/*! \brief  sip_answer: Answer SIP call , send 200 OK on Invite 
 * Part of PBX interface */
static int sip_answer(struct ast_channel *ast)
{
	int res = 0;
	struct sip_pvt *p = ast->tech_pvt;

	sip_pvt_lock(p);
	if (ast->_state != AST_STATE_UP) {
		try_suggested_sip_codec(p);	

		ast_setstate(ast, AST_STATE_UP);
		ast_debug(1, "SIP answering channel: %s\n", ast->name);
		ast_rtp_new_source(p->rtp);
		ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
		res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL, FALSE);
	}
	sip_pvt_unlock(p);
	return res;
}

/*! \brief Send frame to media channel (rtp) */
static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
{
	struct sip_pvt *p = ast->tech_pvt;
	int res = 0;

	switch (frame->frametype) {
	case AST_FRAME_VOICE:
		if (!(frame->subclass & ast->nativeformats)) {
			char s1[512], s2[512], s3[512];
			ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %s(%d) read/write = %s(%d)/%s(%d)\n",
				frame->subclass, 
				ast_getformatname_multiple(s1, sizeof(s1) - 1, ast->nativeformats & AST_FORMAT_AUDIO_MASK),
				ast->nativeformats & AST_FORMAT_AUDIO_MASK,
				ast_getformatname_multiple(s2, sizeof(s2) - 1, ast->readformat),
				ast->readformat,
				ast_getformatname_multiple(s3, sizeof(s3) - 1, ast->writeformat),
				ast->writeformat);
			return 0;
		}
		if (p) {
			sip_pvt_lock(p);
			if (p->rtp) {
				/* If channel is not up, activate early media session */
				if ((ast->_state != AST_STATE_UP) &&
				    !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
				    !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
					ast_rtp_new_source(p->rtp);
					if (!global_prematuremediafilter) {
						p->invitestate = INV_EARLY_MEDIA;
						transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
						ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
					}
				} else if (p->t38.state == T38_ENABLED) {
					/* drop frame, can't sent VOICE frames while in T.38 mode */
				} else {
					p->lastrtptx = time(NULL);
					res = ast_rtp_write(p->rtp, frame);
				}
			}
			sip_pvt_unlock(p);
		}
		break;
	case AST_FRAME_VIDEO:
		if (p) {
			sip_pvt_lock(p);
			if (p->vrtp) {
				/* Activate video early media */
				if ((ast->_state != AST_STATE_UP) &&
				    !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
				    !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
					p->invitestate = INV_EARLY_MEDIA;
					transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
					ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);	
				}
				p->lastrtptx = time(NULL);
				res = ast_rtp_write(p->vrtp, frame);
			}
			sip_pvt_unlock(p);
		}
		break;
	case AST_FRAME_TEXT:
		if (p) {
			sip_pvt_lock(p);
			if (p->trtp) {
				/* Activate text early media */
				if ((ast->_state != AST_STATE_UP) &&
				    !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
				    !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
					p->invitestate = INV_EARLY_MEDIA;
					transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
					ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);	
				}
				p->lastrtptx = time(NULL);
				res = ast_rtp_write(p->trtp, frame);
			}
			sip_pvt_unlock(p);
		}
		break;
	case AST_FRAME_IMAGE:
		return 0;
		break;
	case AST_FRAME_MODEM:
		if (p) {
			sip_pvt_lock(p);
			/* UDPTL requires two-way communication, so early media is not needed here.
				we simply forget the frames if we get modem frames before the bridge is up.
				Fax will re-transmit.
			*/
			if ((ast->_state == AST_STATE_UP) &&
			    p->udptl &&
			    (p->t38.state == T38_ENABLED)) {
				res = ast_udptl_write(p->udptl, frame);
			}
			sip_pvt_unlock(p);
		}
		break;
	default: 
		ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
		return 0;
	}

	return res;
}

/*! \brief  sip_fixup: Fix up a channel:  If a channel is consumed, this is called.
        Basically update any ->owner links */
static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
{
	int ret = -1;
	struct sip_pvt *p;

	if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE))
		ast_debug(1, "New channel is zombie\n");
	if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE))
		ast_debug(1, "Old channel is zombie\n");

	if (!newchan || !newchan->tech_pvt) {
		if (!newchan)
			ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name);
		else
			ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
		return -1;
	}
	p = newchan->tech_pvt;

	sip_pvt_lock(p);
	append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
	append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name);
	if (p->owner != oldchan)
		ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
	else {
		p->owner = newchan;
		/* Re-invite RTP back to Asterisk. Needed if channel is masqueraded out of a native
		   RTP bridge (i.e., RTP not going through Asterisk): RTP bridge code might not be
		   able to do this if the masquerade happens before the bridge breaks (e.g., AMI
		   redirect of both channels). Note that a channel can not be masqueraded *into*
		   a native bridge. So there is no danger that this breaks a native bridge that
		   should stay up. */
		sip_set_rtp_peer(newchan, NULL, NULL, 0, 0, 0);
		ret = 0;
	}
	ast_debug(3, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name);

	sip_pvt_unlock(p);
	return ret;
}

static int sip_senddigit_begin(struct ast_channel *ast, char digit)
{
	struct sip_pvt *p = ast->tech_pvt;
	int res = 0;

	sip_pvt_lock(p);
	switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
	case SIP_DTMF_INBAND:
		res = -1; /* Tell Asterisk to generate inband indications */
		break;
	case SIP_DTMF_RFC2833:
		if (p->rtp)
			ast_rtp_senddigit_begin(p->rtp, digit);
		break;
	default:
		break;
	}
	sip_pvt_unlock(p);

	return res;
}

/*! \brief Send DTMF character on SIP channel
	within one call, we're able to transmit in many methods simultaneously */
static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
{
	struct sip_pvt *p = ast->tech_pvt;
	int res = 0;

	sip_pvt_lock(p);
	switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
	case SIP_DTMF_INFO:
	case SIP_DTMF_SHORTINFO:
		transmit_info_with_digit(p, digit, duration);
		break;
	case SIP_DTMF_RFC2833:
		if (p->rtp)
			ast_rtp_senddigit_end(p->rtp, digit);
		break;
	case SIP_DTMF_INBAND:
		res = -1; /* Tell Asterisk to stop inband indications */
		break;
	}
	sip_pvt_unlock(p);

	return res;
}

/*! \brief Transfer SIP call */
static int sip_transfer(struct ast_channel *ast, const char *dest)
{
	struct sip_pvt *p = ast->tech_pvt;
	int res;

	if (dest == NULL)	/* functions below do not take a NULL */
		dest = "";
	sip_pvt_lock(p);
	if (ast->_state == AST_STATE_RING)
		res = sip_sipredirect(p, dest);
	else
		res = transmit_refer(p, dest);
	sip_pvt_unlock(p);
	return res;
}

/*! \brief Helper function which updates T.38 capability information and triggers a reinvite */
static void interpret_t38_parameters(struct sip_pvt *p, const struct ast_control_t38_parameters *parameters)
{
	if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
		return;
	}

	switch (parameters->request_response) {
	case AST_T38_NEGOTIATED:
	case AST_T38_REQUEST_NEGOTIATE:         /* Request T38 */
		/* Negotiation can not take place without a valid max_ifp value. */
		if (!parameters->max_ifp) {
				change_t38_state(p, T38_DISABLED);
				if (p->t38.state == T38_PEER_REINVITE) {
					AST_SCHED_DEL(sched, p->t38id);
					transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
				}
				break;
		} else if (p->t38.state == T38_PEER_REINVITE) {
			AST_SCHED_DEL(sched, p->t38id);
			p->t38.our_parms = *parameters;
			/* modify our parameters to conform to the peer's parameters,
			 * based on the rules in the ITU T.38 recommendation
			 */
			if (!p->t38.their_parms.fill_bit_removal) {
				p->t38.our_parms.fill_bit_removal = FALSE;
			}
			if (!p->t38.their_parms.transcoding_mmr) {
				p->t38.our_parms.transcoding_mmr = FALSE;
			}
			if (!p->t38.their_parms.transcoding_jbig) {
				p->t38.our_parms.transcoding_jbig = FALSE;
			}
			p->t38.our_parms.version = MIN(p->t38.our_parms.version, p->t38.their_parms.version);
			p->t38.our_parms.rate_management = p->t38.their_parms.rate_management;
			ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
			change_t38_state(p, T38_ENABLED);
			transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
		} else if (p->t38.state != T38_ENABLED) {
			p->t38.our_parms = *parameters;
			ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
			change_t38_state(p, T38_LOCAL_REINVITE);
			if (!p->pendinginvite) {
				transmit_reinvite_with_sdp(p, TRUE, FALSE);
			} else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
				ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
			}
		}
		break;
	case AST_T38_TERMINATED:
	case AST_T38_REFUSED:
	case AST_T38_REQUEST_TERMINATE:         /* Shutdown T38 */
		if (p->t38.state == T38_PEER_REINVITE) {
			AST_SCHED_DEL(sched, p->t38id);
			change_t38_state(p, T38_DISABLED);
			transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
		} else if (p->t38.state == T38_ENABLED)
			transmit_reinvite_with_sdp(p, FALSE, FALSE);
		break;
	default:
		break;
	}
}

/*! \brief Play indication to user 
 * With SIP a lot of indications is sent as messages, letting the device play
   the indication - busy signal, congestion etc 
   \return -1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message
*/
static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
{
	struct sip_pvt *p = ast->tech_pvt;
	int res = 0;

	sip_pvt_lock(p);
	switch(condition) {
	case AST_CONTROL_RINGING:
		if (ast->_state == AST_STATE_RING) {
			p->invitestate = INV_EARLY_MEDIA;
			if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
			    (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {				
				/* Send 180 ringing if out-of-band seems reasonable */
				transmit_provisional_response(p, "180 Ringing", &p->initreq, 0);
				ast_set_flag(&p->flags[0], SIP_RINGING);
				if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
					break;
			} else {
				/* Well, if it's not reasonable, just send in-band */
			}
		}
		res = -1;
		break;
	case AST_CONTROL_BUSY:
		if (ast->_state != AST_STATE_UP) {
			transmit_response_reliable(p, "486 Busy Here", &p->initreq);
			p->invitestate = INV_COMPLETED;
			sip_alreadygone(p);
			ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
			break;
		}
		res = -1;
		break;
	case AST_CONTROL_CONGESTION:
		if (ast->_state != AST_STATE_UP) {
			transmit_response_reliable(p, "503 Service Unavailable", &p->initreq);
			p->invitestate = INV_COMPLETED;
			sip_alreadygone(p);
			ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
			break;
		}
		res = -1;
		break;
	case AST_CONTROL_PROCEEDING:
		if ((ast->_state != AST_STATE_UP) &&
		    !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
		    !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
			transmit_response(p, "100 Trying", &p->initreq);
			p->invitestate = INV_PROCEEDING;  
			break;
		}
		res = -1;
		break;
	case AST_CONTROL_PROGRESS:
		if ((ast->_state != AST_STATE_UP) &&
		    !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
		    !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
			p->invitestate = INV_EARLY_MEDIA;
			transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
			ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);	
			break;
		}
		res = -1;
		break;
	case AST_CONTROL_HOLD:
		ast_rtp_new_source(p->rtp);
		ast_moh_start(ast, data, p->mohinterpret);
		break;
	case AST_CONTROL_UNHOLD:
		ast_rtp_new_source(p->rtp);
		ast_moh_stop(ast);
		break;
	case AST_CONTROL_VIDUPDATE:	/* Request a video frame update */
		if (p->vrtp && !p->novideo) {
			transmit_info_with_vidupdate(p);
			/* ast_rtcp_send_h261fur(p->vrtp); */
		} else
			res = -1;
		break;
	case AST_CONTROL_T38_PARAMETERS:
		if (datalen != sizeof(struct ast_control_t38_parameters)) {
			ast_log(LOG_ERROR, "Invalid datalen for AST_CONTROL_T38_PARAMETERS. Expected %d, got %d\n", (int) sizeof(struct ast_control_t38_parameters), (int) datalen);
		} else {
			const struct ast_control_t38_parameters *parameters = data;
			interpret_t38_parameters(p, parameters);
		}
		break;
	case AST_CONTROL_SRCUPDATE:
		ast_rtp_new_source(p->rtp);
		break;
	case AST_CONTROL_SRCCHANGE:
		ast_rtp_change_source(p->rtp);
		break;
	case -1:
		res = -1;
		break;
	default:
		ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
		res = -1;
		break;
	}
	sip_pvt_unlock(p);
	return res;
}


/*! \brief Initiate a call in the SIP channel
	called from sip_request_call (calls from the pbx ) for outbound channels
	and from handle_request_invite for inbound channels
	
*/
static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title)
{
	struct ast_channel *tmp;
	struct ast_variable *v = NULL;
	int fmt;
	int what;
	int video;
	int text;
	int needvideo = 0;
	int needtext = 0;
	char buf[SIPBUFSIZE];
	char *decoded_exten;

	{
		const char *my_name;	/* pick a good name */
	
		if (title)
			my_name = title;
		else if ( (my_name = strchr(i->fromdomain, ':')) )
			my_name++;	/* skip ':' */
		else
			my_name = i->fromdomain;

		sip_pvt_unlock(i);
		/* Don't hold a sip pvt lock while we allocate a channel */
		tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, i->accountcode, i->exten, i->context, i->amaflags, "SIP/%s-%08x", my_name, ast_atomic_fetchadd_int((int *)&chan_idx, +1));

	}
	if (!tmp) {
		ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
		sip_pvt_lock(i);
		return NULL;
	}
	sip_pvt_lock(i);

	tmp->tech = ( ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INFO || ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO) ?  &sip_tech_info : &sip_tech;

	/* Select our native format based on codec preference until we receive
	   something from another device to the contrary. */
	if (i->jointcapability) { 	/* The joint capabilities of us and peer */
		what = i->jointcapability;
		video = i->jointcapability & AST_FORMAT_VIDEO_MASK;
		text = i->jointcapability & AST_FORMAT_TEXT_MASK;
	} else if (i->capability) {		/* Our configured capability for this peer */
		what = i->capability;
		video = i->capability & AST_FORMAT_VIDEO_MASK;
		text = i->capability & AST_FORMAT_TEXT_MASK;
	} else {
		what = global_capability;	/* Global codec support */
		video = global_capability & AST_FORMAT_VIDEO_MASK;
		text = global_capability & AST_FORMAT_TEXT_MASK;
	}

	/* Set the native formats for audio  and merge in video */
	tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | video | text;
	ast_debug(3, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmp->nativeformats));
	ast_debug(3, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->jointcapability));
	ast_debug(3, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->capability));
	ast_debug(3, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, ast_codec_choose(&i->prefs, what, 1)));
	if (i->prefcodec)
		ast_debug(3, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->prefcodec));

	/* XXX Why are we choosing a codec from the native formats?? */
	fmt = ast_best_codec(tmp->nativeformats);

	/* If we have a prefcodec setting, we have an inbound channel that set a 
	   preferred format for this call. Otherwise, we check the jointcapability
	   We also check for vrtp. If it's not there, we are not allowed do any video anyway.
	 */
	if (i->vrtp) {
		if (i->prefcodec)
			needvideo = i->prefcodec & AST_FORMAT_VIDEO_MASK;	/* Outbound call */
 		else
			needvideo = i->jointcapability & AST_FORMAT_VIDEO_MASK;	/* Inbound call */
	}

	if (i->trtp) {
		if (i->prefcodec)
			needtext = i->prefcodec & AST_FORMAT_TEXT_MASK;	/* Outbound call */
 		else
			needtext = i->jointcapability & AST_FORMAT_TEXT_MASK;	/* Inbound call */
	}

	if (needvideo) 
		ast_debug(3, "This channel can handle video! HOLLYWOOD next!\n");
	else
		ast_debug(3, "This channel will not be able to handle video.\n");

	if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) || (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) ||
	    (ast_test_flag(&i->flags[1], SIP_PAGE2_FAX_DETECT))) {
		int features = DSP_FEATURE_DTMF_DETECT;

		if (ast_test_flag(&i->flags[1], SIP_PAGE2_FAX_DETECT)) {
			features |= DSP_FEATURE_FAX_DETECT;
		}

		i->dsp = ast_dsp_new();
		ast_dsp_set_features(i->dsp, features);
                if (global_relaxdtmf)
			ast_dsp_digitmode(i->dsp, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
        }

	/* Set file descriptors for audio, video, realtime text and UDPTL as needed */
	if (i->rtp) {
		ast_channel_set_fd(tmp, 0, ast_rtp_fd(i->rtp));
		ast_channel_set_fd(tmp, 1, ast_rtcp_fd(i->rtp));
	}
	if (needvideo && i->vrtp) {
		ast_channel_set_fd(tmp, 2, ast_rtp_fd(i->vrtp));
		ast_channel_set_fd(tmp, 3, ast_rtcp_fd(i->vrtp));
	}
	if (needtext && i->trtp) 
		ast_channel_set_fd(tmp, 4, ast_rtp_fd(i->trtp));
	if (i->udptl)
		ast_channel_set_fd(tmp, 5, ast_udptl_fd(i->udptl));

	if (state == AST_STATE_RING)
		tmp->rings = 1;
	tmp->adsicpe = AST_ADSI_UNAVAILABLE;
	tmp->writeformat = fmt;
	tmp->rawwriteformat = fmt;
	tmp->readformat = fmt;
	tmp->rawreadformat = fmt;
	tmp->tech_pvt = i;

	tmp->callgroup = i->callgroup;
	tmp->pickupgroup = i->pickupgroup;
	tmp->cid.cid_pres = i->callingpres;
	if (!ast_strlen_zero(i->accountcode))
		ast_string_field_set(tmp, accountcode, i->accountcode);
	if (i->amaflags)
		tmp->amaflags = i->amaflags;
	if (!ast_strlen_zero(i->language))
		ast_string_field_set(tmp, language, i->language);
	i->owner = tmp;
	ast_module_ref(ast_module_info->self);
	ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
	/*Since it is valid to have extensions in the dialplan that have unescaped characters in them
	 * we should decode the uri before storing it in the channel, but leave it encoded in the sip_pvt
	 * structure so that there aren't issues when forming URI's
	 */
	decoded_exten = ast_strdupa(i->exten);
	ast_uri_decode(decoded_exten);
	ast_copy_string(tmp->exten, decoded_exten, sizeof(tmp->exten));

	/* Don't use ast_set_callerid() here because it will
	 * generate an unnecessary NewCallerID event  */
	tmp->cid.cid_ani = ast_strdup(i->cid_num);
	if (!ast_strlen_zero(i->rdnis))
		tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
	
	if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
		tmp->cid.cid_dnid = ast_strdup(i->exten);

	tmp->priority = 1;
	if (!ast_strlen_zero(i->uri))
		pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
	if (!ast_strlen_zero(i->domain))
		pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
	if (!ast_strlen_zero(i->callid))
		pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
	if (i->rtp)
		ast_jb_configure(tmp, &global_jbconf);

	/* Set channel variables for this call from configuration */
	for (v = i->chanvars ; v ; v = v->next)
		pbx_builtin_setvar_helper(tmp, v->name, v->value);

	if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
		ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
		tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
		ast_hangup(tmp);
		tmp = NULL;
	}

	if (i->do_history)
		append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);

	/* Inform manager user about new channel and their SIP call ID */
	if (global_callevents)
		manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
			"Channel: %s\r\nUniqueid: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\n",
			tmp->name, tmp->uniqueid, "SIP", i->callid, i->fullcontact);

	return tmp;
}

/*! \brief Reads one line of SIP message body */
static char *get_body_by_line(const char *line, const char *name, int nameLen)
{
	if (!strncasecmp(line, name, nameLen) && line[nameLen] == '=')
		return ast_skip_blanks(line + nameLen + 1);

	return "";
}

/*! \brief Lookup 'name' in the SDP starting
 * at the 'start' line. Returns the matching line, and 'start'
 * is updated with the next line number.
 */
static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
{
	int len = strlen(name);

	while (*start < (req->sdp_start + req->sdp_count)) {
		const char *r = get_body_by_line(req->line[(*start)++], name, len);
		if (r[0] != '\0')
			return r;
	}

	/* if the line was not found, ensure that *start points past the SDP */
	(*start)++;

	return "";
}

/*! \brief Fetches the next valid SDP line between the 'start' line
 * (inclusive) and the 'stop' line (exclusive). Returns the type
 * ('a', 'c', ...) and matching line in reference 'start' is updated
 * with the next line number.
 */
static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value)
{
	char type = '\0';
	const char *line = NULL;

	if (stop > (req->sdp_start + req->sdp_count)) {
		stop = req->sdp_start + req->sdp_count;
	}

	while (*start < stop) {
		line = req->line[(*start)++];
		if (line[1] == '=') {
			type = line[0];
			*value = ast_skip_blanks(line + 2);
			break;
		}
	}

	return type;
}

/*! \brief Get a specific line from the message body */
static char *get_body(struct sip_request *req, char *name) 
{
	int x;
	int len = strlen(name);
	char *r;

	for (x = 0; x < req->lines; x++) {
		r = get_body_by_line(req->line[x], name, len);
		if (r[0] != '\0')
			return r;
	}

	return "";
}

/*! \brief Find compressed SIP alias */
static const char *find_alias(const char *name, const char *_default)
{
	/*! \brief Structure for conversion between compressed SIP and "normal" SIP */
	static const struct cfalias {
		char * const fullname;
		char * const shortname;
	} aliases[] = {
		{ "Content-Type",	 "c" },
		{ "Content-Encoding",	 "e" },
		{ "From",		 "f" },
		{ "Call-ID",		 "i" },
		{ "Contact",		 "m" },
		{ "Content-Length",	 "l" },
		{ "Subject",		 "s" },
		{ "To",			 "t" },
		{ "Supported",		 "k" },
		{ "Refer-To",		 "r" },
		{ "Referred-By",	 "b" },
		{ "Allow-Events",	 "u" },
		{ "Event",		 "o" },
		{ "Via",		 "v" },
		{ "Accept-Contact",      "a" },
		{ "Reject-Contact",      "j" },
		{ "Request-Disposition", "d" },
		{ "Session-Expires",     "x" },
		{ "Identity",            "y" },
		{ "Identity-Info",       "n" },
	};
	int x;

	for (x = 0; x < ARRAY_LEN(aliases); x++) {
		if (!strcasecmp(aliases[x].fullname, name))
			return aliases[x].shortname;
	}

	return _default;
}

static const char *__get_header(const struct sip_request *req, const char *name, int *start)
{
	int pass;

	/*
	 * Technically you can place arbitrary whitespace both before and after the ':' in
	 * a header, although RFC3261 clearly says you shouldn't before, and place just
	 * one afterwards.  If you shouldn't do it, what absolute idiot decided it was 
	 * a good idea to say you can do it, and if you can do it, why in the hell would.
	 * you say you shouldn't.
	 * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
	 * and we always allow spaces after that for compatibility.
	 */
	for (pass = 0; name && pass < 2;pass++) {
		int x, len = strlen(name);
		for (x=*start; x<req->headers; x++) {
			if (!strncasecmp(req->header[x], name, len)) {
				char *r = req->header[x] + len;	/* skip name */
				if (pedanticsipchecking)
					r = ast_skip_blanks(r);

				if (*r == ':') {
					*start = x+1;
					return ast_skip_blanks(r+1);
				}
			}
		}
		if (pass == 0) /* Try aliases */
			name = find_alias(name, NULL);
	}

	/* Don't return NULL, so get_header is always a valid pointer */
	return "";
}

/*! \brief Get header from SIP request 
	\return Always return something, so don't check for NULL because it won't happen :-)
*/
static const char *get_header(const struct sip_request *req, const char *name)
{
	int start = 0;
	return __get_header(req, name, &start);
}

/*! \brief Read RTP from network */
static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
{
	/* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
	struct ast_frame *f;
	
	if (!p->rtp) {
		/* We have no RTP allocated for this channel */
		return &ast_null_frame;
	}

	switch(ast->fdno) {
	case 0:
		f = ast_rtp_read(p->rtp);	/* RTP Audio */
		break;
	case 1:
		f = ast_rtcp_read(p->rtp);	/* RTCP Control Channel */
		break;
	case 2:
		f = ast_rtp_read(p->vrtp);	/* RTP Video */
		break;
	case 3:
		f = ast_rtcp_read(p->vrtp);	/* RTCP Control Channel for video */
		break;
	case 4:
		f = ast_rtp_read(p->trtp);	/* RTP Text */
		if (sipdebug_text) {
			int i;
			unsigned char* arr = f->data;
			for (i=0; i < f->datalen; i++)
				ast_verbose("%c", (arr[i] > ' ' && arr[i] < '}') ? arr[i] : '.');
			ast_verbose(" -> ");
			for (i=0; i < f->datalen; i++)
				ast_verbose("%02X ", arr[i]);
			ast_verbose("\n");
		}
		break;
	case 5:
		f = ast_udptl_read(p->udptl);	/* UDPTL for T.38 */
		break;
	default:
		f = &ast_null_frame;
	}
	/* Don't forward RFC2833 if we're not supposed to */
	if (f && (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) &&
	    (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833)) {
		ast_debug(1, "Ignoring DTMF (%c) RTP frame because dtmfmode is not RFC2833\n", f->subclass);
		return &ast_null_frame;
	}

	/* We already hold the channel lock */
	if (!p->owner || (f && f->frametype != AST_FRAME_VOICE))
		return f;

	if (f && f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
		if (!(f->subclass & p->jointcapability)) {
			ast_debug(1, "Bogus frame of format '%s' received from '%s'!\n",
				ast_getformatname(f->subclass), p->owner->name);
			return &ast_null_frame;
		}
		ast_debug(1, "Oooh, format changed to %d %s\n",
			f->subclass, ast_getformatname(f->subclass));
		p->owner->nativeformats = (p->owner->nativeformats & (AST_FORMAT_VIDEO_MASK | AST_FORMAT_TEXT_MASK)) | f->subclass;
		ast_set_read_format(p->owner, p->owner->readformat);
		ast_set_write_format(p->owner, p->owner->writeformat);
	}

	if (f && ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) || ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT)) && p->dsp) {
		f = ast_dsp_process(p->owner, p->dsp, f);
                if (f && f->frametype == AST_FRAME_DTMF) {
			if (f->subclass == 'f') {
                                if (option_debug)
                                        ast_log(LOG_DEBUG, "Fax CNG detected on %s\n", ast->name);
                                *faxdetect = 1;
				/* If we only needed this DSP for fax detection purposes we can just drop it now */
				if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
					ast_dsp_set_features(p->dsp, DSP_FEATURE_DTMF_DETECT);
				} else {
					ast_dsp_free(p->dsp);
					p->dsp = NULL;
				}
			} else {
				ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass);
			}
		}
	}
	
	return f;
}

/*! \brief Read SIP RTP from channel */
static struct ast_frame *sip_read(struct ast_channel *ast)
{
	struct ast_frame *fr;
	struct sip_pvt *p = ast->tech_pvt;
	int faxdetected = FALSE;

	sip_pvt_lock(p);
	fr = sip_rtp_read(ast, p, &faxdetected);
	p->lastrtprx = time(NULL);

	/* If we detect a CNG tone and fax detection is enabled then send us off to the fax extension */
	if (faxdetected && ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT)) {
		ast_channel_lock(ast);
		if (strcmp(ast->exten, "fax")) {
			const char *target_context = S_OR(ast->macrocontext, ast->context);
			ast_channel_unlock(ast);
			if (ast_exists_extension(ast, target_context, "fax", 1, ast->cid.cid_num)) {
				ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension\n", ast->name);
				pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
				if (ast_async_goto(ast, target_context, "fax", 1)) {
					ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast->name, target_context);
				}
				fr = &ast_null_frame;
			} else {
				ast_log(LOG_NOTICE, "Fax detected but no fax extension\n");
                        }
		} else {
			ast_channel_unlock(ast);
                }
        }

	/* Only allow audio through if they sent progress with SDP, or if the channel is actually answered */
	if (fr && fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast->_state != AST_STATE_UP) {
		fr = &ast_null_frame;
	}

	sip_pvt_unlock(p);

	return fr;
}


/*! \brief Generate 32 byte random string for callid's etc */
static char *generate_random_string(char *buf, size_t size)
{
	long val[4];
	int x;

	for (x=0; x<4; x++)
		val[x] = ast_random();
	snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);

	return buf;
}

/*! \brief Build SIP Call-ID value for a non-REGISTER transaction */
static void build_callid_pvt(struct sip_pvt *pvt)
{
	char buf[33];

	const char *host = S_OR(pvt->fromdomain, ast_inet_ntoa(pvt->ourip.sin_addr));
	
	ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);

}

/*! \brief Build SIP Call-ID value for a REGISTER transaction */
static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain)
{
	char buf[33];

	const char *host = S_OR(fromdomain, ast_inet_ntoa(ourip));

	ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
}

/*! \brief Make our SIP dialog tag */
static void make_our_tag(char *tagbuf, size_t len)
{
	snprintf(tagbuf, len, "as%08lx", ast_random());
}

/*! \brief Allocate Session-Timers struct w/in dialog */
static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p)
{
	struct sip_st_dlg *stp;

	if (p->stimer) {
		ast_log(LOG_ERROR, "Session-Timer struct already allocated\n");
		return p->stimer;
	}

	if (!(stp = ast_calloc(1, sizeof(struct sip_st_dlg))))
		return NULL;

	p->stimer = stp;

	stp->st_schedid = -1;           /* Session-Timers ast_sched scheduler id */

	return p->stimer;
}

/*! \brief Allocate sip_pvt structure, set defaults and link in the container.
 * Returns a reference to the object so whoever uses it later must
 * remember to release the reference.
 */
static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
				 int useglobal_nat, const int intended_method, struct sip_request *req)
{
	struct sip_pvt *p;

	if (!(p = ao2_alloc(sizeof(*p), sip_destroy_fn)))
		return NULL;

	if (ast_string_field_init(p, 512)) {
		dialog_unref(p);
		return NULL;
	}

	ast_mutex_init(&p->pvt_lock);

	if (req) {
		set_socket_transport(&p->socket, req->socket.type); /* Later in ast_sip_ouraddrfor we need this to choose the right ip and port for the specific transport */
	} else {
		set_socket_transport(&p->socket, SIP_TRANSPORT_UDP);
	}

	p->socket.fd = -1;
	p->method = intended_method;
	p->initid = -1;
	p->waitid = -1;
	p->autokillid = -1;
	p->request_queue_sched_id = -1;
	p->provisional_keepalive_sched_id = -1;
	p->t38id = -1;
	p->subscribed = NONE;
	p->stateid = -1;
	p->sessionversion_remote = -1;
	p->session_modify = TRUE;
	p->stimer = NULL;
	p->prefs = default_prefs;		/* Set default codecs for this call */

	if (intended_method != SIP_OPTIONS) {	/* Peerpoke has it's own system */
		p->timer_t1 = global_t1;	/* Default SIP retransmission timer T1 (RFC 3261) */
		p->timer_b = global_timer_b;	/* Default SIP transaction timer B (RFC 3261) */
	}

	if (!sin)
		p->ourip = internip;
	else {
		p->sa = *sin;
		ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
	}

	/* Copy global flags to this PVT at setup. */
	ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
	ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);

	p->do_history = recordhistory;

	p->branch = ast_random();	
	make_our_tag(p->tag, sizeof(p->tag));
	p->ocseq = INITIAL_CSEQ;

	if (sip_methods[intended_method].need_rtp) {
		p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
		/* If the global videosupport flag is on, we always create a RTP interface for video */
		if (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT))
			p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
 		if (ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT))
 			p->trtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
		if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
			p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr);
			p->t38_maxdatagram = global_t38_maxdatagram;
		}
 		if (!p->rtp || (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) && !p->vrtp) 
				|| (ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) && !p->trtp)) {
 			ast_log(LOG_WARNING, "Unable to create RTP audio %s%ssession: %s\n",
 				ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "and video " : "",
 				ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "and text " : "", strerror(errno));
			dialog_unref(p);
			return NULL;
		}
		ast_rtp_setqos(p->rtp, global_tos_audio, global_cos_audio, "SIP RTP");
		ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
		ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
		ast_rtp_set_rtptimeout(p->rtp, global_rtptimeout);
		ast_rtp_set_rtpholdtimeout(p->rtp, global_rtpholdtimeout);
		ast_rtp_set_rtpkeepalive(p->rtp, global_rtpkeepalive);
		if (p->vrtp) {
			ast_rtp_setqos(p->vrtp, global_tos_video, global_cos_video, "SIP VRTP");
			ast_rtp_setdtmf(p->vrtp, 0);
			ast_rtp_setdtmfcompensate(p->vrtp, 0);
			ast_rtp_set_rtptimeout(p->vrtp, global_rtptimeout);
			ast_rtp_set_rtpholdtimeout(p->vrtp, global_rtpholdtimeout);
			ast_rtp_set_rtpkeepalive(p->vrtp, global_rtpkeepalive);
		}
		if (p->trtp) {
			ast_rtp_setqos(p->trtp, global_tos_text, global_cos_text, "SIP TRTP");
			ast_rtp_setdtmf(p->trtp, 0);
			ast_rtp_setdtmfcompensate(p->trtp, 0);
		}
		if (p->udptl)
			ast_udptl_setqos(p->udptl, global_tos_audio, global_cos_audio);
		p->maxcallbitrate = default_maxcallbitrate;
		p->autoframing = global_autoframing;
		ast_rtp_codec_setpref(p->rtp, &p->prefs);
	}

	if (useglobal_nat && sin) {
		/* Setup NAT structure according to global settings if we have an address */
		ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
		p->recv = *sin;
		do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
	}

	if (p->method != SIP_REGISTER)
		ast_string_field_set(p, fromdomain, default_fromdomain);
	build_via(p);
	if (!callid)
		build_callid_pvt(p);
	else
		ast_string_field_set(p, callid, callid);
	/* Assign default music on hold class */
	ast_string_field_set(p, mohinterpret, default_mohinterpret);
	ast_string_field_set(p, mohsuggest, default_mohsuggest);
	p->capability = global_capability;
	p->allowtransfer = global_allowtransfer;
	if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
	    (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
		p->noncodeccapability |= AST_RTP_DTMF;
	if (p->udptl) {
		set_t38_capabilities(p);
	}
	ast_string_field_set(p, context, default_context);

	AST_LIST_HEAD_INIT_NOLOCK(&p->request_queue);

	/* Add to active dialog list */
	dialoglist_lock();
	p->next = dialoglist;
	dialoglist = p;
	dialoglist_unlock();
	ast_debug(1, "Allocating new SIP dialog for %s - %s (%s)\n", callid ? callid : "(No Call-ID)", sip_methods[intended_method].text, p->rtp ? "With RTP" : "No RTP");
	return p;
}

/*! \brief find or create a dialog structure for an incoming SIP message.
 * Connect incoming SIP message to current dialog or create new dialog structure
 * Returns a reference to the sip_pvt object, remember to give it back once done.
 *     Called by handle_incoming(), sipsock_read
 */
static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method)
{
	struct sip_pvt *p = NULL;
	char *tag = "";	/* note, tag is never NULL */
	char totag[128];
	char fromtag[128];
	const char *callid = get_header(req, "Call-ID");
	const char *from = get_header(req, "From");
	const char *to = get_header(req, "To");
	const char *cseq = get_header(req, "Cseq");

	/* Call-ID, to, from and Cseq are required by RFC 3261. (Max-forwards and via too - ignored now) */
	/* get_header always returns non-NULL so we must use ast_strlen_zero() */
	if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
			ast_strlen_zero(from) || ast_strlen_zero(cseq))
		return NULL;	/* Invalid packet */

	if (pedanticsipchecking) {
		/* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
		   we need more to identify a branch - so we have to check branch, from
		   and to tags to identify a call leg.
		   For Asterisk to behave correctly, you need to turn on pedanticsipchecking
		   in sip.conf
		   */
		if (gettag(req, "To", totag, sizeof(totag)))
			req->has_to_tag = 1;	/* Used in handle_request/response */
		gettag(req, "From", fromtag, sizeof(fromtag));

		tag = (req->method == SIP_RESPONSE) ? totag : fromtag;

		ast_debug(5, "= Looking for  Call ID: %s (Checking %s) --From tag %s --To-tag %s  \n", callid, req->method==SIP_RESPONSE ? "To" : "From", fromtag, totag);

		/* All messages must always have From: tag */
		if (ast_strlen_zero(fromtag)) {
			ast_debug(5, "%s request has no from tag, dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
			return NULL;
		}
		/* reject requests that must always have a To: tag */
		if (ast_strlen_zero(totag) && (req->method == SIP_ACK || req->method == SIP_BYE || req->method == SIP_INFO )) {
			ast_debug(5, "%s must have a to tag. dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
			return NULL;
		}
	}

	dialoglist_lock();
restartsearch:
	for (p = dialoglist; p; p = p->next) {
		/* In pedantic, we do not want packets with bad syntax to be connected to a PVT */
		int found = FALSE;
		if (ast_strlen_zero(p->callid))
			continue;
		if (req->method == SIP_REGISTER)
			found = (!strcmp(p->callid, callid));
		else 
			found = (!strcmp(p->callid, callid) && 
			(!pedanticsipchecking || ast_strlen_zero(tag) || ast_strlen_zero(p->theirtag) || !ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED) || !strcmp(p->theirtag, tag))) ;

		ast_debug(5, "= %s Their Call ID: %s Their Tag %s Our tag: %s\n", found ? "Found" : "No match", p->callid, p->theirtag, p->tag);

		/* If we get a new request within an existing to-tag - check the to tag as well */
		if (pedanticsipchecking && found  && req->method != SIP_RESPONSE) {	/* SIP Request */
			if (p->tag[0] == '\0' && totag[0]) {
				/* We have no to tag, but they have. Wrong dialog */
				found = FALSE;
			} else if (totag[0]) {			/* Both have tags, compare them */
				if (strcmp(totag, p->tag)) {
					found = FALSE;		/* This is not our packet */
				}
			}
			if (!found)
				ast_debug(5, "= Being pedantic: This is not our match on request: Call ID: %s Ourtag <null> Totag %s Method %s\n", p->callid, totag, sip_methods[req->method].text);
		}


		if (found) {
			/* Found the call */
			if (sip_pvt_trylock(p)) {
				dialoglist_unlock();
				usleep(1);
				dialoglist_lock();
				goto restartsearch;
			}
			dialoglist_unlock();
			return p;
		}
	}
	dialoglist_unlock();
	
	/* See if the method is capable of creating a dialog */
	if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
		if (intended_method == SIP_REFER) {
			/* We do support REFER, but not outside of a dialog yet */
			transmit_response_using_temp(callid, sin, 1, intended_method, req, "603 Declined (no dialog)");
		} else if (intended_method == SIP_NOTIFY) {
			/* We do not support out-of-dialog NOTIFY either,
		   	like voicemail notification, so cancel that early */
			transmit_response_using_temp(callid, sin, 1, intended_method, req, "489 Bad event");
		} else {
			/* Ok, time to create a new SIP dialog object, a pvt */
			if ((p = sip_alloc(callid, sin, 1, intended_method, req)))  {
				/* Ok, we've created a dialog, let's go and process it */
				sip_pvt_lock(p);
			} else {
				/* We have a memory or file/socket error (can't allocate RTP sockets or something) so we're not
					getting a dialog from sip_alloc. 
	
					Without a dialog we can't retransmit and handle ACKs and all that, but at least
					send an error message.
	
					Sorry, we apologize for the inconvienience
				*/
				transmit_response_using_temp(callid, sin, 1, intended_method, req, "500 Server internal error");
				ast_debug(4, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
			}
		}
		return p; /* can be NULL */
	} else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
		/* A method we do not support, let's take it on the volley */
		transmit_response_using_temp(callid, sin, 1, intended_method, req, "501 Method Not Implemented");
		ast_debug(2, "Got a request with unsupported SIP method.\n");
	} else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
		/* This is a request outside of a dialog that we don't know about */
		transmit_response_using_temp(callid, sin, 1, intended_method, req, "481 Call leg/transaction does not exist");
		ast_debug(2, "That's odd...  Got a request in unknown dialog. Callid %s\n", callid ? callid : "<unknown>");
	}
	/* We do not respond to responses for dialogs that we don't know about, we just drop
	   the session quickly */
	if (intended_method == SIP_RESPONSE)
		ast_debug(2, "That's odd...  Got a response on a call we dont know about. Callid %s\n", callid ? callid : "<unknown>");

	return p;
}

/*! \brief Parse register=> line in sip.conf and add to registry */
static int sip_register(const char *value, int lineno)
{
	struct sip_registry *reg;
	int portnum = 0;
	enum sip_transport transport = SIP_TRANSPORT_UDP;
	char buf[256] = "";
	char *userpart = NULL, *hostpart = NULL;
	/* register => [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry] */
	AST_DECLARE_APP_ARGS(pre1,
		AST_APP_ARG(peer);
		AST_APP_ARG(userpart);
	);
	AST_DECLARE_APP_ARGS(pre2,
		AST_APP_ARG(transport);
		AST_APP_ARG(blank);
		AST_APP_ARG(userpart);
	);
	AST_DECLARE_APP_ARGS(user1,
		AST_APP_ARG(userpart);
		AST_APP_ARG(secret);
		AST_APP_ARG(authuser);
	);
	AST_DECLARE_APP_ARGS(user2,
		AST_APP_ARG(userpart);
		AST_APP_ARG(domain);
	);
	AST_DECLARE_APP_ARGS(host1,
		AST_APP_ARG(hostpart);
		AST_APP_ARG(expiry);
	);
	AST_DECLARE_APP_ARGS(host2,
		AST_APP_ARG(hostpart);
		AST_APP_ARG(extension);
	);
	AST_DECLARE_APP_ARGS(host3,
		AST_APP_ARG(host);
		AST_APP_ARG(port);
	);

	if (!value)
		return -1;

	ast_copy_string(buf, value, sizeof(buf));

	/*! register => [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry]
	 * becomes
	 *   userpart => [peer?][transport://]user[@domain][:secret[:authuser]]
	 *   hostpart => host[:port][/extension][~expiry]
	 */
	if ((hostpart = strrchr(buf, '@'))) {
		*hostpart++ = '\0';
		userpart = buf;
	}

	if (ast_strlen_zero(userpart) || ast_strlen_zero(hostpart)) {
		ast_log(LOG_WARNING, "Format for registration is [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry] at line %d\n", lineno);
		return -1;
	}

	/*!
	 * pre1.peer => peer
	 * pre1.userpart => [transport://]user[@domain][:secret[:authuser]]
	 * hostpart => host[:port][/extension][~expiry]
	 */
	AST_NONSTANDARD_RAW_ARGS(pre1, userpart, '?');
	if (ast_strlen_zero(pre1.userpart)) {
		pre1.userpart = pre1.peer;
		pre1.peer = NULL;
	}

	/*!
	 * pre1.peer => peer
	 * pre2.transport = transport
	 * pre2.userpart => user[@domain][:secret[:authuser]]
	 * hostpart => host[:port][/extension][~expiry]
	 */
	AST_NONSTANDARD_RAW_ARGS(pre2, userpart, '/');
	if (ast_strlen_zero(pre2.userpart)) {
		pre2.userpart = pre2.transport;
		pre2.transport = NULL;
	} else {
		pre2.transport[strlen(pre2.transport) - 1] = '\0'; /* Remove trailing : */
	}

	if (!ast_strlen_zero(pre2.blank)) {
		ast_log(LOG_WARNING, "Format for registration is [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry] at line %d\n", lineno);
		return -1;
	}

	/*!
	 * pre1.peer => peer
	 * pre2.transport = transport
	 * user1.userpart => user[@domain]
	 * user1.secret => secret
	 * user1.authuser => authuser
	 * hostpart => host[:port][/extension][~expiry]
	 */
	AST_NONSTANDARD_RAW_ARGS(user1, pre2.userpart, ':');

	/*!
	 * pre1.peer => peer
	 * pre2.transport = transport
	 * user1.userpart => user[@domain]
	 * user1.secret => secret
	 * user1.authuser => authuser
	 * host1.hostpart => host[:port][/extension]
	 * host1.expiry => [expiry]
	 */
	AST_NONSTANDARD_RAW_ARGS(host1, hostpart, '~');

	/*!
	 * pre1.peer => peer
	 * pre2.transport = transport
	 * user1.userpart => user[@domain]
	 * user1.secret => secret
	 * user1.authuser => authuser
	 * host2.hostpart => host[:port]
	 * host2.extension => [extension]
	 */
	AST_NONSTANDARD_RAW_ARGS(host2, host1.hostpart, '/');

	/*!
	 * pre1.peer => peer
	 * pre2.transport = transport
	 * user1.userpart => user[@domain]
	 * user1.secret => secret
	 * user1.authuser => authuser
	 * host3.host => host
	 * host3.port => port
	 * host2.extension => extension
	 * host1.expiry => expiry
	 */
	AST_NONSTANDARD_RAW_ARGS(host3, host2.hostpart, ':');

	/*!
	 * pre1.peer => peer
	 * pre2.transport = transport
	 * user2.userpart => user
	 * user2.domain => domain (regdomain)
	 * user1.secret => secret
	 * user1.authuser => authuser
	 * host3.host => host
	 * host3.port => port
	 * host2.extension => extension (callback)
	 * host1.expiry => expiry
	 */
	AST_NONSTANDARD_RAW_ARGS(user2, user1.userpart, '@');

	/*!
	 * pre1.peer => peer
	 * transport = transport
	 * user2.userpart => user
	 * user2.domain => domain (regdomain)
	 * user1.secret => secret
	 * user1.authuser => authuser
	 * host3.host => host
	 * portnum => port
	 * host2.extension => extension (callback)
	 * host1.expiry => expiry
	 */
	if (host3.port) {
		if (sscanf(host3.port, "%5u", &portnum) != 1 || portnum > 65535) {
			ast_log(LOG_NOTICE, "'%s' is not a valid port number on line %d of sip.conf. using default.\n", host3.port, lineno);
			portnum = -1;
		}
	}

	/*!
	 * pre1.peer => peer
	 * transport = transport
	 * user2.userpart => user
	 * user2.domain => domain (regdomain)
	 * user1.secret => secret
	 * user1.authuser => authuser
	 * host3.host => host
	 * portnum => port
	 * host2.extension => extension (callback)
	 * host1.expiry => expiry
	 */
	if (!pre2.transport) {
		transport = SIP_TRANSPORT_UDP;
	} else if (!strncasecmp(pre2.transport, "tcp", 3)) {
		transport = SIP_TRANSPORT_TCP;
	} else if (!strncasecmp(pre2.transport, "tls", 3)) {
		transport = SIP_TRANSPORT_TLS;
		if (portnum < 0) {
			portnum = STANDARD_TLS_PORT;
		}
	} else if (!strncasecmp(pre2.transport, "udp", 3)) {
		transport = SIP_TRANSPORT_UDP;
	} else {
		ast_log(LOG_NOTICE, "'%.3s' is not a valid transport type on line %d of sip.conf. defaulting to udp.\n", pre2.transport, lineno);
	}

	if (portnum < 0) {
		portnum = STANDARD_SIP_PORT;
	}

	if (!(reg = ast_calloc(1, sizeof(*reg)))) {
		ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
		return -1;
	}

	if (ast_string_field_init(reg, 256)) {
		ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry strings\n");
		ast_free(reg);
		return -1;
	}

	/*!
	 * pre1.peer => peer
	 * transport = transport
	 * user2.userpart => user
	 * user2.domain => domain (regdomain)
	 * user1.secret => secret
	 * user1.authuser => authuser
	 * host3.host => host
	 * portnum => port
	 * host2.extension => extension (callback)
	 * host1.expiry => expiry
	 */
	regobjs++;
	ASTOBJ_INIT(reg);
	ast_string_field_set(reg, callback, ast_strip_quoted(S_OR(host2.extension, "s"), "\"", "\""));
	ast_string_field_set(reg, username, ast_strip_quoted(S_OR(user2.userpart, ""), "\"", "\""));
	ast_string_field_set(reg, hostname, ast_strip_quoted(S_OR(host3.host, ""), "\"", "\""));
	ast_string_field_set(reg, domain, ast_strip_quoted(S_OR(user2.domain, S_OR(host3.host, "")), "\"", "\""));
	ast_string_field_set(reg, authuser, ast_strip_quoted(S_OR(user1.authuser, ""), "\"", "\""));
	ast_string_field_set(reg, secret, ast_strip_quoted(S_OR(user1.secret, ""), "\"", "\""));
	ast_string_field_set(reg, peername, ast_strip_quoted(S_OR(pre1.peer, ""), "\"", "\""));

	reg->transport = transport;
	reg->timeout = reg->expire = -1;
	reg->refresh = reg->expiry = reg->configured_expiry = (host1.expiry ? atoi(ast_strip_quoted(host1.expiry, "\"", "\"")) : default_expiry);
	reg->portno = portnum;
	reg->callid_valid = FALSE;
	reg->ocseq = INITIAL_CSEQ;
	ASTOBJ_CONTAINER_LINK(&regl, reg);	/* Add the new registry entry to the list */
	registry_unref(reg);	/* release the reference given by ASTOBJ_INIT. The container has another reference */
	return 0;
}

/*! \brief  Parse multiline SIP headers into one header
	This is enabled if pedanticsipchecking is enabled */
static int lws2sws(char *msgbuf, int len) 
{
	int h = 0, t = 0; 
	int lws = 0; 

	for (; h < len;) { 
		/* Eliminate all CRs */ 
		if (msgbuf[h] == '\r') { 
			h++; 
			continue; 
		} 
		/* Check for end-of-line */ 
		if (msgbuf[h] == '\n') { 
			/* Check for end-of-message */ 
			if (h + 1 == len) 
				break; 
			/* Check for a continuation line */ 
			if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') { 
				/* Merge continuation line */ 
				h++; 
				continue; 
			} 
			/* Propagate LF and start new line */ 
			msgbuf[t++] = msgbuf[h++]; 
			lws = 0;
			continue; 
		} 
		if (msgbuf[h] == ' ' || msgbuf[h] == '\t') { 
			if (lws) { 
				h++; 
				continue; 
			} 
			msgbuf[t++] = msgbuf[h++]; 
			lws = 1; 
			continue; 
		} 
		msgbuf[t++] = msgbuf[h++]; 
		if (lws) 
			lws = 0; 
	} 
	msgbuf[t] = '\0'; 
	return t; 
}

/*! \brief Parse a SIP message 
	\note this function is used both on incoming and outgoing packets
*/
static int parse_request(struct sip_request *req)
{
	char *c = req->data, **dst = req->header;
	int i = 0, lim = SIP_MAX_HEADERS - 1;
	unsigned int skipping_headers = 0;

	req->header[0] = c;
	req->headers = -1;	/* mark that we are working on the header */
	for (; *c; c++) {
		if (*c == '\r') {		/* remove \r */
			*c = '\0';
		} else if (*c == '\n') { 	/* end of this line */
			*c = '\0';
			if (skipping_headers) {
				/* check to see if this line is blank; if so, turn off
				   the skipping flag, so the next line will be processed
				   as a body line */
				if (ast_strlen_zero(dst[i])) {
					skipping_headers = 0;
				}
				dst[i] = c + 1; /* record start of next line */
				continue;
			}
			if (sipdebug) {
				ast_debug(4, "%7s %2d [%3d]: %s\n",
					  req->headers < 0 ? "Header" : "Body",
					  i, (int) strlen(dst[i]), dst[i]);
			}
			if (ast_strlen_zero(dst[i]) && req->headers < 0) {
				req->headers = i;	/* record number of header lines */
				dst = req->line;	/* start working on the body */
				i = 0;
				lim = SIP_MAX_LINES - 1;
			} else {	/* move to next line, check for overflows */
				if (i++ == lim) {
					/* if we're processing headers, then skip any remaining
					   headers and move on to processing the body, otherwise
					   we're done */
					if (req->headers != -1) {
						break;
					} else {
						req->headers = i;
						dst = req->line;
						i = 0;
						lim = SIP_MAX_LINES - 1;
						skipping_headers = 1;
					}
				}
			}
			dst[i] = c + 1; /* record start of next line */
		}
        }

	/* Check for last header or body line without CRLF. The RFC for SDP requires CRLF,
	   but since some devices send without, we'll be generous in what we accept. However,
	   if we've already reached the maximum number of lines for portion of the message
	   we were parsing, we can't accept any more, so just ignore it.
	*/
	if ((i < lim) && !ast_strlen_zero(dst[i])) {
		if (sipdebug) {
			ast_debug(4, "%7s %2d [%3d]: %s\n",
				  req->headers < 0 ? "Header" : "Body",
				  i, (int) strlen(dst[i]), dst[i]);
		}
		i++;
	}

	/* update count of header or body lines */
	if (req->headers >= 0) {	/* we are in the body */
		req->lines = i;
	} else {			/* no body */
		req->headers = i;
		req->lines = 0;
		req->line[0] = "";
	}

	if (*c) {
		ast_log(LOG_WARNING, "Too many lines, skipping <%s>\n", c);
	}

	/* Split up the first line parts */
	return determine_firstline_parts(req);
}

/*!
  \brief Determine whether a SIP message contains an SDP in its body
  \param req the SIP request to process
  \return 1 if SDP found, 0 if not found

  Also updates req->sdp_start and req->sdp_count to indicate where the SDP
  lives in the message body.
*/
static int find_sdp(struct sip_request *req)
{
	const char *content_type;
	const char *content_length;
	const char *search;
	char *boundary;
	unsigned int x;
	int boundaryisquoted = FALSE;
	int found_application_sdp = FALSE;
	int found_end_of_headers = FALSE;

	content_length = get_header(req, "Content-Length");

	if (!ast_strlen_zero(content_length)) {
		if (sscanf(content_length, "%30u", &x) != 1) {
			ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
			return 0;
		}

		/* Content-Length of zero means there can't possibly be an
		   SDP here, even if the Content-Type says there is */
		if (x == 0)
			return 0;
	}

	content_type = get_header(req, "Content-Type");

	/* if the body contains only SDP, this is easy */
	if (!strncasecmp(content_type, "application/sdp", 15)) {
		req->sdp_start = 0;
		req->sdp_count = req->lines;
		return req->lines ? 1 : 0;
	}

	/* if it's not multipart/mixed, there cannot be an SDP */
	if (strncasecmp(content_type, "multipart/mixed", 15))
		return 0;

	/* if there is no boundary marker, it's invalid */
	if ((search = strcasestr(content_type, ";boundary=")))
		search += 10;
	else if ((search = strcasestr(content_type, "; boundary=")))
		search += 11;
	else
		return 0;

	if (ast_strlen_zero(search))
		return 0;

	/* If the boundary is quoted with ", remove quote */
	if (*search == '\"')  {
		search++;
		boundaryisquoted = TRUE;
	}

	/* make a duplicate of the string, with two extra characters
	   at the beginning */
	boundary = ast_strdupa(search - 2);
	boundary[0] = boundary[1] = '-';
	/* Remove final quote */
	if (boundaryisquoted)
		boundary[strlen(boundary) - 1] = '\0';

	/* search for the boundary marker, the empty line delimiting headers from
	   sdp part and the end boundry if it exists */

	for (x = 0; x < (req->lines ); x++) {
		if(!strncasecmp(req->line[x], boundary, strlen(boundary))){
			if(found_application_sdp && found_end_of_headers){
				req->sdp_count = (x - 1) - req->sdp_start;
				return 1;
			}
			found_application_sdp = FALSE;
		}
		if(!strcasecmp(req->line[x], "Content-Type: application/sdp"))
			found_application_sdp = TRUE;
		
		if (ast_strlen_zero(req->line[x])) {
			if(found_application_sdp && !found_end_of_headers){
				req->sdp_start = x;
				found_end_of_headers = TRUE;
			}
		}
	}
	if(found_application_sdp && found_end_of_headers) {
		req->sdp_count = x - req->sdp_start;
		return TRUE;
	}
	return FALSE;
}

enum media_type {
	SDP_AUDIO,
	SDP_VIDEO,
	SDP_IMAGE,
	SDP_TEXT,
};

static int get_ip_and_port_from_sdp(struct sip_request *req, const enum media_type media, struct sockaddr_in *sin)
{
	const char *m;
	const char *c;
	int miterator = req->sdp_start;
	int citerator = req->sdp_start;
	int x = 0;
	int numberofports;
	int len;
	char host[258] = ""; /*Initialize to empty so we will know if we have any input */
	struct ast_hostent audiohp;
	struct hostent *hp;

	c = get_sdp_iterate(&citerator, req, "c");
	if (sscanf(c, "IN IP4 %256s", host) != 1) {
		ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
		/* Continue since there may be a valid host in a c= line specific to the audio stream */
	}
	/* We only want the m and c lines for audio */
	for (m = get_sdp_iterate(&miterator, req, "m"); !ast_strlen_zero(m); m = get_sdp_iterate(&miterator, req, "m")) {
		if ((media == SDP_AUDIO && ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
		    (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0))) ||
			(media == SDP_VIDEO && ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
		    (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len > 0)))) {
			/* See if there's a c= line for this media stream.
			 * XXX There is no guarantee that we'll be grabbing the c= line for this
			 * particular media stream here. However, this is the same logic used in process_sdp.
			 */
			c = get_sdp_iterate(&citerator, req, "c");
			if (!ast_strlen_zero(c)) {
				sscanf(c, "IN IP4 %256s", host);
			}
			break;
		}
	}

	if (ast_strlen_zero(host) || x == 0) {
		ast_log(LOG_WARNING, "Failed to read an alternate host or port in SDP. Expect %s problems\n", media == SDP_AUDIO ? "audio" : "video");
		return -1;
	}

	hp = ast_gethostbyname(host, &audiohp);
	if (!hp) {
		ast_log(LOG_WARNING, "Could not look up IP address of alternate hostname. Expect %s problems\n", media == SDP_AUDIO? "audio" : "video");
		return -1;
	}

	memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
	sin->sin_port = htons(x);
	return 0;
}

/*! \brief Process SIP SDP offer, select formats and activate RTP channels
	If offer is rejected, we will not change any properties of the call
 	Return 0 on success, a negative value on errors.
	Must be called after find_sdp().
*/
static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
{
	/* Iterators for SDP parsing */
	int start = req->sdp_start;
	int next = start;
	int iterator = start;

	/* Temporary vars for SDP parsing */
	char type = '\0';
	const char *value = NULL;
	const char *m = NULL;           /* SDP media offer */
	const char *nextm = NULL;
	int len = -1;

	/* Host information */
	struct ast_hostent sessionhp;
	struct ast_hostent audiohp;
	struct ast_hostent videohp;
	struct ast_hostent texthp;
	struct ast_hostent imagehp;
	struct hostent *hp = NULL;	/*!< RTP Audio host IP */
	struct hostent *vhp = NULL;	/*!< RTP video host IP */
	struct hostent *thp = NULL;	/*!< RTP text host IP */
	struct hostent *ihp = NULL;     /*!< UDPTL host ip */
	int portno = -1;		/*!< RTP Audio port number */
	int vportno = -1;		/*!< RTP Video port number */
	int tportno = -1;		/*!< RTP Text port number */
	int udptlportno = -1;		/*!< UDPTL Image port number */
	struct sockaddr_in sin;		/*!< media socket address */
	struct sockaddr_in vsin;	/*!< video socket address */
	struct sockaddr_in isin;	/*!< image socket address */
	struct sockaddr_in tsin;	/*!< text socket address */

	/* Peer capability is the capability in the SDP, non codec is RFC2833 DTMF (101) */	
	int peercapability = 0, peernoncodeccapability = 0;
	int vpeercapability = 0, vpeernoncodeccapability = 0;
	int tpeercapability = 0, tpeernoncodeccapability = 0;

	struct ast_rtp *newaudiortp, *newvideortp, *newtextrtp;
	int newjointcapability;				/* Negotiated capability */
	int newpeercapability;
	int newnoncodeccapability;

	const char *codecs;
	int codec;

	/* Others */
	int sendonly = -1;
	int vsendonly = -1;
	int numberofports;
	int numberofmediastreams = 0;
	int last_rtpmap_codec = 0;
	int debug = sip_debug_test_pvt(p);

	/* START UNKNOWN */
	char buf[SIPBUFSIZE];
	/* END UNKNOWN */

	/* Initial check */
	if (!p->rtp) {
		ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
		return -1;
	}

	/* Initialize the temporary RTP structures we use to evaluate the offer from the peer */
#ifdef LOW_MEMORY
	newaudiortp = ast_threadstorage_get(&ts_audio_rtp, ast_rtp_alloc_size());
#else
	newaudiortp = alloca(ast_rtp_alloc_size());
#endif
	memset(newaudiortp, 0, ast_rtp_alloc_size());
	ast_rtp_new_init(newaudiortp);
	ast_rtp_pt_clear(newaudiortp);

#ifdef LOW_MEMORY
	newvideortp = ast_threadstorage_get(&ts_video_rtp, ast_rtp_alloc_size());
#else
	newvideortp = alloca(ast_rtp_alloc_size());
#endif
	memset(newvideortp, 0, ast_rtp_alloc_size());
	ast_rtp_new_init(newvideortp);
	ast_rtp_pt_clear(newvideortp);

#ifdef LOW_MEMORY
	newtextrtp = ast_threadstorage_get(&ts_text_rtp, ast_rtp_alloc_size());
#else
	newtextrtp = alloca(ast_rtp_alloc_size());
#endif
	memset(newtextrtp, 0, ast_rtp_alloc_size());
	ast_rtp_new_init(newtextrtp);
	ast_rtp_pt_clear(newtextrtp);

	/* Update our last rtprx when we receive an SDP, too */
	p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */

	memset(p->offered_media, 0, sizeof(p->offered_media));


	/* default: novideo and notext set */
	p->novideo = TRUE;
	p->notext = TRUE;

	if (p->vrtp)
		ast_rtp_pt_clear(newvideortp);  /* Must be cleared in case no m=video line exists */
 
	if (p->trtp)
		ast_rtp_pt_clear(newtextrtp);  /* Must be cleared in case no m=text line exists */
	
	/* Scan for the first media stream (m=) line to limit scanning of globals */
	nextm = get_sdp_iterate(&next, req, "m");
	if (ast_strlen_zero(nextm)) {
		ast_log(LOG_WARNING, "Insufficient information for SDP (m= not found)\n");
 		return -1;
 	}

	/* Scan session level SDP parameters (lines before first media stream) */
	while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
		int processed = FALSE;
		switch (type) {
		case 'o':
			/* If we end up receiving SDP that doesn't actually modify the session we don't want to treat this as a fatal
			 * error. We just want to ignore the SDP and let the rest of the packet be handled as normal.
			 */
			if (!process_sdp_o(value, p))
				return (p->session_modify == FALSE) ? 0 : -1;
			break;
		case 'c':
			if (process_sdp_c(value, &sessionhp)) {
				processed = TRUE;
				hp = &sessionhp.hp;
				vhp = hp;
				thp = hp;
				ihp = hp;
			}
			break;
		case 'a':
			if (process_sdp_a_sendonly(value, &sendonly)) {
				processed = TRUE;
				vsendonly = sendonly;
			}
			else if (process_sdp_a_audio(value, p, newaudiortp, &last_rtpmap_codec))
				processed = TRUE;
			else if (process_sdp_a_video(value, p, newvideortp, &last_rtpmap_codec))
				processed = TRUE;
			else if (process_sdp_a_text(value, p, newtextrtp, &last_rtpmap_codec))
				processed = TRUE;
			else if (process_sdp_a_image(value, p))
				processed = TRUE;
			break;
		}

		if (option_debug > 2)
			ast_log(LOG_DEBUG, "Processing session-level SDP %c=%s... %s\n", type, value, (processed == TRUE)? "OK." : "UNSUPPORTED.");
 	}



	/* Scan media stream (m=) specific parameters loop */
	while (!ast_strlen_zero(nextm)) {
		int audio = FALSE;
		int video = FALSE;
		int image = FALSE;
		int text = FALSE;
		int x;

		numberofports = 1;
		len = -1;
		start = next;
		m = nextm;
		iterator = next;
		nextm = get_sdp_iterate(&next, req, "m");

		/* Search for audio media definition */
		if ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
		    (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
			audio = TRUE;
			p->offered_media[SDP_AUDIO].offered = TRUE;
			numberofmediastreams++;
			portno = x;

			/* Scan through the RTP payload types specified in a "m=" line: */
			codecs = m + len;
			ast_copy_string(p->offered_media[SDP_AUDIO].text, codecs, sizeof(p->offered_media[SDP_AUDIO].text));
			for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
				if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
					ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
					return -1;
				}
				if (debug)
					ast_verbose("Found RTP audio format %d\n", codec);

				ast_rtp_set_m_type(newaudiortp, codec);
			}
		/* Search for video media definition */
		} else if ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
			   (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len >= 0)) {
			video = TRUE;
			p->novideo = FALSE;
			p->offered_media[SDP_VIDEO].offered = TRUE;
			numberofmediastreams++;
			vportno = x;

			/* Scan through the RTP payload types specified in a "m=" line: */
			codecs = m + len;
			ast_copy_string(p->offered_media[SDP_VIDEO].text, codecs, sizeof(p->offered_media[SDP_VIDEO].text));
			for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
				if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
					ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
					return -1;
				}
				if (debug)
					ast_verbose("Found RTP video format %d\n", codec);
				ast_rtp_set_m_type(newvideortp, codec);
			}
		/* Search for text media definition */
		} else if ((sscanf(m, "text %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
			   (sscanf(m, "text %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
			text = TRUE;
			p->notext = FALSE;
			p->offered_media[SDP_TEXT].offered = TRUE;
			numberofmediastreams++;
			tportno = x;

			/* Scan through the RTP payload types specified in a "m=" line: */
			codecs = m + len;
			ast_copy_string(p->offered_media[SDP_TEXT].text, codecs, sizeof(p->offered_media[SDP_TEXT].text));
			for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
				if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
					ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
					return -1;
				}
				if (debug)
					ast_verbose("Found RTP text format %d\n", codec);
				ast_rtp_set_m_type(newtextrtp, codec);
			}
		/* Search for image media definition */
		} else if (p->udptl && ((sscanf(m, "image %30u udptl t38%n", &x, &len) == 1 && len > 0) ||
					(sscanf(m, "image %30u UDPTL t38%n", &x, &len) == 1 && len > 0) )) {
			image = TRUE;
			if (debug)
				ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
			p->offered_media[SDP_IMAGE].offered = TRUE;
			udptlportno = x;
			numberofmediastreams++;

			if (p->t38.state != T38_ENABLED) {
				memset(&p->t38.their_parms, 0, sizeof(p->t38.their_parms));
			}
		} else {
			ast_log(LOG_WARNING, "Unsupported SDP media type in offer: %s\n", m);
			continue;
		}

		/* Check for number of ports */
		if (numberofports > 1)
			ast_log(LOG_WARNING, "SDP offered %d ports for media, not supported by Asterisk. Will try anyway...\n", numberofports);
		


		/* Media stream specific parameters */
		while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
			int processed = FALSE;

			switch (type) {
			case 'c':
				if (audio) {
					if (process_sdp_c(value, &audiohp)) {
						processed = TRUE;
						hp = &audiohp.hp;
					}
				} else if (video) {
					if (process_sdp_c(value, &videohp)) {
						processed = TRUE;
						vhp = &videohp.hp;
					}
				} else if (text) {
					if (process_sdp_c(value, &texthp)) {
						processed = TRUE;
						thp = &texthp.hp;
					}
				} else if (image) {
					if (process_sdp_c(value, &imagehp)) {
						processed = TRUE;
						ihp = &imagehp.hp;
					}
				}
				break;
			case 'a':
				/* Audio specific scanning */
				if (audio) {
					if (process_sdp_a_sendonly(value, &sendonly))
						processed = TRUE;
					else if (process_sdp_a_audio(value, p, newaudiortp, &last_rtpmap_codec))
						processed = TRUE;
				}
				/* Video specific scanning */
				else if (video) {
					if (process_sdp_a_sendonly(value, &vsendonly))
						processed = TRUE;
					else if (process_sdp_a_video(value, p, newvideortp, &last_rtpmap_codec))
						processed = TRUE;
				}
				/* Text (T.140) specific scanning */
				else if (text) {
					if (process_sdp_a_text(value, p, newtextrtp, &last_rtpmap_codec))
						processed = TRUE;
				}
				/* Image (T.38 FAX) specific scanning */
				else if (image) {
					if (process_sdp_a_image(value, p))
						processed = TRUE;
				}
				break;
			}

			if (option_debug > 2)
				ast_log(LOG_DEBUG, "Processing media-level (%s) SDP %c=%s... %s\n",
						(audio == TRUE)? "audio" : (video == TRUE)? "video" : "image",
						type, value,
						(processed == TRUE)? "OK." : "UNSUPPORTED.");
		}
	}


	/* Sanity checks */
	if (!hp && !vhp && !thp && !ihp) {
		ast_log(LOG_WARNING, "Insufficient information in SDP (c=)...\n");
		return -1;
	}

	if (portno == -1 && vportno == -1 && udptlportno == -1  && tportno == -1)
		/* No acceptable offer found in SDP  - we have no ports */
		/* Do not change RTP or VRTP if this is a re-invite */
		return -2;

	if (numberofmediastreams > 3)
		/* We have too many fax, audio and/or video and/or text media streams, fail this offer */
		return -3;

	if (udptlportno == -1) {
		change_t38_state(p, T38_DISABLED);
	}

	/* Now gather all of the codecs that we are asked for: */
	ast_rtp_get_current_formats(newaudiortp, &peercapability, &peernoncodeccapability);
	ast_rtp_get_current_formats(newvideortp, &vpeercapability, &vpeernoncodeccapability);
	ast_rtp_get_current_formats(newtextrtp, &tpeercapability, &tpeernoncodeccapability);
 
	newjointcapability = p->capability & (peercapability | vpeercapability | tpeercapability);
	newpeercapability = (peercapability | vpeercapability | tpeercapability);
	newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
		
		
	if (debug) {
		/* shame on whoever coded this.... */
		char s1[SIPBUFSIZE], s2[SIPBUFSIZE], s3[SIPBUFSIZE], s4[SIPBUFSIZE], s5[SIPBUFSIZE];

		ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s/text=%s, combined - %s\n",
			    ast_getformatname_multiple(s1, SIPBUFSIZE, p->capability),
			    ast_getformatname_multiple(s2, SIPBUFSIZE, peercapability),
			    ast_getformatname_multiple(s3, SIPBUFSIZE, vpeercapability),
			    ast_getformatname_multiple(s4, SIPBUFSIZE, tpeercapability),
			    ast_getformatname_multiple(s5, SIPBUFSIZE, newjointcapability));

		ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
			    ast_rtp_lookup_mime_multiple(s1, SIPBUFSIZE, p->noncodeccapability, 0, 0),
			    ast_rtp_lookup_mime_multiple(s2, SIPBUFSIZE, peernoncodeccapability, 0, 0),
			    ast_rtp_lookup_mime_multiple(s3, SIPBUFSIZE, newnoncodeccapability, 0, 0));
	}

	if (!newjointcapability && (portno != -1)) {
		ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
		/* Do NOT Change current setting */
		return -1;
	}

	/* Setup audio address and port */
	if (p->rtp) {
		if (portno > 0) {
			sin.sin_family = AF_INET;
			sin.sin_port = htons(portno);
			memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
			ast_rtp_set_peer(p->rtp, &sin);
			if (debug)
				ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
			/* We are now ready to change the sip session and p->rtp and p->vrtp with the offered codecs, since                                                                                                    
			   they are acceptable */
			p->jointcapability = newjointcapability;                /* Our joint codec profile for this call */
			p->peercapability = newpeercapability;                  /* The other sides capability in latest offer */
			p->jointnoncodeccapability = newnoncodeccapability;     /* DTMF capabilities */

			ast_rtp_pt_copy(p->rtp, newaudiortp);

			if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
				ast_clear_flag(&p->flags[0], SIP_DTMF);
				if (newnoncodeccapability & AST_RTP_DTMF) {
					/* XXX Would it be reasonable to drop the DSP at this point? XXX */
					ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
					/* Since RFC2833 is now negotiated we need to change some properties of the RTP stream */
					ast_rtp_setdtmf(p->rtp, 1);
					ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
				} else {
					ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
				}
			}
		} else if (udptlportno > 0) {
			if (debug)
				ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session.\n");
		} else {
			ast_rtp_stop(p->rtp);
			if (debug)
				ast_verbose("Peer doesn't provide audio\n");
		}
	}

	/* Setup video address and port */
	if (p->vrtp) {
		if (vportno > 0) {
			vsin.sin_family = AF_INET;
			vsin.sin_port = htons(vportno);
			memcpy(&vsin.sin_addr, vhp->h_addr, sizeof(vsin.sin_addr));
			ast_rtp_set_peer(p->vrtp, &vsin);
			if (debug) 
				ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(vsin.sin_addr), ntohs(vsin.sin_port));
			ast_rtp_pt_copy(p->vrtp, newvideortp);
		} else {
			ast_rtp_stop(p->vrtp);
			if (debug)
				ast_verbose("Peer doesn't provide video\n");
		}
	}

	/* Setup text address and port */
	if (p->trtp) {
		if (tportno > 0) {
			tsin.sin_family = AF_INET;
			tsin.sin_port = htons(tportno);
			memcpy(&tsin.sin_addr, thp->h_addr, sizeof(tsin.sin_addr));
			ast_rtp_set_peer(p->trtp, &tsin);
			if (debug) 
				ast_verbose("Peer T.140 RTP is at port %s:%d\n", ast_inet_ntoa(vsin.sin_addr), ntohs(vsin.sin_port));
			ast_rtp_pt_copy(p->trtp, newtextrtp);
		} else {
			ast_rtp_stop(p->trtp);
			if (debug)
				ast_verbose("Peer doesn't provide T.140\n");
		}
	}
	/* Setup image address and port */
	if (p->udptl) {
		if (udptlportno > 0) {
			isin.sin_family = AF_INET;
			isin.sin_port = htons(udptlportno);
			if (ast_test_flag(&p->flags[0], SIP_NAT) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
				struct sockaddr_in remote_address = { 0, };
				ast_rtp_get_peer(p->rtp, &remote_address);
				if (remote_address.sin_addr.s_addr) {
					memcpy(&isin, &remote_address, sizeof(isin));
					if (debug) {
						ast_log(LOG_DEBUG, "Peer T.38 UDPTL is set behind NAT and with destination, destination address now %s\n", ast_inet_ntoa(isin.sin_addr));
					}
				}
			} else {
				memcpy(&isin.sin_addr, ihp->h_addr, sizeof(sin.sin_addr));
			}
			ast_udptl_set_peer(p->udptl, &isin);
			if (debug)
				ast_debug(1,"Peer T.38 UDPTL is at port %s:%d\n", ast_inet_ntoa(isin.sin_addr), ntohs(isin.sin_port));

			/* verify the far max ifp can be calculated. this requires far max datagram to be set. */
			if (!ast_udptl_get_far_max_datagram(p->udptl)) {
				/* setting to zero will force a default if none was provided by the SDP */
				ast_udptl_set_far_max_datagram(p->udptl, 0);
			}

			/* Remote party offers T38, we need to update state */
			if ((t38action == SDP_T38_ACCEPT) &&
			    (p->t38.state == T38_LOCAL_REINVITE)) {
				change_t38_state(p, T38_ENABLED);
			} else if ((t38action == SDP_T38_INITIATE) &&
				   p->owner && p->lastinvite) {
				change_t38_state(p, T38_PEER_REINVITE); /* T38 Offered in re-invite from remote party */
			}
		} else {
			ast_udptl_stop(p->udptl);
			if (debug)
				ast_debug(1, "Peer doesn't provide T.38 UDPTL\n");
		}
	}

	if ((portno == -1) && (p->t38.state != T38_DISABLED)) {
		ast_debug(3, "Have T.38 but no audio, accepting offer anyway\n");
                return 0;
        }

	/* Ok, we're going with this offer */
	ast_debug(2, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, p->jointcapability));

	if (!p->owner) 	/* There's no open channel owning us so we can return here. For a re-invite or so, we proceed */
		return 0;

	ast_debug(4, "We have an owner, now see if we need to change this call\n");

	if (!(p->owner->nativeformats & p->jointcapability) && (p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
		if (debug) {
			char s1[SIPBUFSIZE], s2[SIPBUFSIZE];
			ast_debug(1, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n", 
				ast_getformatname_multiple(s1, SIPBUFSIZE, p->jointcapability),
				ast_getformatname_multiple(s2, SIPBUFSIZE, p->owner->nativeformats));
		}
		p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability) | (p->capability & tpeercapability);
		ast_set_read_format(p->owner, p->owner->readformat);
		ast_set_write_format(p->owner, p->owner->writeformat);
	}
	
	if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) && sin.sin_addr.s_addr && (!sendonly || sendonly == -1)) {
		ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
		/* Activate a re-invite */
		ast_queue_frame(p->owner, &ast_null_frame);
		/* Queue Manager Unhold event */
		append_history(p, "Unhold", "%s", req->data);
		if (global_callevents)
			manager_event(EVENT_FLAG_CALL, "Hold",
				      "Status: Off\r\n"
				      "Channel: %s\r\n"
				      "Uniqueid: %s\r\n",
				      p->owner->name,
				      p->owner->uniqueid);
		if (global_notifyhold)
			sip_peer_hold(p, FALSE);
		ast_clear_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD); /* Clear both flags */
	} else if (!sin.sin_addr.s_addr || (sendonly && sendonly != -1)) {
		int already_on_hold = ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD);
		ast_queue_control_data(p->owner, AST_CONTROL_HOLD, 
				       S_OR(p->mohsuggest, NULL),
				       !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
		if (sendonly)
			ast_rtp_stop(p->rtp);
		/* RTCP needs to go ahead, even if we're on hold!!! */
		/* Activate a re-invite */
		ast_queue_frame(p->owner, &ast_null_frame);
		/* Queue Manager Hold event */
		append_history(p, "Hold", "%s", req->data);
		if (global_callevents && !ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
			manager_event(EVENT_FLAG_CALL, "Hold",
				      "Status: On\r\n"
				      "Channel: %s\r\n"
				      "Uniqueid: %s\r\n",
				      p->owner->name, 
				      p->owner->uniqueid);
		}
		if (sendonly == 1)	/* One directional hold (sendonly/recvonly) */
			ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
		else if (sendonly == 2)	/* Inactive stream */
			ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
		else
			ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
		if (global_notifyhold && !already_on_hold)
			sip_peer_hold(p, TRUE);
	}
	
	return 0;
}

static int process_sdp_o(const char *o, struct sip_pvt *p)
{
	char *o_copy;
	char *token;
	int64_t rua_version;

	/* Store the SDP version number of remote UA. This will allow us to
	distinguish between session modifications and session refreshes. If
	the remote UA does not send an incremented SDP version number in a
	subsequent RE-INVITE then that means its not changing media session.
	The RE-INVITE may have been sent to update connected party, remote
	target or to refresh the session (Session-Timers).  Asterisk must not
	change media session and increment its own version number in answer
	SDP in this case. */

	p->session_modify = TRUE;

	if (ast_strlen_zero(o)) {
		ast_log(LOG_WARNING, "SDP syntax error. SDP without an o= line\n");
		return FALSE;
	}

	o_copy = ast_strdupa(o);
	token = strsep(&o_copy, " ");  /* Skip username   */
	if (!o_copy) {
		ast_log(LOG_WARNING, "SDP syntax error in o= line username\n");
		return FALSE;
	}
	token = strsep(&o_copy, " ");  /* Skip session-id */
	if (!o_copy) {
		ast_log(LOG_WARNING, "SDP syntax error in o= line session-id\n");
		return FALSE;
	}
	token = strsep(&o_copy, " ");  /* Version         */
	if (!o_copy) {
		ast_log(LOG_WARNING, "SDP syntax error in o= line\n");
		return FALSE;
	}
	if (!sscanf(token, "%30" SCNd64, &rua_version)) {
		ast_log(LOG_WARNING, "SDP syntax error in o= line version\n");
		return FALSE;
	}

	/* we need to check the SDP version number the other end sent us;
	 * our rules for deciding what to accept are a bit complex.
	 *
	 * 1) if 'ignoresdpversion' has been set for this dialog, then
	 *    we will just accept whatever they sent and assume it is
	 *    a modification of the session, even if it is not
	 * 2) otherwise, if this is the first SDP we've seen from them
	 *    we accept it
	 * 3) otherwise, if the new SDP version number is higher than the
	 *    old one, we accept it
	 * 4) otherwise, if this SDP is in response to us requesting a switch
	 *    to T.38, we accept the SDP, but also generate a warning message
	 *    that this peer should have the 'ignoresdpversion' option set,
	 *    because it is not following the SDP offer/answer RFC; if we did
	 *    not request a switch to T.38, then we stop parsing the SDP, as it
	 *    has not changed from the previous version
	 */

	if (ast_test_flag(&p->flags[1], SIP_PAGE2_IGNORESDPVERSION) ||
	    (p->sessionversion_remote < 0) ||
	    (p->sessionversion_remote < rua_version)) {
		p->sessionversion_remote = rua_version;
	} else {
		if (p->t38.state == T38_LOCAL_REINVITE) {
			p->sessionversion_remote = rua_version;
			ast_log(LOG_WARNING, "Call %s responded to our T.38 reinvite without changing SDP version; 'ignoresdpversion' should be set for this peer.\n", p->callid);
		} else {
			p->session_modify = FALSE;
			ast_debug(2, "Call %s responded to our reinvite without changing SDP version; ignoring SDP.\n", p->callid);
			return FALSE;
		}
	}

	return TRUE;
}

static int process_sdp_c(const char *c, struct ast_hostent *ast_hp)
{
	char host[258];
	struct hostent *hp;

	/* Check for Media-description-level-address */
	if (sscanf(c, "IN IP4 %255s", host) != 1) {
		ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
		return FALSE;
	} else {
		if (!(hp = ast_gethostbyname(host, ast_hp))) {
			ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in c= line, '%s'\n", c);
			return FALSE;
		}
		return TRUE;
	}
	return FALSE;
}

static int process_sdp_a_sendonly(const char *a, int *sendonly)
{
	int found = FALSE;

	if (!strcasecmp(a, "sendonly")) {
		if (*sendonly == -1)
			*sendonly = 1;
		found = TRUE;
	} else if (!strcasecmp(a, "inactive")) {
		if (*sendonly == -1)
			*sendonly = 2;
		found = TRUE;
	}  else if (!strcasecmp(a, "sendrecv")) {
		if (*sendonly == -1)
			*sendonly = 0;
		found = TRUE;
	}
	return found;
}

static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp *newaudiortp, int *last_rtpmap_codec)
{
	int found = FALSE;
	int codec;
	char mimeSubtype[128];
	int debug = sip_debug_test_pvt(p);

	if (!strncasecmp(a, "ptime", 5)) {
		char *tmp = strrchr(a, ':');
		long int framing = 0;
		if (tmp) {
			tmp++;
			framing = strtol(tmp, NULL, 10);
			if (framing == LONG_MIN || framing == LONG_MAX) {
				framing = 0;
				ast_debug(1, "Can't read framing from SDP: %s\n", a);
			}
		}
		if (framing && p->autoframing) {
			struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
			int codec_n;
			int format = 0;
			for (codec_n = 0; codec_n < MAX_RTP_PT; codec_n++) {
				format = ast_rtp_codec_getformat(codec_n);
				if (!format)	/* non-codec or not found */
					continue;
				if (option_debug)
					ast_log(LOG_DEBUG, "Setting framing for %d to %ld\n", format, framing);
				ast_codec_pref_setsize(pref, format, framing);
			}
			ast_rtp_codec_setpref(p->rtp, pref);
		}
		found = TRUE;
	} else if (sscanf(a, "rtpmap: %30u %127[^/]/", &codec, mimeSubtype) == 2) {
		/* We have a rtpmap to handle */
		if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
			if (ast_rtp_set_rtpmap_type(newaudiortp, codec, "audio", mimeSubtype,
			    ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0) != -1) {
				if (debug)
					ast_verbose("Found audio description format %s for ID %d\n", mimeSubtype, codec);
				//found_rtpmap_codecs[last_rtpmap_codec] = codec;
				(*last_rtpmap_codec)++;
				found = TRUE;
			} else {
				ast_rtp_unset_m_type(newaudiortp, codec);
				if (debug)
					ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
			}
		} else {
			if (debug)
				ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
		}
	}

	return found;
}

static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp *newvideortp, int *last_rtpmap_codec)
{
	int found = FALSE;
	int codec;
	char mimeSubtype[128];
	int debug = sip_debug_test_pvt(p);

	if (sscanf(a, "rtpmap: %30u %127[^/]/", &codec, mimeSubtype) == 2) {
		/* We have a rtpmap to handle */
		if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
			/* Note: should really look at the '#chans' params too */
			if (!strncasecmp(mimeSubtype, "H26", 3) || !strncasecmp(mimeSubtype, "MP4", 3)) {
				if (ast_rtp_set_rtpmap_type(newvideortp, codec, "video", mimeSubtype, 0) != -1) {
					if (debug)
						ast_verbose("Found video description format %s for ID %d\n", mimeSubtype, codec);
					//found_rtpmap_codecs[last_rtpmap_codec] = codec;
					(*last_rtpmap_codec)++;
					found = TRUE;
				} else {
					ast_rtp_unset_m_type(newvideortp, codec);
					if (debug) 
						ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
				}
			}
		} else {
			if (debug)
				ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
		}
	}

	return found;
}

static int process_sdp_a_text(const char *a, struct sip_pvt *p, struct ast_rtp *newtextrtp, int *last_rtpmap_codec)
{
	int found = FALSE;
	int codec;
	char mimeSubtype[128];
	int debug = sip_debug_test_pvt(p);

	if (sscanf(a, "rtpmap: %30u %127[^/]/", &codec, mimeSubtype) == 2) {
		/* We have a rtpmap to handle */
		if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
			if (!strncasecmp(mimeSubtype, "T140", 4)) { /* Text */
				if (p->trtp) {
					/* ast_verbose("Adding t140 mimeSubtype to textrtp struct\n"); */
					ast_rtp_set_rtpmap_type(newtextrtp, codec, "text", mimeSubtype, 0);
					found = TRUE;
				}
			}
		} else {
			if (debug)
				ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
		}
	}

	return found;
}

static int process_sdp_a_image(const char *a, struct sip_pvt *p)
{
	int found = FALSE;
	char s[256];
	unsigned int x;

	if ((sscanf(a, "T38FaxMaxBuffer:%30u", &x) == 1)) {
		ast_debug(3, "MaxBufferSize:%d\n", x);
		found = TRUE;
	} else if ((sscanf(a, "T38MaxBitRate:%30u", &x) == 1) || (sscanf(a, "T38FaxMaxRate:%30u", &x) == 1)) {
		ast_debug(3, "T38MaxBitRate: %d\n", x);
		switch (x) {
		case 14400:
			p->t38.their_parms.rate = AST_T38_RATE_14400;
			break;
		case 12000:
			p->t38.their_parms.rate = AST_T38_RATE_12000;
			break;
		case 9600:
			p->t38.their_parms.rate = AST_T38_RATE_9600;
			break;
		case 7200:
			p->t38.their_parms.rate = AST_T38_RATE_7200;
			break;
		case 4800:
			p->t38.their_parms.rate = AST_T38_RATE_4800;
			break;
		case 2400:
			p->t38.their_parms.rate = AST_T38_RATE_2400;
			break;
		}
		found = TRUE;
	} else if ((sscanf(a, "T38FaxVersion:%30u", &x) == 1)) {
		ast_debug(3, "FaxVersion: %u\n", x);
		p->t38.their_parms.version = x;
		found = TRUE;
	} else if ((sscanf(a, "T38FaxMaxDatagram:%30u", &x) == 1) || (sscanf(a, "T38MaxDatagram:%30u", &x) == 1)) {
		/* override the supplied value if the configuration requests it */
		if (((signed int) p->t38_maxdatagram >= 0) && ((unsigned int) p->t38_maxdatagram > x)) {
			ast_debug(1, "Overriding T38FaxMaxDatagram '%d' with '%d'\n", x, p->t38_maxdatagram);
			x = p->t38_maxdatagram;
		}
		ast_debug(3, "FaxMaxDatagram: %u\n", x);
		ast_udptl_set_far_max_datagram(p->udptl, x);
		found = TRUE;
	} else if ((strncmp(a, "T38FaxFillBitRemoval", 20) == 0)) {
		if (sscanf(a, "T38FaxFillBitRemoval:%30u", &x) == 1) {
			ast_debug(3, "FillBitRemoval: %d\n", x);
			if (x == 1) {
				p->t38.their_parms.fill_bit_removal = TRUE;
			}
		} else {
			ast_debug(3, "FillBitRemoval\n");
			p->t38.their_parms.fill_bit_removal = TRUE;
		}
		found = TRUE;
	} else if ((strncmp(a, "T38FaxTranscodingMMR", 20) == 0)) {
		if (sscanf(a, "T38FaxTranscodingMMR:%30u", &x) == 1) {
			ast_debug(3, "Transcoding MMR: %d\n", x);
			if (x == 1) {
				p->t38.their_parms.transcoding_mmr = TRUE;
			}
		} else {
			ast_debug(3, "Transcoding MMR\n");
			p->t38.their_parms.transcoding_mmr = TRUE;
		}
		found = TRUE;
	} else if ((strncmp(a, "T38FaxTranscodingJBIG", 21) == 0)) {
		if (sscanf(a, "T38FaxTranscodingJBIG:%30u", &x) == 1) {
			ast_debug(3, "Transcoding JBIG: %d\n", x);
			if (x == 1) {
				p->t38.their_parms.transcoding_jbig = TRUE;
			}
		} else {
			ast_debug(3, "Transcoding JBIG\n");
			p->t38.their_parms.transcoding_jbig = TRUE;
		}
		found = TRUE;
	} else if ((sscanf(a, "T38FaxRateManagement:%255s", s) == 1)) {
		ast_debug(3, "RateManagement: %s\n", s);
		if (!strcasecmp(s, "localTCF"))
			p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_LOCAL_TCF;
		else if (!strcasecmp(s, "transferredTCF"))
			p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF;
		found = TRUE;
	} else if ((sscanf(a, "T38FaxUdpEC:%255s", s) == 1)) {
		ast_debug(3, "UDP EC: %s\n", s);
		if (!strcasecmp(s, "t38UDPRedundancy")) {
			ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
		} else if (!strcasecmp(s, "t38UDPFEC")) {
			ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
		} else {
			ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
		}
		found = TRUE;
	}

	return found;
}


#ifdef LOW_MEMORY
static void ts_ast_rtp_destroy(void *data)
{
    struct ast_rtp *tmp = data;
    ast_rtp_destroy(tmp);
}
#endif

/*! \brief Add header to SIP message */
static int add_header(struct sip_request *req, const char *var, const char *value)
{
	int maxlen = sizeof(req->data) - 4 - req->len; /* 4 bytes are for two \r\n ? */

	if (req->headers == SIP_MAX_HEADERS) {
		ast_log(LOG_WARNING, "Out of SIP header space\n");
		return -1;
	}

	if (req->lines) {
		ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
		return -1;
	}

	if (maxlen <= 0) {
		ast_log(LOG_WARNING, "Out of space, can't add anymore (%s:%s)\n", var, value);
		return -1;
	}

	req->header[req->headers] = req->data + req->len;

	if (compactheaders)
		var = find_alias(var, var);

	snprintf(req->header[req->headers], maxlen, "%s: %s\r\n", var, value);
	req->len += strlen(req->header[req->headers]);
	req->headers++;

	return 0;	
}

/*! \brief Add 'Content-Length' header to SIP message */
static int add_header_contentLength(struct sip_request *req, int len)
{
	char clen[10];

	snprintf(clen, sizeof(clen), "%d", len);
	return add_header(req, "Content-Length", clen);
}

/*! \brief Add content (not header) to SIP message */
static int add_line(struct sip_request *req, const char *line)
{
	if (req->lines == SIP_MAX_LINES)  {
		ast_log(LOG_WARNING, "Out of SIP line space\n");
		return -1;
	}
	if (!req->lines) {
		/* Add extra empty return */
		ast_copy_string(req->data + req->len, "\r\n", sizeof(req->data) - req->len);
		req->len += strlen(req->data + req->len);
	}
	if (req->len >= sizeof(req->data) - 4) {
		ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
		return -1;
	}
	req->line[req->lines] = req->data + req->len;
	snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
	req->len += strlen(req->line[req->lines]);
	req->lines++;
	return 0;	
}

/*! \brief Copy one header field from one request to another */
static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
{
	const char *tmp = get_header(orig, field);

	if (!ast_strlen_zero(tmp)) /* Add what we're responding to */
		return add_header(req, field, tmp);
	ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
	return -1;
}

/*! \brief Copy all headers from one request to another */
static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
{
	int start = 0;
	int copied = 0;
	for (;;) {
		const char *tmp = __get_header(orig, field, &start);

		if (ast_strlen_zero(tmp))
			break;
		/* Add what we're responding to */
		add_header(req, field, tmp);
		copied++;
	}
	return copied ? 0 : -1;
}

/*! \brief Copy SIP VIA Headers from the request to the response
\note	If the client indicates that it wishes to know the port we received from,
	it adds ;rport without an argument to the topmost via header. We need to
	add the port number (from our point of view) to that parameter.
\verbatim
	We always add ;received=<ip address> to the topmost via header.
\endverbatim
	Received: RFC 3261, rport RFC 3581 */
static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
{
	int copied = 0;
	int start = 0;

	for (;;) {
		char new[512];
		const char *oh = __get_header(orig, field, &start);

		if (ast_strlen_zero(oh))
			break;

		if (!copied) {	/* Only check for empty rport in topmost via header */
			char leftmost[512], *others, *rport;

			/* Only work on leftmost value */
			ast_copy_string(leftmost, oh, sizeof(leftmost));
			others = strchr(leftmost, ',');
			if (others)
			    *others++ = '\0';

			/* Find ;rport;  (empty request) */
			rport = strstr(leftmost, ";rport");
			if (rport && *(rport+6) == '=') 
				rport = NULL;		/* We already have a parameter to rport */

			/* Check rport if NAT=yes or NAT=rfc3581 (which is the default setting)  */
			if (rport && ((ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_ALWAYS) || (ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_RFC3581))) {
				/* We need to add received port - rport */
				char *end;

				rport = strstr(leftmost, ";rport");

				if (rport) {
					end = strchr(rport + 1, ';');
					if (end)
						memmove(rport, end, strlen(end) + 1);
					else
						*rport = '\0';
				}

				/* Add rport to first VIA header if requested */
				snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
					leftmost, ast_inet_ntoa(p->recv.sin_addr),
					ntohs(p->recv.sin_port),
					others ? "," : "", others ? others : "");
			} else {
				/* We should *always* add a received to the topmost via */
				snprintf(new, sizeof(new), "%s;received=%s%s%s",
					leftmost, ast_inet_ntoa(p->recv.sin_addr),
					others ? "," : "", others ? others : "");
			}
			oh = new;	/* the header to copy */
		}  /* else add the following via headers untouched */
		add_header(req, field, oh);
		copied++;
	}
	if (!copied) {
		ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
		return -1;
	}
	return 0;
}

/*! \brief Add route header into request per learned route */
static void add_route(struct sip_request *req, struct sip_route *route)
{
	char r[SIPBUFSIZE*2], *p;
	int n, rem = sizeof(r);

	if (!route)
		return;

	p = r;
	for (;route ; route = route->next) {
		n = strlen(route->hop);
		if (rem < n+3) /* we need room for ",<route>" */
			break;
		if (p != r) {	/* add a separator after fist route */
			*p++ = ',';
			--rem;
		}
		*p++ = '<';
		ast_copy_string(p, route->hop, rem); /* cannot fail */
		p += n;
		*p++ = '>';
		rem -= (n+2);
	}
	*p = '\0';
	add_header(req, "Route", r);
}

/*! \brief Set destination from SIP URI */
static void set_destination(struct sip_pvt *p, char *uri)
{
	char *h, *maddr, hostname[256];
	int port, hn;
	struct hostent *hp;
	struct ast_hostent ahp;
	int debug=sip_debug_test_pvt(p);

	/* Parse uri to h (host) and port - uri is already just the part inside the <> */
	/* general form we are expecting is sip[s]:username[:password][;parameter]@host[:port][;...] */

	if (debug)
		ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);

	/* Find and parse hostname */
	h = strchr(uri, '@');
	if (h)
		++h;
	else {
		h = uri;
		if (!strncasecmp(h, "sip:", 4))
			h += 4;
		else if (!strncasecmp(h, "sips:", 5))
			h += 5;
	}
	hn = strcspn(h, ":;>") + 1;
	if (hn > sizeof(hostname)) 
		hn = sizeof(hostname);
	ast_copy_string(hostname, h, hn);
	/* XXX bug here if string has been trimmed to sizeof(hostname) */
	h += hn - 1;

	/* Is "port" present? if not default to STANDARD_SIP_PORT */
	if (*h == ':') {
		/* Parse port */
		++h;
		port = strtol(h, &h, 10);
	}
	else
		port = STANDARD_SIP_PORT;

	/* Got the hostname:port - but maybe there's a "maddr=" to override address? */
	maddr = strstr(h, "maddr=");
	if (maddr) {
		maddr += 6;
		hn = strspn(maddr, "0123456789.") + 1;
		if (hn > sizeof(hostname))
			hn = sizeof(hostname);
		ast_copy_string(hostname, maddr, hn);
	}
	
	hp = ast_gethostbyname(hostname, &ahp);
	if (hp == NULL)  {
		ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
		return;
	}
	p->sa.sin_family = AF_INET;
	memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
	p->sa.sin_port = htons(port);
	if (debug)
		ast_verbose("set_destination: set destination to %s, port %d\n", ast_inet_ntoa(p->sa.sin_addr), port);
}

/*! \brief Initialize SIP response, based on SIP request */
static int init_resp(struct sip_request *resp, const char *msg)
{
	/* Initialize a response */
	memset(resp, 0, sizeof(*resp));
	resp->method = SIP_RESPONSE;
	resp->header[0] = resp->data;
	snprintf(resp->header[0], sizeof(resp->data), "SIP/2.0 %s\r\n", msg);
	resp->len = strlen(resp->header[0]);
	resp->headers++;
	return 0;
}

/*! \brief Initialize SIP request */
static int init_req(struct sip_request *req, int sipmethod, const char *recip)
{
	/* Initialize a request */
	memset(req, 0, sizeof(*req));
        req->method = sipmethod;
	req->header[0] = req->data;
	snprintf(req->header[0], sizeof(req->data), "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
	req->len = strlen(req->header[0]);
	req->headers++;
	return 0;
}

/*! \brief Test if this response needs a contact header */
static inline int resp_needs_contact(const char *msg, enum sipmethod method) {
	/* Requirements for Contact header inclusion in responses generated
	 * from the header tables found in the following RFCs.  Where the
	 * Contact header was marked mandatory (m) or optional (o) this
	 * function returns 1.
	 *
	 * - RFC 3261 (ACK, BYE, CANCEL, INVITE, OPTIONS, REGISTER)
	 * - RFC 2976 (INFO)
	 * - RFC 3262 (PRACK)
	 * - RFC 3265 (SUBSCRIBE, NOTIFY)
	 * - RFC 3311 (UPDATE)
	 * - RFC 3428 (MESSAGE)
	 * - RFC 3515 (REFER)
	 * - RFC 3903 (PUBLISH)
	 */

	switch (method) {
		/* 1xx, 2xx, 3xx, 485 */
		case SIP_INVITE:
		case SIP_UPDATE:
		case SIP_SUBSCRIBE:
		case SIP_NOTIFY:
			if ((msg[0] >= '1' && msg[0] <= '3') || !strncmp(msg, "485", 3))
				return 1;
			break;

		/* 2xx, 3xx, 485 */
		case SIP_REGISTER:
		case SIP_OPTIONS:
			if (msg[0] == '2' || msg[0] == '3' || !strncmp(msg, "485", 3))
				return 1;
			break;

		/* 3xx, 485 */
		case SIP_BYE:
		case SIP_PRACK:
		case SIP_MESSAGE:
		case SIP_PUBLISH:
			if (msg[0] == '3' || !strncmp(msg, "485", 3))
				return 1;
			break;

		/* 2xx, 3xx, 4xx, 5xx, 6xx */
		case SIP_REFER:
			if (msg[0] >= '2' && msg[0] <= '6')
				return 1;
			break;

		/* contact will not be included for everything else */
		case SIP_ACK:
		case SIP_CANCEL:
		case SIP_INFO:
		case SIP_PING:
		default:
			return 0;
	}
	return 0;
}

/*! \brief Prepare SIP response packet */
static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
{
	char newto[256];
	const char *ot;

	init_resp(resp, msg);
	copy_via_headers(p, resp, req, "Via");
	if (msg[0] == '1' || msg[0] == '2')
		copy_all_header(resp, req, "Record-Route");
	copy_header(resp, req, "From");
	ot = get_header(req, "To");
	if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
		/* Add the proper tag if we don't have it already.  If they have specified
		   their tag, use it.  Otherwise, use our own tag */
		if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
			snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
		else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
			snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
		else
			ast_copy_string(newto, ot, sizeof(newto));
		ot = newto;
	}
	add_header(resp, "To", ot);
	copy_header(resp, req, "Call-ID");
	copy_header(resp, req, "CSeq");
	if (!ast_strlen_zero(global_useragent))
		add_header(resp, "User-Agent", global_useragent);
	add_header(resp, "Allow", ALLOWED_METHODS);
	add_header(resp, "Supported", SUPPORTED_EXTENSIONS);

	/* If this is an invite, add Session-Timers related headers if the feature is active for this session */
	if (p->method == SIP_INVITE && p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE) {
		char se_hdr[256];
		snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval, 
			strefresher2str(p->stimer->st_ref));
		add_header(resp, "Require", "timer");
		add_header(resp, "Session-Expires", se_hdr);
	}

	if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER)) {
		/* For registration responses, we also need expiry and
		   contact info */
		char tmp[256];

		snprintf(tmp, sizeof(tmp), "%d", p->expiry);
		add_header(resp, "Expires", tmp);
		if (p->expiry) {	/* Only add contact if we have an expiry time */
			char contact[SIPBUFSIZE];
			const char *contact_uri = p->method == SIP_SUBSCRIBE ? p->our_contact : p->fullcontact;
			char *brackets = strchr(contact_uri, '<');
			snprintf(contact, sizeof(contact), "%s%s%s;expires=%d", brackets ? "" : "<", contact_uri, brackets ? "" : ">", p->expiry);
			add_header(resp, "Contact", contact);	/* Not when we unregister */
		}
	} else if (!ast_strlen_zero(p->our_contact) && resp_needs_contact(msg, p->method)) {
		add_header(resp, "Contact", p->our_contact);
	}

	if (!ast_strlen_zero(p->url)) {
		add_header(resp, "Access-URL", p->url);
		ast_string_field_set(p, url, NULL);
	}

	return 0;
}

/*! \brief Initialize a SIP request message (not the initial one in a dialog) */
static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch)
{
	struct sip_request *orig = &p->initreq;
	char stripped[80];
	char tmp[80];
	char newto[256];
	const char *c;
	const char *ot, *of;
	int is_strict = FALSE;		/*!< Strict routing flag */
	int is_outbound = ast_test_flag(&p->flags[0], SIP_OUTGOING);	/* Session direction */

	memset(req, 0, sizeof(struct sip_request));
	
	snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
	
	if (!seqno) {
		p->ocseq++;
		seqno = p->ocseq;
	}
		
	/* A CANCEL must have the same branch as the INVITE that it is canceling. */
	if (sipmethod == SIP_CANCEL) {
		p->branch = p->invite_branch;
		build_via(p);
	} else if (newbranch && (sipmethod == SIP_INVITE)) {
		p->branch ^= ast_random();
		p->invite_branch = p->branch;
		build_via(p);
	} else if (newbranch) {
		p->branch ^= ast_random();
		build_via(p);
	}

	/* Check for strict or loose router */
	if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop, ";lr") == NULL) {
		is_strict = TRUE;
		if (sipdebug)
			ast_debug(1, "Strict routing enforced for session %s\n", p->callid);
	}
	
	if (sipmethod == SIP_CANCEL)
		c = p->initreq.rlPart2;	/* Use original URI */
	else if (sipmethod == SIP_ACK) {
		/* Use URI from Contact: in 200 OK (if INVITE) 
		(we only have the contacturi on INVITEs) */
		if (!ast_strlen_zero(p->okcontacturi))
			c = is_strict ? p->route->hop : p->okcontacturi;
 		else
 			c = p->initreq.rlPart2;
	} else if (!ast_strlen_zero(p->okcontacturi)) 
		c = is_strict ? p->route->hop : p->okcontacturi; /* Use for BYE or REINVITE */
	else if (!ast_strlen_zero(p->uri)) 
		c = p->uri;
	else {
		char *n;
		/* We have no URI, use To: or From:  header as URI (depending on direction) */
		ast_copy_string(stripped, get_header(orig, is_outbound ? "To" : "From"),
				sizeof(stripped));
		n = get_in_brackets(stripped);
		c = remove_uri_parameters(n);
	}	
	init_req(req, sipmethod, c);

	snprintf(tmp, sizeof(tmp), "%d %s", seqno, sip_methods[sipmethod].text);

	add_header(req, "Via", p->via);
	if (p->route) {
		set_destination(p, p->route->hop);
		add_route(req, is_strict ? p->route->next : p->route);
	}
	add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);

	ot = get_header(orig, "To");
	of = get_header(orig, "From");

	/* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
	   as our original request, including tag (or presumably lack thereof) */
	if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
		/* Add the proper tag if we don't have it already.  If they have specified
		   their tag, use it.  Otherwise, use our own tag */
		if (is_outbound && !ast_strlen_zero(p->theirtag))
			snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
		else if (!is_outbound)
			snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
		else
			snprintf(newto, sizeof(newto), "%s", ot);
		ot = newto;
	}

	if (is_outbound) {
		add_header(req, "From", of);
		add_header(req, "To", ot);
	} else {
		add_header(req, "From", ot);
		add_header(req, "To", of);
	}
	/* Do not add Contact for MESSAGE, BYE and Cancel requests */
	if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
		add_header(req, "Contact", p->our_contact);

	copy_header(req, orig, "Call-ID");
	add_header(req, "CSeq", tmp);

	if (!ast_strlen_zero(global_useragent))
		add_header(req, "User-Agent", global_useragent);

	if (!ast_strlen_zero(p->rpid))
		add_header(req, "Remote-Party-ID", p->rpid);

	if (!ast_strlen_zero(p->url)) {
		add_header(req, "Access-URL", p->url);
		ast_string_field_set(p, url, NULL);
	}

	/* Add Session-Timers related headers if the feature is active for this session.
	   An exception to this behavior is the ACK request. Since Asterisk never requires 
	   session-timers support from a remote end-point (UAS) in an INVITE, it must 
	   not send 'Require: timer' header in the ACK request. 
	   This should only be added in the INVITE transactions, not MESSAGE or REFER or other
	   in-dialog messages.
	*/
	if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE 
	    && sipmethod == SIP_INVITE) {
		char se_hdr[256];
		snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval, 
			strefresher2str(p->stimer->st_ref));
		add_header(req, "Require", "timer");
		add_header(req, "Session-Expires", se_hdr);
		snprintf(se_hdr, sizeof(se_hdr), "%d", st_get_se(p, FALSE));
		add_header(req, "Min-SE", se_hdr);
	}

	return 0;
}

/*! \brief Base transmit response function */
static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
{
	struct sip_request resp;
	int seqno = 0;

	if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
		ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
		return -1;
	}
	respprep(&resp, p, msg, req);
	add_header_contentLength(&resp, 0);
	/* If we are cancelling an incoming invite for some reason, add information
		about the reason why we are doing this in clear text */
	if (p->method == SIP_INVITE && msg[0] != '1' && p->owner && p->owner->hangupcause) {
		char buf[10];

		add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
		snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
		add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
	}
	return send_response(p, &resp, reliable, seqno);
}

static int temp_pvt_init(void *data)
{
	struct sip_pvt *p = data;

	p->do_history = 0;	/* XXX do we need it ? isn't already all 0 ? */
	return ast_string_field_init(p, 512);
}

static void temp_pvt_cleanup(void *data)
{
	struct sip_pvt *p = data;

	ast_string_field_free_memory(p);

	ast_free(data);
}

/*! \brief Transmit response, no retransmits, using a temporary pvt structure */
static int transmit_response_using_temp(ast_string_field callid, struct sockaddr_in *sin, int useglobal_nat, const int intended_method, const struct sip_request *req, const char *msg)
{
	struct sip_pvt *p = NULL;

	if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
		ast_log(LOG_NOTICE, "Failed to get temporary pvt\n");
		return -1;
	}

	/* XXX the structure may be dirty from previous usage.
	 * Here we should state clearly how we should reinitialize it
	 * before using it.
	 * E.g. certainly the threadstorage should be left alone,
	 * but other thihngs such as flags etc. maybe need cleanup ?
	 */
	 
	/* Initialize the bare minimum */
	p->method = intended_method;

	if (!sin)
		p->ourip = internip;
	else {
		p->sa = *sin;
		ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
	}

	p->branch = ast_random();
	make_our_tag(p->tag, sizeof(p->tag));
	p->ocseq = INITIAL_CSEQ;

	if (useglobal_nat && sin) {
		ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
		p->recv = *sin;
		do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
	}

	ast_string_field_set(p, fromdomain, default_fromdomain);
	build_via(p);
	ast_string_field_set(p, callid, callid);

	copy_socket_data(&p->socket, &req->socket);

	/* Use this temporary pvt structure to send the message */
	__transmit_response(p, msg, req, XMIT_UNRELIABLE);

	/* Free the string fields, but not the pool space */
	ast_string_field_init(p, 0);

	return 0;
}

/*! \brief Transmit response, no retransmits */
static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req) 
{
	return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
}

/*! \brief Transmit response, no retransmits */
static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported) 
{
	struct sip_request resp;
	respprep(&resp, p, msg, req);
	append_date(&resp);
	add_header(&resp, "Unsupported", unsupported);
	add_header_contentLength(&resp, 0);
	return send_response(p, &resp, XMIT_UNRELIABLE, 0);
}

/*! \brief Transmit 422 response with Min-SE header (Session-Timers)  */
static int transmit_response_with_minse(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minse_int)
{
	struct sip_request resp;
	char minse_str[20];

	respprep(&resp, p, msg, req);
	append_date(&resp);

	snprintf(minse_str, sizeof(minse_str), "%d", minse_int);
	add_header(&resp, "Min-SE", minse_str);

	add_header_contentLength(&resp, 0);
	return send_response(p, &resp, XMIT_UNRELIABLE, 0);
}


/*! \brief Transmit response, Make sure you get an ACK
	This is only used for responses to INVITEs, where we need to make sure we get an ACK
*/
static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
{
	return __transmit_response(p, msg, req, req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL);
}

/*! \brief Append date to SIP message */
static void append_date(struct sip_request *req)
{
	char tmpdat[256];
	struct tm tm;
	time_t t = time(NULL);

	gmtime_r(&t, &tm);
	strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
	add_header(req, "Date", tmpdat);
}

/*! \brief Append date and content length before transmitting response */
static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
{
	struct sip_request resp;
	respprep(&resp, p, msg, req);
	append_date(&resp);
	add_header_contentLength(&resp, 0);
	return send_response(p, &resp, XMIT_UNRELIABLE, 0);
}

/*! \brief Append Accept header, content length before transmitting response */
static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
{
	struct sip_request resp;
	respprep(&resp, p, msg, req);
	add_header(&resp, "Accept", "application/sdp");
	add_header_contentLength(&resp, 0);
	return send_response(p, &resp, reliable, 0);
}

/*! \brief Respond with authorization request */
static int transmit_response_with_auth(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *randdata, enum xmittype reliable, const char *header, int stale)
{
	struct sip_request resp;
	char tmp[512];
	int seqno = 0;

	if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
		ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
		return -1;
	}
	/* Stale means that they sent us correct authentication, but 
	   based it on an old challenge (nonce) */
	snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", global_realm, randdata, stale ? ", stale=true" : "");
	respprep(&resp, p, msg, req);
	add_header(&resp, header, tmp);
	add_header_contentLength(&resp, 0);
	append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
	return send_response(p, &resp, reliable, seqno);
}

/* Only use a static string for the msg, here! */
static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp)
{
	int res;

	if (!(res = with_sdp ? transmit_response_with_sdp(p, msg, req, XMIT_UNRELIABLE, FALSE) : transmit_response(p, msg, req))) {
		p->last_provisional = msg;
		update_provisional_keepalive(p, with_sdp);
	}

	return res;
}

/*! \brief Add text body to SIP message */
static int add_text(struct sip_request *req, const char *text)
{
	/* XXX Convert \n's to \r\n's XXX */
	add_header(req, "Content-Type", "text/plain");
	add_header_contentLength(req, strlen(text));
	add_line(req, text);
	return 0;
}

/*! \brief Add DTMF INFO tone to sip message 
	Mode = 	0 for application/dtmf-relay (Cisco)
		1 for application/dtmf
*/
static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode)
{
	char tmp[256];
	int event;
	if (mode) {
		/* Application/dtmf short version used by some implementations */
		if (digit == '*')
			event = 10;
		else if (digit == '#')
			event = 11;
		else if ((digit >= 'A') && (digit <= 'D'))
			event = 12 + digit - 'A';
		else
			event = atoi(&digit);
		snprintf(tmp, sizeof(tmp), "%d\r\n", event);
		add_header(req, "Content-Type", "application/dtmf");
		add_header_contentLength(req, strlen(tmp));
		add_line(req, tmp);
	} else {
		/* Application/dtmf-relay as documented by Cisco */
		snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
		add_header(req, "Content-Type", "application/dtmf-relay");
		add_header_contentLength(req, strlen(tmp));
		add_line(req, tmp);
	}
	return 0;
}

/*! \brief add XML encoded media control with update 
	\note XML: The only way to turn 0 bits of information into a few hundred. (markster) */
static int add_vidupdate(struct sip_request *req)
{
	const char *xml_is_a_huge_waste_of_space =
		"<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
		" <media_control>\r\n"
		"  <vc_primitive>\r\n"
		"   <to_encoder>\r\n"
		"    <picture_fast_update>\r\n"
		"    </picture_fast_update>\r\n"
		"   </to_encoder>\r\n"
		"  </vc_primitive>\r\n"
		" </media_control>\r\n";
	add_header(req, "Content-Type", "application/media_control+xml");
	add_header_contentLength(req, strlen(xml_is_a_huge_waste_of_space));
	add_line(req, xml_is_a_huge_waste_of_space);
	return 0;
}

/*! \brief Add codec offer to SDP offer/answer body in INVITE or 200 OK */
static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
			     struct ast_str **m_buf, struct ast_str **a_buf,
			     int debug, int *min_packet_size)
{
	int rtp_code;
	struct ast_format_list fmt;


	if (debug)
		ast_verbose("Adding codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
	if ((rtp_code = ast_rtp_lookup_code(p->rtp, 1, codec)) == -1)
		return;

	if (p->rtp) {
		struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
		fmt = ast_codec_pref_getsize(pref, codec);
	} else /* I dont see how you couldn't have p->rtp, but good to check for and error out if not there like earlier code */
		return;
	ast_str_append(m_buf, 0, " %d", rtp_code);
	ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
			 ast_rtp_lookup_mime_subtype(1, codec,
						     ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
			 sample_rate);
	if (codec == AST_FORMAT_G729A) {
		/* Indicate that we don't support VAD (G.729 annex B) */
		ast_str_append(a_buf, 0, "a=fmtp:%d annexb=no\r\n", rtp_code);
	} else if (codec == AST_FORMAT_G723_1) {
		/* Indicate that we don't support VAD (G.723.1 annex A) */
		ast_str_append(a_buf, 0, "a=fmtp:%d annexa=no\r\n", rtp_code);
	} else if (codec == AST_FORMAT_ILBC) {
		/* Add information about us using only 20/30 ms packetization */
		ast_str_append(a_buf, 0, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
	}

	if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
		*min_packet_size = fmt.cur_ms;

	/* Our first codec packetization processed cannot be zero */
	if ((*min_packet_size)==0 && fmt.cur_ms)
		*min_packet_size = fmt.cur_ms;
}

/*! \brief Add video codec offer to SDP offer/answer body in INVITE or 200 OK */
/* This is different to the audio one now so we can add more caps later */
static void add_vcodec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
			     struct ast_str **m_buf, struct ast_str **a_buf,
			     int debug, int *min_packet_size)
{
	int rtp_code;

	if (!p->vrtp)
		return;

	if (debug)
		ast_verbose("Adding video codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));

	if ((rtp_code = ast_rtp_lookup_code(p->vrtp, 1, codec)) == -1)
		return;

	ast_str_append(m_buf, 0, " %d", rtp_code);
	ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
			 ast_rtp_lookup_mime_subtype(1, codec, 0), sample_rate);
	/* Add fmtp code here */
}

/*! \brief Add text codec offer to SDP offer/answer body in INVITE or 200 OK */
static void add_tcodec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
			     struct ast_str **m_buf, struct ast_str **a_buf,
			     int debug, int *min_packet_size)
{
	int rtp_code;

	if (!p->trtp)
		return;

	if (debug)
		ast_verbose("Adding text codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));

	if ((rtp_code = ast_rtp_lookup_code(p->trtp, 1, codec)) == -1)
		return;

	ast_str_append(m_buf, 0, " %d", rtp_code);
	ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
			 ast_rtp_lookup_mime_subtype(1, codec, 0), sample_rate);
	/* Add fmtp code here */
}


/*! \brief Get Max T.38 Transmission rate from T38 capabilities */
static unsigned int t38_get_rate(enum ast_control_t38_rate rate)
{
	switch (rate) {
	case AST_T38_RATE_2400:
		return 2400;
	case AST_T38_RATE_4800:
		return 4800;
	case AST_T38_RATE_7200:
		return 7200;
	case AST_T38_RATE_9600:
		return 9600;
	case AST_T38_RATE_12000:
		return 12000;
	case AST_T38_RATE_14400:
		return 14400;
	default:
		return 0;
	}
}

/*! \brief Add RFC 2833 DTMF offer to SDP */
static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
				struct ast_str **m_buf, struct ast_str **a_buf,
				int debug)
{
	int rtp_code;

	if (debug)
		ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype(0, format, 0));
	if ((rtp_code = ast_rtp_lookup_code(p->rtp, 0, format)) == -1)
		return;

	ast_str_append(m_buf, 0, " %d", rtp_code);
	ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
			 ast_rtp_lookup_mime_subtype(0, format, 0),
			 sample_rate);
	if (format == AST_RTP_DTMF)	/* Indicate we support DTMF and FLASH... */
		ast_str_append(a_buf, 0, "a=fmtp:%d 0-16\r\n", rtp_code);
}

/*! \brief Set all IP media addresses for this call 
	\note called from add_sdp()
*/
static void get_our_media_address(struct sip_pvt *p, int needvideo,
	struct sockaddr_in *sin, struct sockaddr_in *vsin, struct sockaddr_in *tsin,
	struct sockaddr_in *dest, struct sockaddr_in *vdest)
{
	/* First, get our address */
	ast_rtp_get_us(p->rtp, sin);
	if (p->vrtp)
		ast_rtp_get_us(p->vrtp, vsin);
	if (p->trtp)
		ast_rtp_get_us(p->trtp, tsin);

	/* Now, try to figure out where we want them to send data */
	/* Is this a re-invite to move the media out, then use the original offer from caller  */
	if (p->redirip.sin_addr.s_addr) {	/* If we have a redirection IP, use it */
		dest->sin_port = p->redirip.sin_port;
		dest->sin_addr = p->redirip.sin_addr;
	} else {
		dest->sin_addr = p->ourip.sin_addr;
		dest->sin_port = sin->sin_port;
	}
	if (needvideo) {
		/* Determine video destination */
		if (p->vredirip.sin_addr.s_addr) {
			vdest->sin_addr = p->vredirip.sin_addr;
			vdest->sin_port = p->vredirip.sin_port;
		} else {
			vdest->sin_addr = p->ourip.sin_addr;
			vdest->sin_port = vsin->sin_port;
		}
	}

}

/*!
 * \note G.722 actually is supposed to specified as 8 kHz, even though it is
 * really 16 kHz.  Update this macro for other formats as they are added in
 * the future.
 */
#define SDP_SAMPLE_RATE(x) 8000

/*! \brief Add Session Description Protocol message 

    If oldsdp is TRUE, then the SDP version number is not incremented. This mechanism
    is used in Session-Timers where RE-INVITEs are used for refreshing SIP sessions 
    without modifying the media session in any way. 
*/
static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38)
{
	int len = 0;
	int alreadysent = 0;

	struct sockaddr_in sin;
	struct sockaddr_in vsin;
	struct sockaddr_in tsin;
	struct sockaddr_in dest;
	struct sockaddr_in udptlsin;
	struct sockaddr_in vdest = { 0, };
	struct sockaddr_in tdest = { 0, };
	struct sockaddr_in udptldest = { 0, };

	/* SDP fields */
	char *version = 	"v=0\r\n";		/* Protocol version */
	char subject[256];				/* Subject of the session */
	char owner[256];				/* Session owner/creator */
	char connection[256];				/* Connection data */
	char *stime = "t=0 0\r\n"; 			/* Time the session is active */
	char bandwidth[256] = "";			/* Max bitrate */
	char *hold = "";
	struct ast_str *m_audio = ast_str_alloca(256);  /* Media declaration line for audio */
	struct ast_str *m_video = ast_str_alloca(256);  /* Media declaration line for video */
	struct ast_str *m_text = ast_str_alloca(256);   /* Media declaration line for text */
	struct ast_str *m_modem = ast_str_alloca(256);  /* Media declaration line for modem */
	struct ast_str *a_audio = ast_str_alloca(1024); /* Attributes for audio */
	struct ast_str *a_video = ast_str_alloca(1024); /* Attributes for video */
	struct ast_str *a_text = ast_str_alloca(1024);  /* Attributes for text */
	struct ast_str *a_modem = ast_str_alloca(1024); /* Attributes for modem */

	int x;
	int capability = 0;
	int needaudio = FALSE;
	int needvideo = FALSE;
	int needtext = FALSE;
	int debug = sip_debug_test_pvt(p);
	int min_audio_packet_size = 0;
	int min_video_packet_size = 0;
	int min_text_packet_size = 0;

	char codecbuf[SIPBUFSIZE];
	char buf[SIPBUFSIZE];
	char dummy_answer[256];

	/* Set the SDP session name */
	snprintf(subject, sizeof(subject), "s=%s\r\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);

	if (!p->rtp) {
		ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
		return AST_FAILURE;
	}
	/* XXX We should not change properties in the SIP dialog until 
		we have acceptance of the offer if this is a re-invite */

	/* Set RTP Session ID and version */
	if (!p->sessionid) {
		p->sessionid = (int)ast_random();
		p->sessionversion = p->sessionid;
	} else {
		if (oldsdp == FALSE)
			p->sessionversion++;
	}

	if (add_audio) {
		/* Check if we need video in this call */
		if ((p->jointcapability & AST_FORMAT_VIDEO_MASK) && !p->novideo) {
			if (p->vrtp) {
				needvideo = TRUE;
				ast_debug(2, "This call needs video offers!\n");
			} else
				ast_debug(2, "This call needs video offers, but there's no video support enabled!\n");
		}
		/* Check if we need text in this call */
		if ((p->jointcapability & AST_FORMAT_TEXT_MASK) && !p->notext) {
			if (sipdebug_text)
				ast_verbose("We think we can do text\n");
			if (p->trtp) {
				if (sipdebug_text) {
					ast_verbose("And we have a text rtp object\n");
				}
				needtext = TRUE;
				ast_debug(2, "This call needs text offers! \n");
			} else {
				ast_debug(2, "This call needs text offers, but there's no text support enabled ! \n");
			}
		}
	}

	get_our_media_address(p, needvideo, &sin, &vsin, &tsin, &dest, &vdest);

	snprintf(owner, sizeof(owner), "o=%s %d %d IN IP4 %s\r\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner, p->sessionid, p->sessionversion, ast_inet_ntoa(dest.sin_addr));
	snprintf(connection, sizeof(connection), "c=IN IP4 %s\r\n", ast_inet_ntoa(dest.sin_addr));

	if (add_audio) {
		capability = p->jointcapability;

		/* XXX note, Video and Text are negated - 'true' means 'no' */
		ast_debug(1, "** Our capability: %s Video flag: %s Text flag: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability), 
			  p->novideo ? "True" : "False", p->notext ? "True" : "False");
		ast_debug(1, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcodec));

		/* Check if we need audio */
		if (capability & AST_FORMAT_AUDIO_MASK)
			needaudio = TRUE;

		if (debug) 
			ast_verbose("Audio is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(sin.sin_port));	

		/* Ok, we need video. Let's add what we need for video and set codecs.
		   Video is handled differently than audio since we can not transcode. */
		if (needvideo) {
			ast_str_append(&m_video, 0, "m=video %d RTP/AVP", ntohs(vdest.sin_port));

			/* Build max bitrate string */
			if (p->maxcallbitrate)
				snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
			if (debug) 
				ast_verbose("Video is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(vdest.sin_port));	
		}

		/* Ok, we need text. Let's add what we need for text and set codecs.
		   Text is handled differently than audio since we can not transcode. */
		if (needtext) {
			if (sipdebug_text)
				ast_verbose("Lets set up the text sdp\n");
			/* Determine text destination */
			if (p->tredirip.sin_addr.s_addr) {
				tdest.sin_addr = p->tredirip.sin_addr;
				tdest.sin_port = p->tredirip.sin_port;
			} else {
				tdest.sin_addr = p->ourip.sin_addr;
				tdest.sin_port = tsin.sin_port;
			}
			ast_str_append(&m_text, 0, "m=text %d RTP/AVP", ntohs(tdest.sin_port));

			if (debug) /* XXX should I use tdest below ? */
				ast_verbose("Text is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(tsin.sin_port));	

		}

		/* Start building generic SDP headers */

		/* We break with the "recommendation" and send our IP, in order that our
		   peer doesn't have to ast_gethostbyname() us */

		ast_str_append(&m_audio, 0, "m=audio %d RTP/AVP", ntohs(dest.sin_port));

		if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR)
			hold = "a=recvonly\r\n";
		else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE)
			hold = "a=inactive\r\n";
		else
			hold = "a=sendrecv\r\n";

		/* Now, start adding audio codecs. These are added in this order:
		   - First what was requested by the calling channel
		   - Then preferences in order from sip.conf device config for this peer/user
		   - Then other codecs in capabilities, including video
		*/

		/* Prefer the audio codec we were requested to use, first, no matter what 
		   Note that p->prefcodec can include video codecs, so mask them out
		*/
		if (capability & p->prefcodec) {
			int codec = p->prefcodec & AST_FORMAT_AUDIO_MASK;

			add_codec_to_sdp(p, codec, SDP_SAMPLE_RATE(codec),
					 &m_audio, &a_audio,
					 debug, &min_audio_packet_size);
			alreadysent |= codec;
		}

		/* Start by sending our preferred audio/video codecs */
		for (x = 0; x < 32; x++) {
			int codec;

			if (!(codec = ast_codec_pref_index(&p->prefs, x)))
				break; 

			if (!(capability & codec))
				continue;

			if (alreadysent & codec)
			continue;

			add_codec_to_sdp(p, codec, SDP_SAMPLE_RATE(codec),
					 &m_audio, &a_audio,
					 debug, &min_audio_packet_size);
			alreadysent |= codec;
		}

		/* Now send any other common audio and video codecs, and non-codec formats: */
		for (x = 1; x <= (needtext ? AST_FORMAT_TEXT_MASK : (needvideo ? AST_FORMAT_VIDEO_MASK : AST_FORMAT_AUDIO_MASK)); x <<= 1) {
			if (!(capability & x))	/* Codec not requested */
				continue;

			if (alreadysent & x)	/* Already added to SDP */
				continue;

			if (x & AST_FORMAT_AUDIO_MASK)
				add_codec_to_sdp(p, x, SDP_SAMPLE_RATE(x),
						 &m_audio, &a_audio, debug, &min_audio_packet_size);
			else if (x & AST_FORMAT_VIDEO_MASK) 
				add_vcodec_to_sdp(p, x, 90000,
						  &m_video, &a_video, debug, &min_video_packet_size);
			else if (x & AST_FORMAT_TEXT_MASK)
				add_tcodec_to_sdp(p, x, 1000,
						  &m_text, &a_text, debug, &min_text_packet_size);
		}

		/* Now add DTMF RFC2833 telephony-event as a codec */
		for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
			if (!(p->jointnoncodeccapability & x))
				continue;

			add_noncodec_to_sdp(p, x, 8000, &m_audio, &a_audio, debug);
		}

		ast_debug(3, "-- Done with adding codecs to SDP\n");

		if (!p->owner || !ast_internal_timing_enabled(p->owner))
			ast_str_append(&a_audio, 0, "a=silenceSupp:off - - - -\r\n");

		if (min_audio_packet_size)
			ast_str_append(&a_audio, 0, "a=ptime:%d\r\n", min_audio_packet_size);

		/* XXX don't think you can have ptime for video */
		if (min_video_packet_size)
			ast_str_append(&a_video, 0, "a=ptime:%d\r\n", min_video_packet_size);

		/* XXX don't think you can have ptime for text */
		if (min_text_packet_size)
			ast_str_append(&a_text, 0, "a=ptime:%d\r\n", min_text_packet_size);
	}

	if (add_t38) {
		ast_udptl_get_us(p->udptl, &udptlsin);

		/* Determine T.38 UDPTL destination */
		if (p->udptlredirip.sin_addr.s_addr) {
			udptldest.sin_port = p->udptlredirip.sin_port;
			udptldest.sin_addr = p->udptlredirip.sin_addr;
		} else {
			udptldest.sin_addr = p->ourip.sin_addr;
			udptldest.sin_port = udptlsin.sin_port;
		}

		if (debug)
			ast_debug(1, "T.38 UDPTL is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(udptlsin.sin_port));

		/* We break with the "recommendation" and send our IP, in order that our
		   peer doesn't have to ast_gethostbyname() us */

		ast_str_append(&m_modem, 0, "m=image %d udptl t38\r\n", ntohs(udptldest.sin_port));

		ast_str_append(&a_modem, 0, "a=T38FaxVersion:%d\r\n", p->t38.our_parms.version);
		ast_str_append(&a_modem, 0, "a=T38MaxBitRate:%d\r\n", t38_get_rate(p->t38.our_parms.rate));
		if (p->t38.our_parms.fill_bit_removal) {
			ast_str_append(&a_modem, 0, "a=T38FaxFillBitRemoval\r\n");
		}
		if (p->t38.our_parms.transcoding_mmr) {
			ast_str_append(&a_modem, 0, "a=T38FaxTranscodingMMR\r\n");
		}
		if (p->t38.our_parms.transcoding_jbig) {
			ast_str_append(&a_modem, 0, "a=T38FaxTranscodingJBIG\r\n");
		}
		switch (p->t38.our_parms.rate_management) {
		case AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF:
			ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:transferredTCF\r\n");
			break;
		case AST_T38_RATE_MANAGEMENT_LOCAL_TCF:
			ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:localTCF\r\n");
			break;
		}
		ast_str_append(&a_modem, 0, "a=T38FaxMaxDatagram:%u\r\n", ast_udptl_get_local_max_datagram(p->udptl));
		switch (ast_udptl_get_error_correction_scheme(p->udptl)) {
		case UDPTL_ERROR_CORRECTION_NONE:
			break;
		case UDPTL_ERROR_CORRECTION_FEC:
			ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPFEC\r\n");
			break;
		case UDPTL_ERROR_CORRECTION_REDUNDANCY:
			ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPRedundancy\r\n");
			break;
		}
	}

	if (m_audio->len - m_audio->used < 2 || m_video->len - m_video->used < 2 ||
	    m_text->len - m_text->used < 2 || a_text->len - a_text->used < 2 ||
	    a_audio->len - a_audio->used < 2 || a_video->len - a_video->used < 2)
		ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");

	if (needaudio)
 		ast_str_append(&m_audio, 0, "\r\n");
 	if (needvideo)
 		ast_str_append(&m_video, 0, "\r\n");
 	if (needtext)
 		ast_str_append(&m_text, 0, "\r\n");

 	len = strlen(version) + strlen(subject) + strlen(owner) +
		strlen(connection) + strlen(stime);
	if (needaudio)
		len += m_audio->used + a_audio->used + strlen(hold);
 	if (needvideo) /* only if video response is appropriate */
 		len += m_video->used + a_video->used + strlen(bandwidth) + strlen(hold);
 	if (needtext) /* only if text response is appropriate */
 		len += m_text->used + a_text->used + strlen(hold);
	if (add_t38)
		len += m_modem->used + a_modem->used;

	add_header(resp, "Content-Type", "application/sdp");
	add_header_contentLength(resp, len);
	add_line(resp, version);
	add_line(resp, owner);
	add_line(resp, subject);
	add_line(resp, connection);
	if (needvideo)	 	/* only if video response is appropriate */
		add_line(resp, bandwidth);
	add_line(resp, stime);
	if (needaudio) {
		add_line(resp, m_audio->str);
		add_line(resp, a_audio->str);
		add_line(resp, hold);
	} else if (p->offered_media[SDP_AUDIO].offered) {
		snprintf(dummy_answer, sizeof(dummy_answer), "m=audio 0 RTP/AVP %s\r\n", p->offered_media[SDP_AUDIO].text);
		add_line(resp, dummy_answer);
	}
	if (needvideo) { /* only if video response is appropriate */
		add_line(resp, m_video->str);
		add_line(resp, a_video->str);
		add_line(resp, hold);	/* Repeat hold for the video stream */
	} else if (p->offered_media[SDP_VIDEO].offered) {
		snprintf(dummy_answer, sizeof(dummy_answer), "m=video 0 RTP/AVP %s\r\n", p->offered_media[SDP_VIDEO].text);
		add_line(resp, dummy_answer);
	}
	if (needtext) { /* only if text response is appropriate */
		add_line(resp, m_text->str);
		add_line(resp, a_text->str);
		add_line(resp, hold);	/* Repeat hold for the text stream */
	} else if (p->offered_media[SDP_TEXT].offered) {
		snprintf(dummy_answer, sizeof(dummy_answer), "m=text 0 RTP/AVP %s\r\n", p->offered_media[SDP_TEXT].text);
		add_line(resp, dummy_answer);
	}
	if (add_t38) {
		add_line(resp, m_modem->str);
		add_line(resp, a_modem->str);
	} else if (p->offered_media[SDP_IMAGE].offered) {
		add_line(resp, "m=image 0 udptl t38\r\n");
	}

	/* Update lastrtprx when we send our SDP */
	p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */

	ast_debug(3, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, capability));

	return AST_SUCCESS;
}

/*! \brief Used for 200 OK and 183 early media */
static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
{
	struct sip_request resp;
	int seqno;
	
	if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
		ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
		return -1;
	}
	respprep(&resp, p, msg, req);
	if (p->udptl) {
		add_sdp(&resp, p, 0, 0, 1);
	} else 
		ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
	if (retrans && !p->pendinginvite)
		p->pendinginvite = seqno;		/* Buggy clients sends ACK on RINGING too */
	return send_response(p, &resp, retrans, seqno);
}

/*! \brief copy SIP request (mostly used to save request for responses) */
static void copy_request(struct sip_request *dst, const struct sip_request *src)
{
	long offset;
	int x;
	offset = ((void *)dst) - ((void *)src);
	/* First copy stuff */
	memcpy(dst, src, sizeof(*dst));
	/* Now fix pointer arithmetic */
	for (x=0; x < src->headers; x++)
		dst->header[x] += offset;
	for (x=0; x < src->lines; x++)
		dst->line[x] += offset;
	dst->rlPart1 += offset;
	dst->rlPart2 += offset;
}

/*! \brief Used for 200 OK and 183 early media 
	\return Will return XMIT_ERROR for network errors.
*/
static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp)
{
	struct sip_request resp;
	int seqno;
	if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
		ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
		return -1;
	}
	respprep(&resp, p, msg, req);
	if (p->rtp) {
		if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
			ast_debug(1, "Setting framing from config on incoming call\n");
			ast_rtp_codec_setpref(p->rtp, &p->prefs);
		}
		try_suggested_sip_codec(p);
		if (p->t38.state == T38_ENABLED) {
			add_sdp(&resp, p, oldsdp, TRUE, TRUE);
		} else {
			add_sdp(&resp, p, oldsdp, TRUE, FALSE);
		}
	} else 
		ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
	if (reliable && !p->pendinginvite)
		p->pendinginvite = seqno;		/* Buggy clients sends ACK on RINGING too */
	return send_response(p, &resp, reliable, seqno);
}

/*! \brief Parse first line of incoming SIP request */
static int determine_firstline_parts(struct sip_request *req) 
{
	char *e = ast_skip_blanks(req->header[0]);	/* there shouldn't be any */

	if (!*e)
		return -1;
	req->rlPart1 = e;	/* method or protocol */
	e = ast_skip_nonblanks(e);
	if (*e)
		*e++ = '\0';
	/* Get URI or status code */
	e = ast_skip_blanks(e);
	if ( !*e )
		return -1;
	ast_trim_blanks(e);

	if (!strcasecmp(req->rlPart1, "SIP/2.0") ) { /* We have a response */
		if (strlen(e) < 3)	/* status code is 3 digits */
			return -1;
		req->rlPart2 = e;
	} else { /* We have a request */
		if ( *e == '<' ) { /* XXX the spec says it must not be in <> ! */
			ast_debug(3, "Oops. Bogus uri in <> %s\n", e);
			e++;
			if (!*e)
				return -1; 
		}
		req->rlPart2 = e;	/* URI */
		e = ast_skip_nonblanks(e);
		if (*e)
			*e++ = '\0';
		e = ast_skip_blanks(e);
		if (strcasecmp(e, "SIP/2.0") ) {
			ast_debug(3, "Skipping packet - Bad request protocol %s\n", e);
			return -1;
		}
	}
	return 1;
}

/*! \brief Transmit reinvite with SDP
\note 	A re-invite is basically a new INVITE with the same CALL-ID and TAG as the
	INVITE that opened the SIP dialogue 
	We reinvite so that the audio stream (RTP) go directly between
	the SIP UAs. SIP Signalling stays with * in the path.
	
	If t38version is TRUE, we send T38 SDP for re-invite from audio/video to
	T38 UDPTL transmission on the channel

    If oldsdp is TRUE then the SDP version number is not incremented. This
    is needed for Session-Timers so we can send a re-invite to refresh the
    SIP session without modifying the media session. 
*/
static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp)
{
	struct sip_request req;

	reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ?  SIP_UPDATE : SIP_INVITE, 0, 1);

	add_header(&req, "Allow", ALLOWED_METHODS);
	add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
	if (sipdebug) {
		if (oldsdp == TRUE)
			add_header(&req, "X-asterisk-Info", "SIP re-invite (Session-Timers)");
		else
			add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
	}

	if (p->do_history)
		append_history(p, "ReInv", "Re-invite sent");
	memset(p->offered_media, 0, sizeof(p->offered_media));

	if (t38version)
		add_sdp(&req, p, oldsdp, FALSE, TRUE);
	else
		add_sdp(&req, p, oldsdp, TRUE, FALSE);

	/* Use this as the basis */
	initialize_initreq(p, &req);
	p->lastinvite = p->ocseq;
	ast_set_flag(&p->flags[0], SIP_OUTGOING);       /* Change direction of this dialog */

	return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
}

/* \brief Remove URI parameters at end of URI, not in username part though */
static char *remove_uri_parameters(char *uri)
{
	char *atsign;
	atsign = strchr(uri, '@');	/* First, locate the at sign */
	if (!atsign)
		atsign = uri;	/* Ok hostname only, let's stick with the rest */
	atsign = strchr(atsign, ';');	/* Locate semi colon */
	if (atsign)
		*atsign = '\0';	/* Kill at the semi colon */
	return uri;
}

/*! \brief Check Contact: URI of SIP message */
static void extract_uri(struct sip_pvt *p, struct sip_request *req)
{
	char stripped[SIPBUFSIZE];
	char *c;

	ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
	c = get_in_brackets(stripped);
	/* Cut the URI at the at sign after the @, not in the username part */
	c = remove_uri_parameters(c);
	if (!ast_strlen_zero(c))
		ast_string_field_set(p, uri, c);

}

/*! \brief Build contact header - the contact header we send out */
static void build_contact(struct sip_pvt *p)
{
	int ourport = ntohs(p->ourip.sin_port);
	/* only add port if it's non-standard for the transport type */
	if (!sip_standard_port(p->socket.type, ourport)) {
		if (p->socket.type == SIP_TRANSPORT_UDP)
			ast_string_field_build(p, our_contact, "<sip:%s%s%s:%d>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr), ourport);
		else
			ast_string_field_build(p, our_contact, "<sip:%s%s%s:%d;transport=%s>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr), ourport, get_transport(p->socket.type));
	} else {
		if (p->socket.type == SIP_TRANSPORT_UDP)
			ast_string_field_build(p, our_contact, "<sip:%s%s%s>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr));
		else
			ast_string_field_build(p, our_contact, "<sip:%s%s%s;transport=%s>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr), get_transport(p->socket.type));
	}
}

/*! \brief Build the Remote Party-ID & From using callingpres options */
static void build_rpid(struct sip_pvt *p)
{
	int send_pres_tags = TRUE;
	const char *privacy=NULL;
	const char *screen=NULL;
	char buf[256];
	const char *clid = default_callerid;
	const char *clin = NULL;
	const char *fromdomain;

	if (!ast_strlen_zero(p->rpid) || !ast_strlen_zero(p->rpid_from))  
		return;

	if (p->owner && !ast_strlen_zero(p->owner->cid.cid_num))
		clid = p->owner->cid.cid_num;
	if (p->owner && p->owner->cid.cid_name)
		clin = p->owner->cid.cid_name;
	if (ast_strlen_zero(clin))
		clin = clid;

	switch (p->callingpres) {
	case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
		privacy = "off";
		screen = "no";
		break;
	case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
		privacy = "off";
		screen = "yes";
		break;
	case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
		privacy = "off";
		screen = "no";
		break;
	case AST_PRES_ALLOWED_NETWORK_NUMBER:
		privacy = "off";
		screen = "yes";
		break;
	case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
		privacy = "full";
		screen = "no";
		break;
	case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
		privacy = "full";
		screen = "yes";
		break;
	case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
		privacy = "full";
		screen = "no";
		break;
	case AST_PRES_PROHIB_NETWORK_NUMBER:
		privacy = "full";
		screen = "yes";
		break;
	case AST_PRES_NUMBER_NOT_AVAILABLE:
		send_pres_tags = FALSE;
		break;
	default:
		ast_log(LOG_WARNING, "Unsupported callingpres (%d)\n", p->callingpres);
		if ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)
			privacy = "full";
		else
			privacy = "off";
		screen = "no";
		break;
	}
	
	fromdomain = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip.sin_addr));

	snprintf(buf, sizeof(buf), "\"%s\" <sip:%s@%s>", clin, clid, fromdomain);
	if (send_pres_tags)
		snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ";privacy=%s;screen=%s", privacy, screen);
	ast_string_field_set(p, rpid, buf);

	ast_string_field_build(p, rpid_from, "\"%s\" <sip:%s@%s>;tag=%s", clin,
			       S_OR(p->fromuser, clid),
			       fromdomain, p->tag);
}

/*! \brief Initiate new SIP request to peer/user */
static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod)
{
	struct ast_str *invite = ast_str_alloca(256);
	char from[256];
	char to[256];
	char tmp_n[SIPBUFSIZE/2];	/* build a local copy of 'n' if needed */
	char tmp_l[SIPBUFSIZE/2];	/* build a local copy of 'l' if needed */
	const char *l = NULL;	/* XXX what is this, exactly ? */
	const char *n = NULL;	/* XXX what is this, exactly ? */
	const char *d = NULL;	/* domain in from header */
	const char *urioptions = "";
	int ourport;

	if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
	 	const char *s = p->username;	/* being a string field, cannot be NULL */

		/* Test p->username against allowed characters in AST_DIGIT_ANY
			If it matches the allowed characters list, then sipuser = ";user=phone"
			If not, then sipuser = ""
		*/
		/* + is allowed in first position in a tel: uri */
		if (*s == '+')
			s++;
		for (; *s; s++) {
			if (!strchr(AST_DIGIT_ANYNUM, *s) )
				break;
		}
		/* If we have only digits, add ;user=phone to the uri */
		if (!*s)
			urioptions = ";user=phone";
	}


	snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);

	d = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip.sin_addr));
	if (p->owner) {
		l = p->owner->cid.cid_num;
		n = p->owner->cid.cid_name;
	}
	/* if we are not sending RPID and user wants his callerid restricted */
	if (!ast_test_flag(&p->flags[0], SIP_SENDRPID) &&
	    ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)) {
		l = CALLERID_UNKNOWN;
		n = l;
		d = FROMDOMAIN_INVALID;
	}
	if (ast_strlen_zero(l))
		l = default_callerid;
	if (ast_strlen_zero(n))
		n = l;
	/* Allow user to be overridden */
	if (!ast_strlen_zero(p->fromuser))
		l = p->fromuser;
	else /* Save for any further attempts */
		ast_string_field_set(p, fromuser, l);

	/* Allow user to be overridden */
	if (!ast_strlen_zero(p->fromname))
		n = p->fromname;
	else /* Save for any further attempts */
		ast_string_field_set(p, fromname, n);

	if (pedanticsipchecking) {
		ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
		n = tmp_n;
		ast_uri_encode(l, tmp_l, sizeof(tmp_l), 0);
		l = tmp_l;
	}

	ourport = ntohs(p->ourip.sin_port);
	if (!sip_standard_port(p->socket.type, ourport) && ast_strlen_zero(p->fromdomain))
		snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=%s", n, l, d, ourport, p->tag);
	else
		snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, l, d, p->tag);

	/* If we're calling a registered SIP peer, use the fullcontact to dial to the peer */
	if (!ast_strlen_zero(p->fullcontact)) {
		/* If we have full contact, trust it */
		ast_str_append(&invite, 0, "%s", p->fullcontact);
	} else {
		/* Otherwise, use the username while waiting for registration */
		ast_str_append(&invite, 0, "sip:");
		if (!ast_strlen_zero(p->username)) {
			n = p->username;
			if (pedanticsipchecking) {
				ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
				n = tmp_n;
			}
			ast_str_append(&invite, 0, "%s@", n);
		}
		ast_str_append(&invite, 0, "%s", p->tohost);
		if (p->portinuri)
			ast_str_append(&invite, 0, ":%d", ntohs(p->sa.sin_port));
		ast_str_append(&invite, 0, "%s", urioptions);
	}

	/* If custom URI options have been provided, append them */
	if (p->options && !ast_strlen_zero(p->options->uri_options))
		ast_str_append(&invite, 0, ";%s", p->options->uri_options);
	
 	/* This is the request URI, which is the next hop of the call
 		which may or may not be the destination of the call
 	*/
	ast_string_field_set(p, uri, invite->str);
  
 	if (!ast_strlen_zero(p->todnid)) {
 		/*! \todo Need to add back the VXML URL here at some point, possibly use build_string for all this junk */
 		if (!strchr(p->todnid, '@')) {
 			/* We have no domain in the dnid */
 			snprintf(to, sizeof(to), "<sip:%s@%s>%s%s", p->todnid, p->tohost, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
 		} else {
 			snprintf(to, sizeof(to), "<sip:%s>%s%s", p->todnid, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
 		}
 	} else {
 		if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) { 
 			/* If this is a NOTIFY, use the From: tag in the subscribe (RFC 3265) */
			snprintf(to, sizeof(to), "<%s%s>;tag=%s", (!strncasecmp(p->uri, "sip:", 4) ? "" : "sip:"), p->uri, p->theirtag);
 		} else if (p->options && p->options->vxml_url) {
 			/* If there is a VXML URL append it to the SIP URL */
 			snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
 		} else 
 			snprintf(to, sizeof(to), "<%s>", p->uri);
 	}

	init_req(req, sipmethod, p->uri);
	/* now tmp_n is available so reuse it to build the CSeq */
	snprintf(tmp_n, sizeof(tmp_n), "%d %s", ++p->ocseq, sip_methods[sipmethod].text);

	add_header(req, "Via", p->via);
	add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
	/* This will be a no-op most of the time. However, under certain circumstances,
	 * NOTIFY messages will use this function for preparing the request and should
	 * have Route headers present.
	 */
	add_route(req, p->route);

	/* Build Remote Party-ID and From */
	if (ast_test_flag(&p->flags[0], SIP_SENDRPID) && (sipmethod == SIP_INVITE)) {
		build_rpid(p);
		add_header(req, "From", p->rpid_from);
	} else 
		add_header(req, "From", from);
	add_header(req, "To", to);
	ast_string_field_set(p, exten, l);
	build_contact(p);
	add_header(req, "Contact", p->our_contact);
	add_header(req, "Call-ID", p->callid);
	add_header(req, "CSeq", tmp_n);
	if (!ast_strlen_zero(global_useragent))
		add_header(req, "User-Agent", global_useragent);
	if (!ast_strlen_zero(p->rpid))
		add_header(req, "Remote-Party-ID", p->rpid);
}

/*! \brief Build REFER/INVITE/OPTIONS message and transmit it 
	\param init 0 = Prepare request within dialog, 1= prepare request, new branch, 2= prepare new request and new dialog. do_proxy_auth calls this with init!=2
 \param p sip_pvt structure
 \param sdp unknown 
 \param sipmethod unknown 
 
*/
static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init)
{
	struct sip_request req;
	
	req.method = sipmethod;
	if (init) {/* Bump branch even on initial requests */
		p->branch ^= ast_random();
		p->invite_branch = p->branch;
		build_via(p);
	}
	if (init > 1)
		initreqprep(&req, p, sipmethod);
	else
		/* If init=1, we should not generate a new branch. If it's 0, we need a new branch. */
		reqprep(&req, p, sipmethod, 0, init ? 0 : 1);
		
	if (p->options && p->options->auth)
		add_header(&req, p->options->authheader, p->options->auth);
	append_date(&req);
	if (sipmethod == SIP_REFER) {	/* Call transfer */
		if (p->refer) {
			char buf[SIPBUFSIZE];
			if (!ast_strlen_zero(p->refer->refer_to))
				add_header(&req, "Refer-To", p->refer->refer_to);
			if (!ast_strlen_zero(p->refer->referred_by)) {
				snprintf(buf, sizeof(buf), "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
				add_header(&req, "Referred-By", buf);
			}
		}
	}
	/* This new INVITE is part of an attended transfer. Make sure that the
	other end knows and replace the current call with this new call */
	if (p->options && !ast_strlen_zero(p->options->replaces)) {
		add_header(&req, "Replaces", p->options->replaces);
		add_header(&req, "Require", "replaces");
	}

	/* Add Session-Timers related headers */
	if (st_get_mode(p) == SESSION_TIMER_MODE_ORIGINATE) {
		char i2astr[10];

		if (!p->stimer->st_interval)
			p->stimer->st_interval = st_get_se(p, TRUE);

		p->stimer->st_active = TRUE;
		
		snprintf(i2astr, sizeof(i2astr), "%d", p->stimer->st_interval);
		add_header(&req, "Session-Expires", i2astr);
		snprintf(i2astr, sizeof(i2astr), "%d", st_get_se(p, FALSE));
		add_header(&req, "Min-SE", i2astr);
	}

	add_header(&req, "Allow", ALLOWED_METHODS);
	add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
	if (p->options && p->options->addsipheaders && p->owner) {
		struct ast_channel *chan = p->owner; /* The owner channel */
		struct varshead *headp;
	
		ast_channel_lock(chan);

		headp = &chan->varshead;

		if (!headp)
			ast_log(LOG_WARNING, "No Headp for the channel...ooops!\n");
		else {
			const struct ast_var_t *current;
			AST_LIST_TRAVERSE(headp, current, entries) {  
				/* SIPADDHEADER: Add SIP header to outgoing call */
				if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
					char *content, *end;
					const char *header = ast_var_value(current);
					char *headdup = ast_strdupa(header);

					/* Strip of the starting " (if it's there) */
					if (*headdup == '"')
				 		headdup++;
					if ((content = strchr(headdup, ':'))) {
						*content++ = '\0';
						content = ast_skip_blanks(content); /* Skip white space */
						/* Strip the ending " (if it's there) */
				 		end = content + strlen(content) -1;	
						if (*end == '"')
							*end = '\0';
					
						add_header(&req, headdup, content);
						if (sipdebug)
							ast_debug(1, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
					}
				}
			}
		}

		ast_channel_unlock(chan);
	}
	if (sdp) {
		memset(p->offered_media, 0, sizeof(p->offered_media));
		if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
			ast_debug(1, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
			add_sdp(&req, p, FALSE, FALSE, TRUE);
		} else if (p->rtp) 
			add_sdp(&req, p, FALSE, TRUE, FALSE);
	} else {
		add_header_contentLength(&req, 0);
	}

	if (!p->initreq.headers || init > 2)
		initialize_initreq(p, &req);
	p->lastinvite = p->ocseq;
	return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
}

/*! \brief Used in the SUBSCRIBE notification subsystem */
static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout)
{
	struct ast_str *tmp = ast_str_alloca(4000);
	char from[256], to[256];
	char *c, *mfrom, *mto;
	struct sip_request req;
	char hint[AST_MAX_EXTENSION];
	char *statestring = "terminated";
	const struct cfsubscription_types *subscriptiontype;
	enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
	char *pidfstate = "--";
	char *pidfnote= "Ready";

	memset(from, 0, sizeof(from));
	memset(to, 0, sizeof(to));

	switch (state) {
	case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
		statestring = (global_notifyringing) ? "early" : "confirmed";
		local_state = NOTIFY_INUSE;
		pidfstate = "busy";
		pidfnote = "Ringing";
		break;
	case AST_EXTENSION_RINGING:
		statestring = "early";
		local_state = NOTIFY_INUSE;
		pidfstate = "busy";
		pidfnote = "Ringing";
		break;
	case AST_EXTENSION_INUSE:
		statestring = "confirmed";
		local_state = NOTIFY_INUSE;
		pidfstate = "busy";
		pidfnote = "On the phone";
		break;
	case AST_EXTENSION_BUSY:
		statestring = "confirmed";
		local_state = NOTIFY_CLOSED;
		pidfstate = "busy";
		pidfnote = "On the phone";
		break;
	case AST_EXTENSION_UNAVAILABLE:
		statestring = "terminated";
		local_state = NOTIFY_CLOSED;
		pidfstate = "away";
		pidfnote = "Unavailable";
		break;
	case AST_EXTENSION_ONHOLD:
		statestring = "confirmed";
		local_state = NOTIFY_CLOSED;
		pidfstate = "busy";
		pidfnote = "On hold";
		break;
	case AST_EXTENSION_NOT_INUSE:
	default:
		/* Default setting */
		break;
	}

	subscriptiontype = find_subscription_type(p->subscribed);
	
	/* Check which device/devices we are watching  and if they are registered */
	if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten)) {
		char *hint2 = hint, *individual_hint = NULL;
		int hint_count = 0, unavailable_count = 0;

		while ((individual_hint = strsep(&hint2, "&"))) {
			hint_count++;

			if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
				unavailable_count++;
		}

		/* If none of the hinted devices are registered, we will
		 * override notification and show no availability.
		 */
		if (hint_count > 0 && hint_count == unavailable_count) {
			local_state = NOTIFY_CLOSED;
			pidfstate = "away";
			pidfnote = "Not online";
		}
	}

	ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
	c = get_in_brackets(from);
	if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
		ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
		return -1;
	}
	
	mfrom = remove_uri_parameters(c);

	ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
	c = get_in_brackets(to);
	if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
		ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
		return -1;
	}
	mto = remove_uri_parameters(c);

	reqprep(&req, p, SIP_NOTIFY, 0, 1);

	
	add_header(&req, "Event", subscriptiontype->event);
	add_header(&req, "Content-Type", subscriptiontype->mediatype);
	switch(state) {
	case AST_EXTENSION_DEACTIVATED:
		if (timeout)
			add_header(&req, "Subscription-State", "terminated;reason=timeout");
		else {
			add_header(&req, "Subscription-State", "terminated;reason=probation");
			add_header(&req, "Retry-After", "60");
		}
		break;
	case AST_EXTENSION_REMOVED:
		add_header(&req, "Subscription-State", "terminated;reason=noresource");
		break;
	default:
		if (p->expiry)
			add_header(&req, "Subscription-State", "active");
		else	/* Expired */
			add_header(&req, "Subscription-State", "terminated;reason=timeout");
	}
	switch (p->subscribed) {
	case XPIDF_XML:
	case CPIM_PIDF_XML:
		ast_str_append(&tmp, 0,
			"<?xml version=\"1.0\"?>\n"
			"<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n"
			"<presence>\n");
		ast_str_append(&tmp, 0, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
		ast_str_append(&tmp, 0, "<atom id=\"%s\">\n", p->exten);
		ast_str_append(&tmp, 0, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
		ast_str_append(&tmp, 0, "<status status=\"%s\" />\n", (local_state ==  NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
		ast_str_append(&tmp, 0, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
		ast_str_append(&tmp, 0, "</address>\n</atom>\n</presence>\n");
		break;
	case PIDF_XML: /* Eyebeam supports this format */
		ast_str_append(&tmp, 0,
			"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
			"<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" \nxmlns:pp=\"urn:ietf:params:xml:ns:pidf:person\"\nxmlns:es=\"urn:ietf:params:xml:ns:pidf:rpid:status:rpid-status\"\nxmlns:ep=\"urn:ietf:params:xml:ns:pidf:rpid:rpid-person\"\nentity=\"%s\">\n", mfrom);
		ast_str_append(&tmp, 0, "<pp:person><status>\n");
		if (pidfstate[0] != '-')
			ast_str_append(&tmp, 0, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
		ast_str_append(&tmp, 0, "</status></pp:person>\n");
		ast_str_append(&tmp, 0, "<note>%s</note>\n", pidfnote); /* Note */
		ast_str_append(&tmp, 0, "<tuple id=\"%s\">\n", p->exten); /* Tuple start */
		ast_str_append(&tmp, 0, "<contact priority=\"1\">%s</contact>\n", mto);
		if (pidfstate[0] == 'b') /* Busy? Still open ... */
			ast_str_append(&tmp, 0, "<status><basic>open</basic></status>\n");
		else
			ast_str_append(&tmp, 0, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
		ast_str_append(&tmp, 0, "</tuple>\n</presence>\n");
		break;
	case DIALOG_INFO_XML: /* SNOM subscribes in this format */
		ast_str_append(&tmp, 0, "<?xml version=\"1.0\"?>\n");
		ast_str_append(&tmp, 0, "<dialog-info xmlns=\"urn:ietf:params:xml:ns:dialog-info\" version=\"%d\" state=\"%s\" entity=\"%s\">\n", p->dialogver++, full ? "full":"partial", mto);
		if ((state & AST_EXTENSION_RINGING) && global_notifyringing)
			ast_str_append(&tmp, 0, "<dialog id=\"%s\" direction=\"recipient\">\n", p->exten);
		else
			ast_str_append(&tmp, 0, "<dialog id=\"%s\">\n", p->exten);
		ast_str_append(&tmp, 0, "<state>%s</state>\n", statestring);
		if (state == AST_EXTENSION_ONHOLD) {
			ast_str_append(&tmp, 0, "<local>\n<target uri=\"%s\">\n"
			                                "<param pname=\"+sip.rendering\" pvalue=\"no\"/>\n"
			                                "</target>\n</local>\n", mto);
		}
		ast_str_append(&tmp, 0, "</dialog>\n</dialog-info>\n");
		break;
	case NONE:
	default:
		break;
	}

	add_header_contentLength(&req, tmp->used);
	add_line(&req, tmp->str);

	p->pendinginvite = p->ocseq;	/* Remember that we have a pending NOTIFY in order not to confuse the NOTIFY subsystem */

	return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
}

/*! \brief Notify user of messages waiting in voicemail
\note	- Notification only works for registered peers with mailbox= definitions
	in sip.conf
	- We use the SIP Event package message-summary
	 MIME type defaults to  "application/simple-message-summary";
 */
static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten)
{
	struct sip_request req;
	struct ast_str *out = ast_str_alloca(500);
	int ourport = ntohs(p->ourip.sin_port);
	const char *exten = S_OR(vmexten, default_vmexten);

	initreqprep(&req, p, SIP_NOTIFY);
	add_header(&req, "Event", "message-summary");
	add_header(&req, "Content-Type", default_notifymime);
	ast_str_append(&out, 0, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");

	if (!ast_strlen_zero(p->fromdomain)) {
		ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, p->fromdomain);
	} else if (!sip_standard_port(p->socket.type, ourport)) {
		if (p->socket.type == SIP_TRANSPORT_UDP) {
			ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr), ourport);
		} else {
			ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d;transport=%s\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr), ourport, get_transport(p->socket.type));
		}
	} else {
		if (p->socket.type == SIP_TRANSPORT_UDP) {
			ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr));
		} else {
			ast_str_append(&out, 0, "Message-Account: sip:%s@%s;transport=%s\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr), get_transport(p->socket.type));
		}
	}
	/* Cisco has a bug in the SIP stack where it can't accept the
		(0/0) notification. This can temporarily be disabled in
		sip.conf with the "buggymwi" option */
	ast_str_append(&out, 0, "Voice-Message: %d/%d%s\r\n",
		newmsgs, oldmsgs, (ast_test_flag(&p->flags[1], SIP_PAGE2_BUGGY_MWI) ? "" : " (0/0)"));

	if (p->subscribed) {
		if (p->expiry)
			add_header(&req, "Subscription-State", "active");
		else	/* Expired */
			add_header(&req, "Subscription-State", "terminated;reason=timeout");
	}

	add_header_contentLength(&req, out->used);
	add_line(&req, out->str);

	if (!p->initreq.headers) 
		initialize_initreq(p, &req);
	return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
}

/*! \brief Transmit SIP request unreliably (only used in sip_notify subsystem) */
static int transmit_sip_request(struct sip_pvt *p, struct sip_request *req)
{
	if (!p->initreq.headers) 	/* Initialize first request before sending */
		initialize_initreq(p, req);
	return send_request(p, req, XMIT_UNRELIABLE, p->ocseq);
}

/*! \brief Notify a transferring party of the status of transfer */
static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
{
	struct sip_request req;
	char tmp[SIPBUFSIZE/2];

	reqprep(&req, p, SIP_NOTIFY, 0, 1);
	snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
	add_header(&req, "Event", tmp);
	add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
	add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
	add_header(&req, "Allow", ALLOWED_METHODS);
	add_header(&req, "Supported", SUPPORTED_EXTENSIONS);

	snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
	add_header_contentLength(&req, strlen(tmp));
	add_line(&req, tmp);

	if (!p->initreq.headers)
		initialize_initreq(p, &req);

	return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
}

static const struct _map_x_s regstatestrings[] = {
	{ REG_STATE_FAILED,     "Failed" },
	{ REG_STATE_UNREGISTERED, "Unregistered"},
	{ REG_STATE_REGSENT, "Request Sent"},
	{ REG_STATE_AUTHSENT, "Auth. Sent"},
	{ REG_STATE_REGISTERED, "Registered"},
	{ REG_STATE_REJECTED, "Rejected"},
	{ REG_STATE_TIMEOUT, "Timeout"},
	{ REG_STATE_NOAUTH, "No Authentication"},
	{ -1, NULL } /* terminator */
};

/*! \brief Convert registration state status to string */
static const char *regstate2str(enum sipregistrystate regstate)
{
	return map_x_s(regstatestrings, regstate, "Unknown");
}

/*! \brief Update registration with SIP Proxy.
 * Called from the scheduler when the previous registration expires,
 * so we don't have to cancel the pending event.
 * We assume the reference so the sip_registry is valid, since it
 * is stored in the scheduled event anyways.
 */
static int sip_reregister(const void *data) 
{
	/* if we are here, we know that we need to reregister. */
	struct sip_registry *r= registry_addref((struct sip_registry *) data);

	/* if we couldn't get a reference to the registry object, punt */
	if (!r)
		return 0;

	if (r->call && r->call->do_history)
		append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
	/* Since registry's are only added/removed by the the monitor thread, this
	   may be overkill to reference/dereference at all here */
	if (sipdebug)
		ast_log(LOG_NOTICE, "   -- Re-registration for  %s@%s\n", r->username, r->hostname);

	r->expire = -1;
	r->expiry = r->configured_expiry;
	__sip_do_register(r);
	registry_unref(r);
	return 0;
}

/*! \brief Register with SIP proxy */
static int __sip_do_register(struct sip_registry *r)
{
	int res;

	res = transmit_register(r, SIP_REGISTER, NULL, NULL);
	return res;
}

/*! \brief Registration timeout, register again
 * Registered as a timeout handler during transmit_register(),
 * to retransmit the packet if a reply does not come back.
 * This is called by the scheduler so the event is not pending anymore when
 * we are called.
 */
static int sip_reg_timeout(const void *data)
{

	/* if we are here, our registration timed out, so we'll just do it over */
	struct sip_registry *r = registry_addref((struct sip_registry *) data);
	struct sip_pvt *p;
	int res;

	/* if we couldn't get a reference to the registry object, punt */
	if (!r)
		return 0;

	ast_log(LOG_NOTICE, "   -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts); 
	/* If the initial tranmission failed, we may not have an existing dialog,
	 * so it is possible that r->call == NULL.
	 * Otherwise destroy it, as we have a timeout so we don't want it.
	 */
	if (r->call) {
		/* Unlink us, destroy old call.  Locking is not relevant here because all this happens
		   in the single SIP manager thread. */
		p = r->call;
		sip_pvt_lock(p);
		p->needdestroy = 1;
		/* Pretend to ACK anything just in case */
		__sip_pretend_ack(p);
		sip_pvt_unlock(p);

		/* decouple the two objects */
		/* p->registry == r, so r has 2 refs, and the unref won't take the object away */
		if (p->registry)
			p->registry = registry_unref(p->registry);
		r->call = NULL;
	}
	/* If we have a limit, stop registration and give up */
	if (global_regattempts_max && r->regattempts > global_regattempts_max) {
		/* Ok, enough is enough. Don't try any more */
		/* We could add an external notification here... 
			steal it from app_voicemail :-) */
		ast_log(LOG_NOTICE, "   -- Giving up forever trying to register '%s@%s'\n", r->username, r->hostname);
		r->regstate = REG_STATE_FAILED;
	} else {
		r->regstate = REG_STATE_UNREGISTERED;
		r->timeout = -1;
		res=transmit_register(r, SIP_REGISTER, NULL, NULL);
	}
	manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nUsername: %s\r\nDomain: %s\r\nStatus: %s\r\n", r->username, r->hostname, regstate2str(r->regstate));
	registry_unref(r);
	return 0;
}

/*! \brief Transmit register to SIP proxy or UA
 * auth = NULL on the initial registration (from sip_reregister())
 */
static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
{
	struct sip_request req;
	char from[256];
	char to[256];
	char tmp[80];
	char addr[80];
	struct sip_pvt *p;
	char *fromdomain;
	char *domainport = NULL;

	/* exit if we are already in process with this registrar ?*/
	if ( r == NULL || ((auth==NULL) && (r->regstate==REG_STATE_REGSENT || r->regstate==REG_STATE_AUTHSENT))) {
		if (r) {
			ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
		}
		return 0;
	}

	if (r->call) {	/* We have a registration */
		if (!auth) {
			ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
			return 0;
		} else {
			p = r->call;
			make_our_tag(p->tag, sizeof(p->tag));	/* create a new local tag for every register attempt */
			ast_string_field_set(p, theirtag, NULL);	/* forget their old tag, so we don't match tags when getting response */
		}
	} else {
		/* Build callid for registration if we haven't registered before */
		struct sip_peer *peer = NULL;

		if (!r->callid_valid) {
			build_callid_registry(r, internip.sin_addr, default_fromdomain);
			r->callid_valid = TRUE;
		}
		/* Allocate SIP dialog for registration */
		if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER, NULL))) {
			ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
			return 0;
		}

		if (p->do_history)
			append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);

		if (!ast_strlen_zero(r->peername)) {
			if (!(peer = find_peer(r->peername, NULL, 1, 0, 0))) {
				ast_log(LOG_WARNING, "Could not find peer %s in transmit_register\n", r->peername);
			} else {
				p->peerauth = peer->auth;
			}
		}
		obproxy_get(p, peer); /* it is ok to pass a NULL peer into obproxy_get() */

		p->outboundproxy = obproxy_get(p, NULL);

		/* Find address to hostname */
		if (create_addr(p, r->hostname, 0)) {
			/* we have what we hope is a temporary network error,
			 * probably DNS.  We need to reschedule a registration try */
			dialog_cleanup_and_destroy(p); /*sip_destroy(p);*/
			if (r->timeout > -1) {
				AST_SCHED_REPLACE(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r);
				ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
			} else {
				r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, r);
				ast_log(LOG_WARNING, "Probably a DNS error for registration to %s@%s, trying REGISTER again (after %d seconds)\n", r->username, r->hostname, global_reg_timeout);
			}
			r->regattempts++;
			return 0;
		}
		/* Copy back Call-ID in case create_addr changed it */
		ast_string_field_set(r, callid, p->callid);
		if (r->portno) {
			p->sa.sin_port = htons(r->portno);
 			p->recv.sin_port = htons(r->portno);
		} else {	/* Set registry port to the port set from the peer definition/srv or default */
			r->portno = ntohs(p->sa.sin_port);
		}
		ast_set_flag(&p->flags[0], SIP_OUTGOING);	/* Registration is outgoing call */
		r->call = p;		/* Save pointer to SIP dialog */
		p->registry = registry_addref(r);	/* Add pointer to registry in packet */
		if (!ast_strlen_zero(r->secret))	/* Secret (password) */
			ast_string_field_set(p, peersecret, r->secret);
		if (!ast_strlen_zero(r->md5secret))
			ast_string_field_set(p, peermd5secret, r->md5secret);
		/* User name in this realm  
		- if authuser is set, use that, otherwise use username */
		if (!ast_strlen_zero(r->authuser)) {	
			ast_string_field_set(p, peername, r->authuser);
			ast_string_field_set(p, authname, r->authuser);
		} else if (!ast_strlen_zero(r->username)) {
			ast_string_field_set(p, peername, r->username);
			ast_string_field_set(p, authname, r->username);
			ast_string_field_set(p, fromuser, r->username);
		}
		if (!ast_strlen_zero(r->username))
			ast_string_field_set(p, username, r->username);
		/* Save extension in packet */
		if (!ast_strlen_zero(r->callback))
			ast_string_field_set(p, exten, r->callback);

		/* Set transport and port so the correct contact is built */
		set_socket_transport(&p->socket, r->transport);
		if (r->transport == SIP_TRANSPORT_TLS || r->transport == SIP_TRANSPORT_TCP) {
			p->socket.port = sip_tcp_desc.sin.sin_port;
		}
		/*
		  check which address we should use in our contact header 
		  based on whether the remote host is on the external or
		  internal network so we can register through nat
		 */
		ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
		build_contact(p);
	}

	/* set up a timeout */
	if (auth == NULL)  {
		if (r->timeout > -1)
			ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
		AST_SCHED_REPLACE(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r);
		ast_debug(1, "Scheduled a registration timeout for %s id  #%d \n", r->hostname, r->timeout);
	}

	if ((fromdomain = strchr(r->username, '@'))) {
		/* the domain name is just behind '@' */
		fromdomain++ ;
		/* We have a domain in the username for registration */
		snprintf(from, sizeof(from), "<sip:%s>;tag=%s", r->username, p->tag);
		if (!ast_strlen_zero(p->theirtag))
			snprintf(to, sizeof(to), "<sip:%s>;tag=%s", r->username, p->theirtag);
		else
			snprintf(to, sizeof(to), "<sip:%s>", r->username);

		/* If the registration username contains '@', then the domain should be used as
		   the equivalent of "fromdomain" for the registration */
		if (ast_strlen_zero(p->fromdomain)) {
			ast_string_field_set(p, fromdomain, fromdomain);
		}
	} else {
		snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->tag);
		if (!ast_strlen_zero(p->theirtag))
			snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->theirtag);
		else
			snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, p->tohost);
	}

	/* Fromdomain is what we are registering to, regardless of actual
  	   host name from SRV */
	if (!ast_strlen_zero(p->fromdomain)) {
		domainport = strrchr(p->fromdomain, ':');
		if (domainport) {
			*domainport++ = '\0'; /* trim off domainport from p->fromdomain */
			if (ast_strlen_zero(domainport))
				domainport = NULL;
		}
		if (domainport) {
			if (atoi(domainport) != STANDARD_SIP_PORT)
				snprintf(addr, sizeof(addr), "sip:%s:%s", p->fromdomain, domainport);
			else
				snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
		} else {
			if (r->portno && r->portno != STANDARD_SIP_PORT)
				snprintf(addr, sizeof(addr), "sip:%s:%d", p->fromdomain, r->portno);
			else
				snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
		}
	} else {
		if (r->portno && r->portno != STANDARD_SIP_PORT)
			snprintf(addr, sizeof(addr), "sip:%s:%d", r->hostname, r->portno);
		else
			snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
	}
	ast_string_field_set(p, uri, addr);

	p->branch ^= ast_random();

	init_req(&req, sipmethod, addr);

	/* Add to CSEQ */
	snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
	p->ocseq = r->ocseq;

	build_via(p);
	add_header(&req, "Via", p->via);
	add_header(&req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
	add_header(&req, "From", from);
	add_header(&req, "To", to);
	add_header(&req, "Call-ID", p->callid);
	add_header(&req, "CSeq", tmp);
	if (!ast_strlen_zero(global_useragent))
		add_header(&req, "User-Agent", global_useragent);

	if (auth) 	/* Add auth header */
		add_header(&req, authheader, auth);
	else if (!ast_strlen_zero(r->nonce)) {
		char digest[1024];

		/* We have auth data to reuse, build a digest header.
		 * Note, this is not always useful because some parties do not
		 * like nonces to be reused (for good reasons!) so they will
		 * challenge us anyways.
		 */
		if (sipdebug)
			ast_debug(1, "   >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
		ast_string_field_set(p, realm, r->realm);
		ast_string_field_set(p, nonce, r->nonce);
		ast_string_field_set(p, domain, r->domain);
		ast_string_field_set(p, opaque, r->opaque);
		ast_string_field_set(p, qop, r->qop);
		p->noncecount = ++r->noncecount;

		memset(digest, 0, sizeof(digest));
		if(!build_reply_digest(p, sipmethod, digest, sizeof(digest)))
			add_header(&req, "Authorization", digest);
		else
			ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
	
	}

	snprintf(tmp, sizeof(tmp), "%d", r->expiry);
	add_header(&req, "Expires", tmp);
	add_header(&req, "Contact", p->our_contact);
	add_header(&req, "Event", "registration");
	add_header_contentLength(&req, 0);

	initialize_initreq(p, &req);
	if (sip_debug_test_pvt(p)) {
		ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
	}
	r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
	r->regattempts++;	/* Another attempt */
	ast_debug(4, "REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);

	return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
}

/*! \brief Transmit text with SIP MESSAGE method */
static int transmit_message_with_text(struct sip_pvt *p, const char *text)
{
	struct sip_request req;

	reqprep(&req, p, SIP_MESSAGE, 0, 1);
	add_text(&req, text);
	return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
}

/*! \brief Allocate SIP refer structure */
static int sip_refer_allocate(struct sip_pvt *p)
{
	p->refer = ast_calloc(1, sizeof(struct sip_refer)); 
	return p->refer ? 1 : 0;
}

/*! \brief Transmit SIP REFER message (initiated by the transfer() dialplan application
	\note this is currently broken as we have no way of telling the dialplan
	engine whether a transfer succeeds or fails.
	\todo Fix the transfer() dialplan function so that a transfer may fail
*/
static int transmit_refer(struct sip_pvt *p, const char *dest)
{
	struct sip_request req = { 
		.headers = 0,	
	};
	char from[256];
	const char *of;
	char *c;
	char referto[256];
	char *ttag, *ftag;
	char *theirtag = ast_strdupa(p->theirtag);

	if (sipdebug)
		ast_debug(1, "SIP transfer of %s to %s\n", p->callid, dest);

	/* Are we transfering an inbound or outbound call ? */
	if (ast_test_flag(&p->flags[0], SIP_OUTGOING))  {
		of = get_header(&p->initreq, "To");
		ttag = theirtag;
		ftag = p->tag;
	} else {
		of = get_header(&p->initreq, "From");
		ftag = theirtag;
		ttag = p->tag;
	}

	ast_copy_string(from, of, sizeof(from));
	of = get_in_brackets(from);
	ast_string_field_set(p, from, of);
	if (!strncasecmp(of, "sip:", 4))
		of += 4;
	else if (!strncasecmp(of, "sips:", 5))
		of += 5;
	else
		ast_log(LOG_NOTICE, "From address missing 'sip(s):', using it anyway\n");
	/* Get just the username part */
	if ((c = strchr(dest, '@')))
		c = NULL;
	else if ((c = strchr(of, '@')))
		*c++ = '\0';
	if (c) 
		snprintf(referto, sizeof(referto), "<sip:%s@%s>", dest, c);
	else
		snprintf(referto, sizeof(referto), "<sip:%s>", dest);

	/* save in case we get 407 challenge */
	sip_refer_allocate(p);
	ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
	ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
	p->refer->status = REFER_SENT;   /* Set refer status */

	reqprep(&req, p, SIP_REFER, 0, 1);

	add_header(&req, "Refer-To", referto);
	add_header(&req, "Allow", ALLOWED_METHODS);
	add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
	if (!ast_strlen_zero(p->our_contact))
		add_header(&req, "Referred-By", p->our_contact);

	return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
	/* We should propably wait for a NOTIFY here until we ack the transfer */
	/* Maybe fork a new thread and wait for a STATUS of REFER_200OK on the refer status before returning to app_transfer */

	/*! \todo In theory, we should hang around and wait for a reply, before
	returning to the dial plan here. Don't know really how that would
	affect the transfer() app or the pbx, but, well, to make this
	useful we should have a STATUS code on transfer().
	*/
}


/*! \brief Send SIP INFO dtmf message, see Cisco documentation on cisco.com */
static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
{
	struct sip_request req;

	reqprep(&req, p, SIP_INFO, 0, 1);
	add_digit(&req, digit, duration, (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO));
	return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
}

/*! \brief Send SIP INFO with video update request */
static int transmit_info_with_vidupdate(struct sip_pvt *p)
{
	struct sip_request req;

	reqprep(&req, p, SIP_INFO, 0, 1);
	add_vidupdate(&req);
	return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
}

/*! \brief Transmit generic SIP request 
	returns XMIT_ERROR if transmit failed with a critical error (don't retry)
*/
static int transmit_request(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
{
	struct sip_request resp;

	if (sipmethod == SIP_ACK)
		p->invitestate = INV_CONFIRMED;

	reqprep(&resp, p, sipmethod, seqno, newbranch);
	if (sipmethod == SIP_CANCEL && p->answered_elsewhere) 
		add_header(&resp, "Reason", "SIP;cause=200;text=\"Call completed elsewhere\"");

	add_header_contentLength(&resp, 0);
	return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
}

/*! \brief return the request and response heade for a 401 or 407 code */
static void auth_headers(enum sip_auth_type code, char **header, char **respheader)
{
	if (code == WWW_AUTH) {			/* 401 */
		*header = "WWW-Authenticate";
		*respheader = "Authorization";
	} else if (code == PROXY_AUTH) {	/* 407 */
		*header = "Proxy-Authenticate";
		*respheader = "Proxy-Authorization";
	} else {
		ast_verbose("-- wrong response code %d\n", code);
		*header = *respheader = "Invalid";
	}
}

/*! \brief Transmit SIP request, auth added */
static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
{
	struct sip_request resp;

	reqprep(&resp, p, sipmethod, seqno, newbranch);
	if (!ast_strlen_zero(p->realm)) {
		char digest[1024];

		memset(digest, 0, sizeof(digest));
		if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
			char *dummy, *response;
			enum sip_auth_type code = p->options ? p->options->auth_type : PROXY_AUTH; /* XXX force 407 if unknown */
			auth_headers(code, &dummy, &response);
			add_header(&resp, response, digest);
		} else
			ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
	}
	/* If we are hanging up and know a cause for that, send it in clear text to make
		debugging easier. */
	if (sipmethod == SIP_BYE)	{
		char buf[10];

		add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->hangupcause));
		snprintf(buf, sizeof(buf), "%d", p->hangupcause);
		add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
	}

	add_header_contentLength(&resp, 0);
	return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);	
}

/*! \brief Remove registration data from realtime database or AST/DB when registration expires */
static void destroy_association(struct sip_peer *peer)
{
	int realtimeregs = ast_check_realtime("sipregs");
	char *tablename = (realtimeregs) ? "sipregs" : "sippeers";

	if (!sip_cfg.ignore_regexpire) {
		if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
			ast_update_realtime(tablename, "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", peer->deprecated_username ? "username" : "defaultuser", "", "regserver", "", NULL);
			ast_update_realtime(tablename, "name", peer->name, "lastms", "", NULL);
		} else {
			ast_db_del("SIP/Registry", peer->name);
		}
	}
}
static void set_socket_transport(struct sip_socket *socket, int transport)
{
	/* if the transport type changes, clear all socket data */
	if (socket->type != transport) {
		socket->fd = -1;
		socket->type = transport;
		if (socket->tcptls_session) {
			ao2_ref(socket->tcptls_session, -1);
			socket->tcptls_session = NULL;
		}
	}
}

/*! \brief Expire registration of SIP peer */
static int expire_register(const void *data)
{
	struct sip_peer *peer = (struct sip_peer *)data;

	if (!peer)		/* Hmmm. We have no peer. Weird. */
		return 0;

	memset(&peer->addr, 0, sizeof(peer->addr));

	destroy_association(peer);	/* remove registration data from storage */
	set_socket_transport(&peer->socket, peer->default_outbound_transport);

	manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
	register_peer_exten(peer, FALSE);	/* Remove regexten */
	peer->expire = -1;
	peer->portinuri = 0;
	ast_device_state_changed("SIP/%s", peer->name);

	/* Do we need to release this peer from memory? 
		Only for realtime peers and autocreated peers
	*/
	if (peer->is_realtime)
		ast_debug(3, "-REALTIME- peer expired registration. Name: %s. Realtime peer objects now %d\n", peer->name, rpeerobjs);

	if (peer->selfdestruct ||
	    ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
		peer = ASTOBJ_CONTAINER_UNLINK(&peerl, peer);	/* Remove from peer list */
		unref_peer(peer);		/* Remove from memory */
	}

	return 0;
}

/*! \brief Poke peer (send qualify to check if peer is alive and well) */
static int sip_poke_peer_s(const void *data)
{
	struct sip_peer *peer = (struct sip_peer *)data;

	peer->pokeexpire = -1;
	sip_poke_peer(peer);
	return 0;
}

/*! \brief Get registration details from Asterisk DB */
static void reg_source_db(struct sip_peer *peer)
{
	char data[256];
	struct in_addr in;
	int expiry;
	int port;
	char *scan, *addr, *port_str, *expiry_str, *username, *contact;

	if (peer->rt_fromcontact) 
		return;
	if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data)))
		return;

	scan = data;
	addr = strsep(&scan, ":");
	port_str = strsep(&scan, ":");
	expiry_str = strsep(&scan, ":");
	username = strsep(&scan, ":");
	contact = scan;	/* Contact include sip: and has to be the last part of the database entry as long as we use : as a separator */

	if (!inet_aton(addr, &in))
		return;

	if (port_str)
		port = atoi(port_str);
	else
		return;

	if (expiry_str)
		expiry = atoi(expiry_str);
	else
		return;

	if (username)
		ast_copy_string(peer->username, username, sizeof(peer->username));
	if (contact)
		ast_copy_string(peer->fullcontact, contact, sizeof(peer->fullcontact));

	ast_debug(2, "SIP Seeding peer from astdb: '%s' at %s@%s:%d for %d\n",
	    peer->name, peer->username, ast_inet_ntoa(in), port, expiry);

	memset(&peer->addr, 0, sizeof(peer->addr));
	peer->addr.sin_family = AF_INET;
	peer->addr.sin_addr = in;
	peer->addr.sin_port = htons(port);
	if (sipsock < 0) {
		/* SIP isn't up yet, so schedule a poke only, pretty soon */
		AST_SCHED_REPLACE(peer->pokeexpire, sched, ast_random() % 5000 + 1, sip_poke_peer_s, peer);
	} else
		sip_poke_peer(peer);
	AST_SCHED_REPLACE(peer->expire, sched, (expiry + 10) * 1000, expire_register, peer);
	register_peer_exten(peer, TRUE);
}

/*! \brief Save contact header for 200 OK on INVITE */
static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
{
	char contact[SIPBUFSIZE]; 
	char *c;

	/* Look for brackets */
	ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
	c = get_in_brackets(contact);

	/* Save full contact to call pvt for later bye or re-invite */
	ast_string_field_set(pvt, fullcontact, c);

	/* Save URI for later ACKs, BYE or RE-invites */
	ast_string_field_set(pvt, okcontacturi, c);

	/* We should return false for URI:s we can't handle,
		like tel:, mailto:,ldap: etc */
	return TRUE;		
}

static int __set_address_from_contact(const char *fullcontact, struct sockaddr_in *sin, int tcp)
{
	struct hostent *hp;
	struct ast_hostent ahp;
	int port = STANDARD_SIP_PORT;
	char *host, *pt, *transport;
	char contact_buf[256];
	char *contact;

	/* Work on a copy */
	ast_copy_string(contact_buf, fullcontact, sizeof(contact_buf));
	contact = contact_buf;

	/* 
	 * We have only the part in <brackets> here so we just need to parse a SIP URI.
	 *
	 * Note: The outbound proxy could be using UDP between the proxy and Asterisk.
	 * We still need to be able to send to the remote agent through the proxy.
	*/

	if (parse_uri(contact, "sip:,sips:", &contact, NULL, &host, &pt, NULL, &transport)) {
		ast_log(LOG_WARNING, "Invalid contact uri %s (missing sip: or sips:), attempting to use anyway\n", fullcontact);
	}

	/* set port */
	if (((get_transport_str2enum(transport) == SIP_TRANSPORT_TLS)) || !(strncasecmp(fullcontact, "sips", 4))) {
		port = port_str2int(pt, STANDARD_TLS_PORT);
	} else {
		port = port_str2int(pt, STANDARD_SIP_PORT);
	}

	/* XXX This could block for a long time XXX */
	/* We should only do this if it's a name, not an IP */
	hp = ast_gethostbyname(host, &ahp);
	if (!hp)  {
		ast_log(LOG_WARNING, "Invalid host name in Contact: (can't resolve in DNS) : '%s'\n", host);
		return -1;
	}
	sin->sin_family = AF_INET;
	memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
	sin->sin_port = htons(port);

	return 0;
}

/*! \brief Change the other partys IP address based on given contact */
static int set_address_from_contact(struct sip_pvt *pvt)
{
	if (ast_test_flag(&pvt->flags[0], SIP_NAT_ROUTE)) {
		/* NAT: Don't trust the contact field.  Just use what they came to us
		   with. */
		pvt->sa = pvt->recv;
		return 0;
	}

	return __set_address_from_contact(pvt->fullcontact, &pvt->sa, pvt->socket.type == SIP_TRANSPORT_TLS ? 1 : 0);
}


/*! \brief Parse contact header and save registration (peer registration) */
static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
{
	char contact[SIPBUFSIZE];
	char data[SIPBUFSIZE];
	const char *expires = get_header(req, "Expires");
	int expiry = atoi(expires);
	char *curi, *host, *pt, *transport;
	int port;
	int transport_type;
	const char *useragent;
	struct hostent *hp;
	struct ast_hostent ahp;
	struct sockaddr_in oldsin, testsin;

	ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));

	if (ast_strlen_zero(expires)) {	/* No expires header, try look in Contact: */
		char *s = strcasestr(contact, ";expires=");
		if (s) {
			expires = strsep(&s, ";"); /* trim ; and beyond */
			if (sscanf(expires + 9, "%30d", &expiry) != 1)
				expiry = default_expiry;
		} else {
			/* Nothing has been specified */
			expiry = default_expiry;
		}
	}

	copy_socket_data(&pvt->socket, &req->socket);

	/* Look for brackets */
	curi = contact;
	if (strchr(contact, '<') == NULL)	/* No <, check for ; and strip it */
		strsep(&curi, ";");	/* This is Header options, not URI options */
	curi = get_in_brackets(contact);

	/* if they did not specify Contact: or Expires:, they are querying
	   what we currently have stored as their contact address, so return
	   it
	*/
	if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
		/* If we have an active registration, tell them when the registration is going to expire */
		if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact))
			pvt->expiry = ast_sched_when(sched, peer->expire);
		return PARSE_REGISTER_QUERY;
	} else if (!strcasecmp(curi, "*") || !expiry) {	/* Unregister this peer */
		/* This means remove all registrations and return OK */
		memset(&peer->addr, 0, sizeof(peer->addr));
		set_socket_transport(&peer->socket, peer->default_outbound_transport);
		AST_SCHED_DEL(sched, peer->expire);

		destroy_association(peer);

		register_peer_exten(peer, FALSE);	/* Remove extension from regexten= setting in sip.conf */
		peer->fullcontact[0] = '\0';
		peer->useragent[0] = '\0';
		peer->sipoptions = 0;
		peer->lastms = 0;
		peer->portinuri = 0;
		pvt->expiry = 0;

		ast_verb(3, "Unregistered SIP '%s'\n", peer->name);
			manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\n", peer->name);
		return PARSE_REGISTER_UPDATE;
	}

	/* Store whatever we got as a contact from the client */
	ast_copy_string(peer->fullcontact, curi, sizeof(peer->fullcontact));

	/* For the 200 OK, we should use the received contact */
	ast_string_field_build(pvt, our_contact, "<%s>", curi);

	/* Make sure it's a SIP URL */
	if (parse_uri(curi, "sip:,sips:", &curi, NULL, &host, &pt, NULL, &transport)) {
		ast_log(LOG_NOTICE, "Not a valid SIP contact (missing sip:) trying to use anyway\n");
	}

	/* If we have a port number in the given URI, make sure we do remember to not check for NAPTR/SRV records. 
	   The domain part is actually a host. */
	peer->portinuri = !ast_strlen_zero(pt) ? TRUE : FALSE;

	/* handle the transport type specified in Contact header. */
	if ((transport_type = get_transport_str2enum(transport))) {
		/* if the port is not specified but the transport is, make sure to set the
		 * default port to match the specified transport.  This may or may not be the
		 * same transport used by the pvt struct for the Register dialog. */
		
		port = port_str2int(pt, (transport_type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
	} else {
		port = port_str2int(pt, STANDARD_SIP_PORT);
		transport_type = pvt->socket.type;
	}

	/* if the peer's socket type is different than the Registration
	 * transport type, change it.  If it got this far, it is a
	 * supported type, but check just in case */
	if ((peer->socket.type != transport_type) && (peer->transports & transport_type)) {
		set_socket_transport(&peer->socket, transport_type);
	}

	oldsin = peer->addr;

	/* Check that they're allowed to register at this IP */
	/* XXX This could block for a long time XXX */
	hp = ast_gethostbyname(host, &ahp);
	if (!hp)  {
		ast_log(LOG_WARNING, "Invalid host '%s'\n", host);
		*peer->fullcontact = '\0';
		ast_string_field_set(pvt, our_contact, "");
		return PARSE_REGISTER_FAILED;
	}
	memcpy(&testsin.sin_addr, hp->h_addr, sizeof(testsin.sin_addr));
	if (	ast_apply_ha(global_contact_ha, &testsin) != AST_SENSE_ALLOW ||
			ast_apply_ha(peer->contactha, &testsin) != AST_SENSE_ALLOW) {
		ast_log(LOG_WARNING, "Host '%s' disallowed by contact ACL (violating IP %s)\n", host, ast_inet_ntoa(testsin.sin_addr));
		*peer->fullcontact = '\0';
		ast_string_field_set(pvt, our_contact, "");
		return PARSE_REGISTER_DENIED;
	}

	if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE)) {
		peer->addr.sin_family = AF_INET;
		memcpy(&peer->addr.sin_addr, hp->h_addr, sizeof(peer->addr.sin_addr));
		peer->addr.sin_port = htons(port);
	} else {
		/* Don't trust the contact field.  Just use what they came to us
		   with */
		peer->addr = pvt->recv;
	}

	/* if the Contact header information copied into peer->addr matches the
	 * received address, and the transport types are the same, then copy socket
	 * data into the peer struct */
	if ((peer->socket.type == pvt->socket.type) &&
		(peer->addr.sin_addr.s_addr == pvt->recv.sin_addr.s_addr) &&
		(peer->addr.sin_port == pvt->recv.sin_port)){

		copy_socket_data(&peer->socket, &pvt->socket);
	}

	/* Save SIP options profile */
	peer->sipoptions = pvt->sipoptions;

	if (!ast_strlen_zero(curi) && ast_strlen_zero(peer->username))
		ast_copy_string(peer->username, curi, sizeof(peer->username));

	AST_SCHED_DEL(sched, peer->expire);
	if (expiry > max_expiry)
		expiry = max_expiry;
	if (expiry < min_expiry)
		expiry = min_expiry;
	peer->expire = peer->is_realtime && !ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS) ? -1 :
		ast_sched_add(sched, (expiry + 10) * 1000, expire_register, peer);
	pvt->expiry = expiry;
	snprintf(data, sizeof(data), "%s:%d:%d:%s:%s", ast_inet_ntoa(peer->addr.sin_addr), ntohs(peer->addr.sin_port), expiry, peer->username, peer->fullcontact);
	/* Saving TCP connections is useless, we won't be able to reconnect 
		XXX WHY???? XXX
		\todo check this
	*/
	if (!peer->rt_fromcontact && (peer->socket.type & SIP_TRANSPORT_UDP))
		ast_db_put("SIP/Registry", peer->name, data);
	manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Registered\r\n", peer->name);

	/* Is this a new IP address for us? */
	if (VERBOSITY_ATLEAST(2) && inaddrcmp(&peer->addr, &oldsin)) {
		ast_verbose(VERBOSE_PREFIX_3 "Registered SIP '%s' at %s port %d\n", peer->name, ast_inet_ntoa(peer->addr.sin_addr), ntohs(peer->addr.sin_port));
	}
	sip_poke_peer(peer);
	register_peer_exten(peer, 1);
	
	/* Save User agent */
	useragent = get_header(req, "User-Agent");
	if (strcasecmp(useragent, peer->useragent)) {	/* XXX copy if they are different ? */
		ast_copy_string(peer->useragent, useragent, sizeof(peer->useragent));
		ast_verb(4, "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
	}
	return PARSE_REGISTER_UPDATE;
}

/*! \brief Remove route from route list */
static void free_old_route(struct sip_route *route)
{
	struct sip_route *next;

	while (route) {
		next = route->next;
		ast_free(route);
		route = next;
	}
}

/*! \brief List all routes - mostly for debugging */
static void list_route(struct sip_route *route)
{
	if (!route)
		ast_verbose("list_route: no route\n");
	else {
		for (;route; route = route->next)
			ast_verbose("list_route: hop: <%s>\n", route->hop);
	}
}

/*! \brief Build route list from Record-Route header */
static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
{
	struct sip_route *thishop, *head, *tail;
	int start = 0;
	int len;
	const char *rr, *contact, *c;

	/* Once a persistant route is set, don't fool with it */
	if (p->route && p->route_persistant) {
		ast_debug(1, "build_route: Retaining previous route: <%s>\n", p->route->hop);
		return;
	}

	if (p->route) {
		free_old_route(p->route);
		p->route = NULL;
	}

	/* We only want to create the route set the first time this is called */
	p->route_persistant = 1;
	
	/* Build a tailq, then assign it to p->route when done.
	 * If backwards, we add entries from the head so they end up
	 * in reverse order. However, we do need to maintain a correct
	 * tail pointer because the contact is always at the end.
	 */
	head = NULL;
	tail = head;
	/* 1st we pass through all the hops in any Record-Route headers */
	for (;;) {
		/* Each Record-Route header */
		rr = __get_header(req, "Record-Route", &start);
		if (*rr == '\0')
			break;
		for (; (rr = strchr(rr, '<')) ; rr += len) { /* Each route entry */
			++rr;
			len = strcspn(rr, ">") + 1;
			/* Make a struct route */
			if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
				/* ast_calloc is not needed because all fields are initialized in this block */
				ast_copy_string(thishop->hop, rr, len);
				ast_debug(2, "build_route: Record-Route hop: <%s>\n", thishop->hop);
				/* Link in */
				if (backwards) {
					/* Link in at head so they end up in reverse order */
					thishop->next = head;
					head = thishop;
					/* If this was the first then it'll be the tail */
					if (!tail)
						tail = thishop;
				} else {
					thishop->next = NULL;
					/* Link in at the end */
					if (tail)
						tail->next = thishop;
					else
						head = thishop;
					tail = thishop;
				}
			}
		}
	}

	/* Only append the contact if we are dealing with a strict router */
	if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop, ";lr") == NULL) ) {
		/* 2nd append the Contact: if there is one */
		/* Can be multiple Contact headers, comma separated values - we just take the first */
		contact = get_header(req, "Contact");
		if (!ast_strlen_zero(contact)) {
			ast_debug(2, "build_route: Contact hop: %s\n", contact);
			/* Look for <: delimited address */
			c = strchr(contact, '<');
			if (c) {
				/* Take to > */
				++c;
				len = strcspn(c, ">") + 1;
			} else {
				/* No <> - just take the lot */
				c = contact;
				len = strlen(contact) + 1;
			}
			if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
				/* ast_calloc is not needed because all fields are initialized in this block */
				ast_copy_string(thishop->hop, c, len);
				thishop->next = NULL;
				/* Goes at the end */
				if (tail)
					tail->next = thishop;
				else
					head = thishop;
			}
		}
	}

	/* Store as new route */
	p->route = head;

	/* For debugging dump what we ended up with */
	if (sip_debug_test_pvt(p))
		list_route(p->route);
}

/*! \brief builds the sip_pvt's randdata field which is used for the nonce
 *  challenge.  When forceupdate is not set, the nonce is only updated if
 *  the current one is stale.  In this case, a stalenonce is one which
 *  has already received a response, if a nonce has not received a response
 *  it is not always necessary or beneficial to create a new one. */

static void set_nonce_randdata(struct sip_pvt *p, int forceupdate)
{
	if (p->stalenonce || forceupdate || ast_strlen_zero(p->randdata)) {
		ast_string_field_build(p, randdata, "%08lx", ast_random());	/* Create nonce for challenge */
		p->stalenonce = 0;
	}
}

AST_THREADSTORAGE(check_auth_buf);
#define CHECK_AUTH_BUF_INITLEN   256

/*! \brief  Check user authorization from peer definition 
	Some actions, like REGISTER and INVITEs from peers require
	authentication (if peer have secret set) 
    \return 0 on success, non-zero on error
*/
static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
					 const char *secret, const char *md5secret, int sipmethod,
					 char *uri, enum xmittype reliable, int ignore)
{
	const char *response;
	char *reqheader, *respheader;
	const char *authtoken;
	char a1_hash[256];
	char resp_hash[256]="";
	char *c;
	int  wrongnonce = FALSE;
	int  good_response;
	const char *usednonce = p->randdata;
	struct ast_str *buf;
	int res;

	/* table of recognised keywords, and their value in the digest */
	enum keys { K_RESP, K_URI, K_USER, K_NONCE, K_LAST };
	struct x {
		const char *key;
		const char *s;
	} *i, keys[] = {
		[K_RESP] = { "response=", "" },
		[K_URI] = { "uri=", "" },
		[K_USER] = { "username=", "" },
		[K_NONCE] = { "nonce=", "" },
		[K_LAST] = { NULL, NULL}
	};

	/* Always OK if no secret */
	if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret))
		return AUTH_SUCCESSFUL;

	/* Always auth with WWW-auth since we're NOT a proxy */
	/* Using proxy-auth in a B2BUA may block proxy authorization in the same transaction */
	response = "401 Unauthorized";

	/*
	 * Note the apparent swap of arguments below, compared to other
	 * usages of auth_headers().
	 */
	auth_headers(WWW_AUTH, &respheader, &reqheader);

	authtoken =  get_header(req, reqheader);	
	if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
		/* This is a retransmitted invite/register/etc, don't reconstruct authentication
		   information */
		if (!reliable) {
			/* Resend message if this was NOT a reliable delivery.   Otherwise the
			   retransmission should get it */
			transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
			/* Schedule auto destroy in 32 seconds (according to RFC 3261) */
			sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
		}
		return AUTH_CHALLENGE_SENT;
	} else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
		/* We have no auth, so issue challenge and request authentication */
		set_nonce_randdata(p, 1); /* Create nonce for challenge */
		transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
		/* Schedule auto destroy in 32 seconds */
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
		return AUTH_CHALLENGE_SENT;
	} 

	/* --- We have auth, so check it */

	/* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
	   an example in the spec of just what it is you're doing a hash on. */

	if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN)))
		return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */

	/* Make a copy of the response and parse it */
	res = ast_str_set(&buf, 0, "%s", authtoken);

	if (res == AST_DYNSTR_BUILD_FAILED)
		return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */

	c = buf->str;

	while(c && *(c = ast_skip_blanks(c)) ) { /* lookup for keys */
		for (i = keys; i->key != NULL; i++) {
			const char *separator = ",";	/* default */

			if (strncasecmp(c, i->key, strlen(i->key)) != 0)
				continue;
			/* Found. Skip keyword, take text in quotes or up to the separator. */
			c += strlen(i->key);
			if (*c == '"') { /* in quotes. Skip first and look for last */
				c++;
				separator = "\"";
			}
			i->s = c;
			strsep(&c, separator);
			break;
		}
		if (i->key == NULL) /* not found, jump after space or comma */
			strsep(&c, " ,");
	}

	/* Verify that digest username matches  the username we auth as */
	if (strcmp(username, keys[K_USER].s)) {
		ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
			username, keys[K_USER].s);
		/* Oops, we're trying something here */
		return AUTH_USERNAME_MISMATCH;
	}

	/* Verify nonce from request matches our nonce, and the nonce has not already been responded to.
	 * If this check fails, send 401 with new nonce */
	if (strcasecmp(p->randdata, keys[K_NONCE].s) || p->stalenonce) { /* XXX it was 'n'casecmp ? */
		wrongnonce = TRUE;
		usednonce = keys[K_NONCE].s;
	} else {
		p->stalenonce = 1; /* now, since the nonce has a response, mark it as stale so it can't be sent or responded to again */
	}

	if (!ast_strlen_zero(md5secret))
		ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
	else {
		char a1[256];
		snprintf(a1, sizeof(a1), "%s:%s:%s", username, global_realm, secret);
		ast_md5_hash(a1_hash, a1);
	}

	/* compute the expected response to compare with what we received */
	{
		char a2[256];
		char a2_hash[256];
		char resp[256];

		snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
				S_OR(keys[K_URI].s, uri));
		ast_md5_hash(a2_hash, a2);
		snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
		ast_md5_hash(resp_hash, resp);
	}

	good_response = keys[K_RESP].s &&
			!strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash));
	if (wrongnonce) {
		if (good_response) {
			if (sipdebug)
				ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req, "To"));
			/* We got working auth token, based on stale nonce . */
			set_nonce_randdata(p, 0);
			transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, TRUE);
		} else {
			/* Everything was wrong, so give the device one more try with a new challenge */
			if (!req->ignore) {
				if (sipdebug)
					ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
				set_nonce_randdata(p, 1);
			} else {
				if (sipdebug)
					ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", get_header(req, "To"));
			}
			transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
		}

		/* Schedule auto destroy in 32 seconds */
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
		return AUTH_CHALLENGE_SENT;
	} 
	if (good_response) {
		append_history(p, "AuthOK", "Auth challenge succesful for %s", username);
		return AUTH_SUCCESSFUL;
	}

	/* Ok, we have a bad username/secret pair */
	/* Tell the UAS not to re-send this authentication data, because
	   it will continue to fail
	*/

	return AUTH_SECRET_FAILED;
}

/*! \brief Change onhold state of a peer using a pvt structure */
static void sip_peer_hold(struct sip_pvt *p, int hold)
{
	struct sip_peer *peer = find_peer(p->peername, NULL, 1, 0, 0);

	if (!peer)
		return;

	/* If they put someone on hold, increment the value... otherwise decrement it */
	ast_atomic_fetchadd_int(&peer->onHold, (hold ? +1 : -1));

	/* Request device state update */
	ast_device_state_changed("SIP/%s", peer->name);

	return;
}

/*! \brief Receive MWI events that we have subscribed to */
static void mwi_event_cb(const struct ast_event *event, void *userdata)
{
	struct sip_peer *peer = userdata;

	ASTOBJ_RDLOCK(peer);
	sip_send_mwi_to_peer(peer, event, 0);
	ASTOBJ_UNLOCK(peer);
}

/*! \brief Callback for the devicestate notification (SUBSCRIBE) support subsystem
\note	If you add an "hint" priority to the extension in the dial plan,
	you will get notifications on device state changes */
static int cb_extensionstate(char *context, char* exten, int state, void *data)
{
	struct sip_pvt *p = data;

	sip_pvt_lock(p);

	switch(state) {
	case AST_EXTENSION_DEACTIVATED:	/* Retry after a while */
	case AST_EXTENSION_REMOVED:	/* Extension is gone */
		if (p->autokillid > -1 && sip_cancel_destroy(p))	/* Remove subscription expiry for renewals */
			ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);	/* Delete subscription in 32 secs */
		ast_verb(2, "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
		p->stateid = -1;
		p->subscribed = NONE;
		append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
		break;
	default:	/* Tell user */
		p->laststate = state;
		break;
	}
	if (p->subscribed != NONE) {	/* Only send state NOTIFY if we know the format */
		if (!p->pendinginvite) {
			transmit_state_notify(p, state, 1, FALSE);
		} else {
			/* We already have a NOTIFY sent that is not answered. Queue the state up.
			   if many state changes happen meanwhile, we will only send a notification of the last one */
			ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
		}
	}
	ast_verb(2, "Extension Changed %s[%s] new state %s for Notify User %s %s\n", exten, context, ast_extension_state2str(state), p->username,
			ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");

	sip_pvt_unlock(p);

	return 0;
}

/*! \brief Send a fake 401 Unauthorized response when the administrator
  wants to hide the names of local users/peers from fishers
 */
static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable)
{
	/* We have to emulate EXACTLY what we'd get with a good peer
	 * and a bad password, or else we leak information. */
	const char *response = "407 Proxy Authentication Required";
	const char *reqheader = "Proxy-Authorization";
	const char *respheader = "Proxy-Authenticate";
	const char *authtoken;
	struct ast_str *buf;
	char *c;

	/* table of recognised keywords, and their value in the digest */
	enum keys { K_NONCE, K_LAST };
	struct x {
		const char *key;
		const char *s;
	} *i, keys[] = {
		[K_NONCE] = { "nonce=", "" },
		[K_LAST] = { NULL, NULL}
	};

	if (sipmethod == SIP_REGISTER || sipmethod == SIP_SUBSCRIBE) {
		response = "401 Unauthorized";
		reqheader = "Authorization";
		respheader = "WWW-Authenticate";
	}
	authtoken = get_header(req, reqheader);
	if (req->ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
		/* This is a retransmitted invite/register/etc, don't reconstruct authentication
		 * information */
		transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
		/* Schedule auto destroy in 32 seconds (according to RFC 3261) */
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
		return;
	} else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
		/* We have no auth, so issue challenge and request authentication */
		set_nonce_randdata(p, 1);
		transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
		/* Schedule auto destroy in 32 seconds */
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
		return;
	}

	if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
		transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
		return;
	}

	/* Make a copy of the response and parse it */
	if (ast_str_set(&buf, 0, "%s", authtoken) == AST_DYNSTR_BUILD_FAILED) {
		transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
		return;
	}

	c = buf->str;

	while (c && *(c = ast_skip_blanks(c))) { /* lookup for keys */
		for (i = keys; i->key != NULL; i++) {
			const char *separator = ",";	/* default */

			if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
				continue;
			}
			/* Found. Skip keyword, take text in quotes or up to the separator. */
			c += strlen(i->key);
			if (*c == '"') { /* in quotes. Skip first and look for last */
				c++;
				separator = "\"";
			}
			i->s = c;
			strsep(&c, separator);
			break;
		}
		if (i->key == NULL) { /* not found, jump after space or comma */
			strsep(&c, " ,");
		}
	}

	/* Verify nonce from request matches our nonce.  If not, send 401 with new nonce */
	if (strcasecmp(p->randdata, keys[K_NONCE].s)) {
		if (!req->ignore) {
			set_nonce_randdata(p, 1);
		}
		transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);

		/* Schedule auto destroy in 32 seconds */
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
	} else {
		transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
	}
}

/*!
 * Terminate the uri at the first ';' or space.
 * Technically we should ignore escaped space per RFC3261 (19.1.1 etc)
 * but don't do it for the time being. Remember the uri format is:
 *\verbatim
 *
 *	sip:user:password@host:port;uri-parameters?headers
 *	sips:user:password@host:port;uri-parameters?headers
 *
 *\endverbatim
 */
static char *terminate_uri(char *uri)
{
	char *t = uri;
	while (*t && *t > ' ' && *t != ';')
		t++;
	*t = '\0';
	return uri;
}

/*! \brief Verify registration of user 
	- Registration is done in several steps, first a REGISTER without auth
	  to get a challenge (nonce) then a second one with auth
	- Registration requests are only matched with peers that are marked as "dynamic"
 */
static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
					      struct sip_request *req, char *uri)
{
	enum check_auth_result res = AUTH_NOT_FOUND;
	struct sip_peer *peer;
	char tmp[256];
	char *name, *c;
	char *domain;

	terminate_uri(uri);	/* warning, overwrite the string */

	ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
	if (pedanticsipchecking)
		ast_uri_decode(tmp);

	c = get_in_brackets(tmp);
	c = remove_uri_parameters(c);

	if (!strncasecmp(c, "sip:", 4)) {
		name = c + 4;
	} else if (!strncasecmp(c, "sips:", 5)) {
		name = c + 5;
	} else {
		name = c;
		ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_inet_ntoa(sin->sin_addr));
	}

	/* XXX here too we interpret a missing @domain as a name-only
	 * URI, whereas the RFC says this is a domain-only uri.
	 */
	/* Strip off the domain name */
	if ((c = strchr(name, '@'))) {
		*c++ = '\0';
		domain = c;
		if ((c = strchr(domain, ':')))	/* Remove :port */
			*c = '\0';
		if (!AST_LIST_EMPTY(&domain_list)) {
			if (!check_sip_domain(domain, NULL, 0)) {
				transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
				return AUTH_UNKNOWN_DOMAIN;
			}
		}
	}
	c = strchr(name, ';');	/* Remove any Username parameters */
	if (c)
		*c = '\0';

	ast_string_field_set(p, exten, name);
	build_contact(p);
	if (req->ignore) {
		/* Expires is a special case, where we only want to load the peer if this isn't a deregistration attempt */
		const char *expires = get_header(req, "Expires");
		int expire = atoi(expires);

		if (ast_strlen_zero(expires)) { /* No expires header; look in Contact */
			if ((expires = strcasestr(get_header(req, "Contact"), ";expires="))) {
				expire = atoi(expires + 9);
			}
		}
		if (!ast_strlen_zero(expires) && expire == 0) {
			transmit_response_with_date(p, "200 OK", req);
			return 0;
		}
	}
	peer = find_peer(name, NULL, 1, 0, 0);
	if (!(peer && ast_apply_ha(peer->ha, sin))) {
		/* Peer fails ACL check */
		if (peer) {
			unref_peer(peer);
			peer = NULL;
			res = AUTH_ACL_FAILED;
		} else
			res = AUTH_NOT_FOUND;
	}

	if (peer) {
		/* Set Frame packetization */
		if (p->rtp) {
			ast_rtp_codec_setpref(p->rtp, &peer->prefs);
			p->autoframing = peer->autoframing;
		}
		if (!peer->host_dynamic) {
			ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
			res = AUTH_PEER_NOT_DYNAMIC;
		} else {
			ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT);
			if (ast_test_flag(&p->flags[1], SIP_PAGE2_REGISTERTRYING))
				transmit_response(p, "100 Trying", req);
			if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri, XMIT_UNRELIABLE, req->ignore))) {
				if (sip_cancel_destroy(p))
					ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");

				/* We have a successful registration attempt with proper authentication,
				   now, update the peer */
				switch (parse_register_contact(p, peer, req)) {
				case PARSE_REGISTER_DENIED:
					transmit_response_with_date(p, "603 Denied", req);
					peer->lastmsgssent = -1;
					res = 0;
					break;
				case PARSE_REGISTER_FAILED:
					ast_log(LOG_WARNING, "Failed to parse contact info\n");
					transmit_response_with_date(p, "400 Bad Request", req);
					peer->lastmsgssent = -1;
					res = 0;
					break;
				case PARSE_REGISTER_QUERY:
					ast_string_field_set(p, fullcontact, peer->fullcontact);
					transmit_response_with_date(p, "200 OK", req);
					peer->lastmsgssent = -1;
					res = 0;
					break;
				case PARSE_REGISTER_UPDATE:
					ast_string_field_set(p, fullcontact, peer->fullcontact);
					update_peer(peer, p->expiry);
					/* Say OK and ask subsystem to retransmit msg counter */
					transmit_response_with_date(p, "200 OK", req);
					if (!ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY))
						peer->lastmsgssent = -1;
					res = 0;
					break;
				}

				if (check_request_transport(peer, req)) {
					ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
					transmit_response_with_date(p, "403 Forbidden", req);
					res = AUTH_BAD_TRANSPORT;
				}
			} 
		}
	}
	if (!peer && autocreatepeer) {
		/* Create peer if we have autocreate mode enabled */
		peer = temp_peer(name);
		if (peer) {
			ASTOBJ_CONTAINER_LINK(&peerl, peer);
			if (sip_cancel_destroy(p))
				ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
			switch (parse_register_contact(p, peer, req)) {
			case PARSE_REGISTER_DENIED:
				transmit_response_with_date(p, "403 Forbidden (ACL)", req);
				peer->lastmsgssent = -1;
				res = 0;
				break;
			case PARSE_REGISTER_FAILED:
				ast_log(LOG_WARNING, "Failed to parse contact info\n");
				transmit_response_with_date(p, "400 Bad Request", req);
				peer->lastmsgssent = -1;
				res = 0;
				break;
			case PARSE_REGISTER_QUERY:
				ast_string_field_set(p, fullcontact, peer->fullcontact);
				transmit_response_with_date(p, "200 OK", req);
				peer->lastmsgssent = -1;
				res = 0;
				break;
			case PARSE_REGISTER_UPDATE:
				ast_string_field_set(p, fullcontact, peer->fullcontact);
				/* Say OK and ask subsystem to retransmit msg counter */
				transmit_response_with_date(p, "200 OK", req);
				manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Registered\r\n", peer->name);
				peer->lastmsgssent = -1;
				res = 0;
				break;
			}
		}
	}
	if (!peer && global_alwaysauthreject) {
		/* If we found a peer, we transmit a 100 Trying.  Therefore, if we're
		 * trying to avoid leaking information, we MUST also transmit the same
		 * response when we DON'T find a peer. */
		transmit_response(p, "100 Trying", req);
		/* Insert a fake delay between the 100 and the subsequent failure. */
		sched_yield();
	}
	if (!res) {
		ast_device_state_changed("SIP/%s", peer->name);
	}
	if (res < 0) {
		switch (res) {
		case AUTH_SECRET_FAILED:
			/* Wrong password in authentication. Go away, don't try again until you fixed it */
			transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
			break;
		case AUTH_USERNAME_MISMATCH:
			/* Username and digest username does not match.
			   Asterisk uses the From: username for authentication. We need the
			   users to use the same authentication user name until we support
			   proper authentication by digest auth name */
		case AUTH_NOT_FOUND:
		case AUTH_PEER_NOT_DYNAMIC:
		case AUTH_ACL_FAILED:
			if (global_alwaysauthreject) {
				transmit_fake_auth_response(p, SIP_REGISTER, &p->initreq, XMIT_UNRELIABLE);
			} else {
				/* URI not found */
				if (res == AUTH_PEER_NOT_DYNAMIC)
					transmit_response(p, "403 Forbidden", &p->initreq);
				else
					transmit_response(p, "404 Not found", &p->initreq);
			}
			break;
		case AUTH_BAD_TRANSPORT:
		default:
			break;
		}
	}
	if (peer)
		unref_peer(peer);

	return res;
}

/*! \brief Translate referring cause */
static void sip_set_redirstr(struct sip_pvt *p, char *reason) {

	if (!strcmp(reason, "unknown")) {
		ast_string_field_set(p, redircause, "UNKNOWN");
	} else if (!strcmp(reason, "user-busy")) {
		ast_string_field_set(p, redircause, "BUSY");
	} else if (!strcmp(reason, "no-answer")) {
		ast_string_field_set(p, redircause, "NOANSWER");
	} else if (!strcmp(reason, "unavailable")) {
		ast_string_field_set(p, redircause, "UNREACHABLE");
	} else if (!strcmp(reason, "unconditional")) {
		ast_string_field_set(p, redircause, "UNCONDITIONAL");
	} else if (!strcmp(reason, "time-of-day")) {
		ast_string_field_set(p, redircause, "UNKNOWN");
	} else if (!strcmp(reason, "do-not-disturb")) {
		ast_string_field_set(p, redircause, "UNKNOWN");
	} else if (!strcmp(reason, "deflection")) {
		ast_string_field_set(p, redircause, "UNKNOWN");
	} else if (!strcmp(reason, "follow-me")) {
		ast_string_field_set(p, redircause, "UNKNOWN");
	} else if (!strcmp(reason, "out-of-service")) {
		ast_string_field_set(p, redircause, "UNREACHABLE");
	} else if (!strcmp(reason, "away")) {
		ast_string_field_set(p, redircause, "UNREACHABLE");
	} else {
		ast_string_field_set(p, redircause, "UNKNOWN");
	}
}

/*! \brief Get referring dnis */
static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq)
{
	char tmp[256], *exten, *rexten, *rdomain;
	char *params, *reason = NULL;
	struct sip_request *req;
	
	req = oreq ? oreq : &p->initreq;

	ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
	if (ast_strlen_zero(tmp))
		return 0;

	params = strchr(tmp, ';');

	exten = get_in_brackets(tmp);
	if (!strncasecmp(exten, "sip:", 4)) {
		exten += 4;
	} else if (!strncasecmp(exten, "sips:", 5)) {
		exten += 5;
	} else {
		ast_log(LOG_WARNING, "Huh?  Not an RDNIS SIP header (%s)?\n", exten);
		return -1;
	}

	/* Get diversion-reason param if present */
	if (params) {
		*params = '\0';	/* Cut off parameters  */
		params++;
		while (*params == ';' || *params == ' ')
			params++;
		/* Check if we have a reason parameter */
		if ((reason = strcasestr(params, "reason="))) {
			reason+=7;
			/* Remove enclosing double-quotes */
			if (*reason == '"') 
				ast_strip_quoted(reason, "\"", "\"");
			if (!ast_strlen_zero(reason)) {
				sip_set_redirstr(p, reason);
				if (p->owner) {
					pbx_builtin_setvar_helper(p->owner, "__PRIREDIRECTREASON", p->redircause);
					pbx_builtin_setvar_helper(p->owner, "__SIPREDIRECTREASON", reason);
				}
			}
		}
	}

	rdomain = exten;
	rexten = strsep(&rdomain, "@");	/* trim anything after @ */
	if (p->owner) 
		pbx_builtin_setvar_helper(p->owner, "__SIPRDNISDOMAIN", rdomain);

	if (sip_debug_test_pvt(p))
		ast_verbose("RDNIS for this call is is %s (reason %s)\n", exten, reason ? reason : "");

	ast_string_field_set(p, rdnis, rexten);

	return 0;
}

/*! \brief Find out who the call is for.
	We use the request uri as a destination. 
	This code assumes authentication has been done, so that the
	device (peer/user) context is already set.
	\return 0 on success (found a matching extension),
	1 for pickup extension or overlap dialling support (if we support it),
	-1 on error.
*/
static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
{
	char tmp[256] = "", *uri, *a;
	char tmpf[256] = "", *from = NULL;
	struct sip_request *req;
	char *colon;
	char *decoded_uri;
	
	req = oreq;
	if (!req)
		req = &p->initreq;

	/* Find the request URI */
	if (req->rlPart2)
		ast_copy_string(tmp, req->rlPart2, sizeof(tmp));
	
	if (pedanticsipchecking)
		ast_uri_decode(tmp);

	uri = get_in_brackets(tmp);
	
	if (!strncasecmp(uri, "sip:", 4)) {
		uri += 4;
	} else if (!strncasecmp(uri, "sips:", 5)) {
		uri += 5;
	} else {
		ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", uri);
		return -1;
	}

	/* Now find the From: caller ID and name */
	/* XXX Why is this done in get_destination? Isn't it already done?
	   Needs to be checked 
        */
	ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
	if (!ast_strlen_zero(tmpf)) {
		if (pedanticsipchecking)
			ast_uri_decode(tmpf);
		from = get_in_brackets(tmpf);
	} 
	
	if (!ast_strlen_zero(from)) {
		if (!strncasecmp(from, "sip:", 4)) {
			from += 4;
		} else if (!strncasecmp(from, "sips:", 5)) {
			from += 5;
		} else {
			ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", from);
			return -1;
		}
		if ((a = strchr(from, '@')))
			*a++ = '\0';
		else
			a = from;	/* just a domain */
		from = strsep(&from, ";");	/* Remove userinfo options */
		a = strsep(&a, ";");		/* Remove URI options */
		ast_string_field_set(p, fromdomain, a);
	}

	/* Skip any options and find the domain */

	/* Get the target domain */
	if ((a = strchr(uri, '@'))) {
		*a++ = '\0';
	} else {	/* No username part */
		a = uri;
		uri = "s";	/* Set extension to "s" */
	}
	colon = strchr(a, ':'); /* Remove :port */
	if (colon)
		*colon = '\0';

	uri = strsep(&uri, ";");	/* Remove userinfo options */
	a = strsep(&a, ";");		/* Remove URI options */

	ast_string_field_set(p, domain, a);

	if (!AST_LIST_EMPTY(&domain_list)) {
		char domain_context[AST_MAX_EXTENSION];

		domain_context[0] = '\0';
		if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
			if (!allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
				ast_debug(1, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
				return -2;
			}
		}
		/* If we don't have a peer (i.e. we're a guest call),
		 * overwrite the original context */
		if (!ast_test_flag(&p->flags[1], SIP_PAGE2_HAVEPEERCONTEXT) && !ast_strlen_zero(domain_context))
			ast_string_field_set(p, context, domain_context);
	}

	/* If the request coming in is a subscription and subscribecontext has been specified use it */
	if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext))
		ast_string_field_set(p, context, p->subscribecontext);

	if (sip_debug_test_pvt(p))
		ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);

	/* If this is a subscription we actually just need to see if a hint exists for the extension */
	if (req->method == SIP_SUBSCRIBE) {
		char hint[AST_MAX_EXTENSION];
		return (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten) ? 0 : -1);
	} else {
		decoded_uri = ast_strdupa(uri);
		ast_uri_decode(decoded_uri);
		/* Check the dialplan for the username part of the request URI,
		   the domain will be stored in the SIPDOMAIN variable
		   Since extensions.conf can have unescaped characters, try matching a decoded
		   uri in addition to the non-decoded uri
		   Return 0 if we have a matching extension */
		if (ast_exists_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from)) || ast_exists_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from)) ||
		    !strcmp(decoded_uri, ast_pickup_ext())) {
			if (!oreq)
				ast_string_field_set(p, exten, decoded_uri);
			return 0;
		} 
	}

	/* Return 1 for pickup extension or overlap dialling support (if we support it) */
	if((ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) && 
 	    ast_canmatch_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))) ||
	    !strncmp(decoded_uri, ast_pickup_ext(), strlen(decoded_uri))) {
		return 1;
	}
	
	return -1;
}

/*! \brief Lock dialog lock and find matching pvt lock  
	- Their tag is fromtag, our tag is to-tag
	- This means that in some transactions, totag needs to be their tag :-)
	  depending upon the direction
	Returns a reference, remember to release it when done XXX
*/
static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag) 
{
	struct sip_pvt *sip_pvt_ptr;


	if (totag)
		ast_debug(4, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");

	/* Search dialogs and find the match */
	dialoglist_lock();
	for (sip_pvt_ptr = dialoglist; sip_pvt_ptr; sip_pvt_ptr = sip_pvt_ptr->next) {
		if (!strcmp(sip_pvt_ptr->callid, callid)) {
			int match = 1;
			char *ourtag = sip_pvt_ptr->tag;

			/* Go ahead and lock it (and its owner) before returning */
			sip_pvt_lock(sip_pvt_ptr);

			/* Check if tags match. If not, this is not the call we want
			   (With a forking SIP proxy, several call legs share the
			   call id, but have different tags)
			*/
			
			/* RFC 3891
			 * > 3.  User Agent Server Behavior: Receiving a Replaces Header
			 * > The Replaces header contains information used to match an existing
			 * > SIP dialog (call-id, to-tag, and from-tag).  Upon receiving an INVITE
			 * > with a Replaces header, the User Agent (UA) attempts to match this
			 * > information with a confirmed or early dialog.  The User Agent Server
			 * > (UAS) matches the to-tag and from-tag parameters as if they were tags
			 * > present in an incoming request.  In other words, the to-tag parameter
			 * > is compared to the local tag, and the from-tag parameter is compared
			 * > to the remote tag.
			 *
			 * Thus, the totag is always compared to the local tag, regardless if
			 * this our call is an incoming or outgoing call.
			 */
			if (pedanticsipchecking && (strcmp(fromtag, sip_pvt_ptr->theirtag) || (!ast_strlen_zero(totag) && strcmp(totag, ourtag))))
				match = 0;

			if (!match) {
				sip_pvt_unlock(sip_pvt_ptr);
				continue;
			}

			if (totag)				 
				ast_debug(4, "Matched %s call - their tag is %s Our tag is %s\n",
					ast_test_flag(&sip_pvt_ptr->flags[0], SIP_OUTGOING) ? "OUTGOING": "INCOMING",
					sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);

			/* deadlock avoidance... */
			while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
				sip_pvt_unlock(sip_pvt_ptr);
				usleep(1);
				sip_pvt_lock(sip_pvt_ptr);
			}
			break;
		}
	}
	dialoglist_unlock();
	if (!sip_pvt_ptr)
		ast_debug(4, "Found no match for callid %s to-tag %s from-tag %s\n", callid, totag, fromtag);
	return sip_pvt_ptr;
}

/*! \brief Call transfer support (the REFER method) 
 * 	Extracts Refer headers into pvt dialog structure */
static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
{

	const char *p_referred_by = NULL;
	char *h_refer_to = NULL; 
	char *h_referred_by = NULL;
	char *refer_to;
	const char *p_refer_to;
	char *referred_by_uri = NULL;
	char *ptr;
	struct sip_request *req = NULL;
	const char *transfer_context = NULL;
	struct sip_refer *referdata;


	req = outgoing_req;
	referdata = transferer->refer;

	if (!req)
		req = &transferer->initreq;

	p_refer_to = get_header(req, "Refer-To");
	if (ast_strlen_zero(p_refer_to)) {
		ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
		return -2;	/* Syntax error */
	}
	h_refer_to = ast_strdupa(p_refer_to);
	refer_to = get_in_brackets(h_refer_to);
	if (pedanticsipchecking)
		ast_uri_decode(refer_to);

	if (!strncasecmp(refer_to, "sip:", 4)) {
		refer_to += 4;			/* Skip sip: */
	} else if (!strncasecmp(refer_to, "sips:", 5)) {
		refer_to += 5;
	} else {
		ast_log(LOG_WARNING, "Can't transfer to non-sip: URI.  (Refer-to: %s)?\n", refer_to);
		return -3;
	}

	/* Get referred by header if it exists */
	p_referred_by = get_header(req, "Referred-By");

	/* Give useful transfer information to the dialplan */
	if (transferer->owner) {
		struct ast_channel *peer = ast_bridged_channel(transferer->owner);
		if (peer) {
			pbx_builtin_setvar_helper(peer, "SIPREFERRINGCONTEXT", transferer->context);
			pbx_builtin_setvar_helper(peer, "SIPREFERREDBYHDR", p_referred_by);
		}
	}

	if (!ast_strlen_zero(p_referred_by)) {
		char *lessthan;
		h_referred_by = ast_strdupa(p_referred_by);
		if (pedanticsipchecking)
			ast_uri_decode(h_referred_by);

		/* Store referrer's caller ID name */
		ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
		if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
			*(lessthan - 1) = '\0';	/* Space */
		}

		referred_by_uri = get_in_brackets(h_referred_by);
		if (!strncasecmp(referred_by_uri, "sip:", 4)) {
			referred_by_uri += 4;		/* Skip sip: */
		} else if (!strncasecmp(referred_by_uri, "sips:", 5)) {
			referred_by_uri += 5;		/* Skip sips: */
		} else {
			ast_log(LOG_WARNING, "Huh?  Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
			referred_by_uri = NULL;
		}
	}

	/* Check for arguments in the refer_to header */
	if ((ptr = strcasestr(refer_to, "replaces="))) {
		char *to = NULL, *from = NULL;
		
		/* This is an attended transfer */
		referdata->attendedtransfer = 1;
		ast_copy_string(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
		ast_uri_decode(referdata->replaces_callid);
		if ((ptr = strchr(referdata->replaces_callid, ';'))) 	/* Find options */ {
			*ptr++ = '\0';
		}
		
		if (ptr) {
			/* Find the different tags before we destroy the string */
			to = strcasestr(ptr, "to-tag=");
			from = strcasestr(ptr, "from-tag=");
		}
		
		/* Grab the to header */
		if (to) {
			ptr = to + 7;
			if ((to = strchr(ptr, '&')))
				*to = '\0';
			if ((to = strchr(ptr, ';')))
				*to = '\0';
			ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
		}
		
		if (from) {
			ptr = from + 9;
			if ((to = strchr(ptr, '&')))
				*to = '\0';
			if ((to = strchr(ptr, ';')))
				*to = '\0';
			ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
		}
		
		if (!pedanticsipchecking)
			ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
		else
			ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s F-tag: %s T-tag: %s\n", referdata->replaces_callid, referdata->replaces_callid_fromtag ? referdata->replaces_callid_fromtag : "<none>", referdata->replaces_callid_totag ? referdata->replaces_callid_totag : "<none>" );
	}
	
	if ((ptr = strchr(refer_to, '@'))) {	/* Separate domain */
		char *urioption = NULL, *domain;
		*ptr++ = '\0';

		if ((urioption = strchr(ptr, ';'))) /* Separate urioptions */
			*urioption++ = '\0';
		
		domain = ptr;
		if ((ptr = strchr(domain, ':')))	/* Remove :port */
			*ptr = '\0';
		
		/* Save the domain for the dial plan */
		ast_copy_string(referdata->refer_to_domain, domain, sizeof(referdata->refer_to_domain));
		if (urioption)
			ast_copy_string(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
	}

	if ((ptr = strchr(refer_to, ';'))) 	/* Remove options */
		*ptr = '\0';
	ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
	
	if (referred_by_uri) {
		if ((ptr = strchr(referred_by_uri, ';'))) 	/* Remove options */
			*ptr = '\0';
		ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
	} else {
		referdata->referred_by[0] = '\0';
	}

	/* Determine transfer context */
	if (transferer->owner)	/* Mimic behaviour in res_features.c */
		transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");

	/* By default, use the context in the channel sending the REFER */
	if (ast_strlen_zero(transfer_context)) {
		transfer_context = S_OR(transferer->owner->macrocontext,
					S_OR(transferer->context, default_context));
	}

	ast_copy_string(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
	
	/* Either an existing extension or the parking extension */
	if (referdata->attendedtransfer || ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
		if (sip_debug_test_pvt(transferer)) {
			ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
		}
		/* We are ready to transfer to the extension */
		return 0;
	} 
	if (sip_debug_test_pvt(transferer))
		ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);

	/* Failure, we can't find this extension */
	return -1;
}


/*! \brief Call transfer support (old way, deprecated by the IETF)--*/
static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
{
	char tmp[256] = "", *c, *a;
	struct sip_request *req = oreq ? oreq : &p->initreq;
	struct sip_refer *referdata = NULL;
	const char *transfer_context = NULL;
	
	if (!p->refer && !sip_refer_allocate(p))
		return -1;

	referdata = p->refer;

	ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
	c = get_in_brackets(tmp);

	if (pedanticsipchecking)
		ast_uri_decode(c);

	if (!strncasecmp(c, "sip:", 4)) {
		c += 4;
	} else if (!strncasecmp(c, "sips:", 5)) {
		c += 5;
	} else {
		ast_log(LOG_WARNING, "Huh?  Not a SIP header in Also: transfer (%s)?\n", c);
		return -1;
	}

	if ((a = strchr(c, ';'))) 	/* Remove arguments */
		*a = '\0';
	
	if ((a = strchr(c, '@'))) {	/* Separate Domain */
		*a++ = '\0';
		ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
	}
	
	if (sip_debug_test_pvt(p))
		ast_verbose("Looking for %s in %s\n", c, p->context);

	if (p->owner)	/* Mimic behaviour in res_features.c */
		transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");

	/* By default, use the context in the channel sending the REFER */
	if (ast_strlen_zero(transfer_context)) {
		transfer_context = S_OR(p->owner->macrocontext,
					S_OR(p->context, default_context));
	}
	if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
		/* This is a blind transfer */
		ast_debug(1, "SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
		ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
		ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
		ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
		referdata->refer_call = NULL;
		/* Set new context */
		ast_string_field_set(p, context, transfer_context);
		return 0;
	} else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
		return 1;
	}

	return -1;
}

/*! \brief check received= and rport= in a SIP response.
 * If we get a response with received= and/or rport= in the Via:
 * line, use them as 'p->ourip' (see RFC 3581 for rport,
 * and RFC 3261 for received).
 * Using these two fields SIP can produce the correct
 * address and port in the SIP headers without the need for STUN.
 * The address part is also reused for the media sessions.
 * Note that ast_sip_ouraddrfor() still rewrites p->ourip
 * if you specify externip/seternaddr/stunaddr.
 */
static attribute_unused void check_via_response(struct sip_pvt *p, struct sip_request *req)
{
	char via[256];
	char *cur, *opts;

	ast_copy_string(via, get_header(req, "Via"), sizeof(via));

	/* Work on the leftmost value of the topmost Via header */
	opts = strchr(via, ',');
	if (opts)
		*opts = '\0';

	/* parse all relevant options */
	opts = strchr(via, ';');
	if (!opts)
		return;	/* no options to parse */
	*opts++ = '\0';
	while ( (cur = strsep(&opts, ";")) ) {
		if (!strncmp(cur, "rport=", 6)) {
			int port = strtol(cur+6, NULL, 10);
			/* XXX add error checking */
			p->ourip.sin_port = ntohs(port);
		} else if (!strncmp(cur, "received=", 9)) {
			if (ast_parse_arg(cur+9, PARSE_INADDR, &p->ourip))
				;	/* XXX add error checking */
		}
	}
}

/*! \brief check Via: header for hostname, port and rport request/answer */
static void check_via(struct sip_pvt *p, struct sip_request *req)
{
	char via[512];
	char *c, *pt, *maddr;
	struct hostent *hp;
	struct ast_hostent ahp;

	ast_copy_string(via, get_header(req, "Via"), sizeof(via));

	/* Work on the leftmost value of the topmost Via header */
	c = strchr(via, ',');
	if (c)
		*c = '\0';

	/* Check for rport */
	c = strstr(via, ";rport");
	if (c && (c[6] != '='))	/* rport query, not answer */
		ast_set_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT);

	/* Check for maddr */
	maddr = strstr(via, "maddr=");
	if (maddr) {
		maddr += 6;
		c = maddr + strspn(maddr, "0123456789.");
		*c = '\0';
	}

	c = strchr(via, ';');
	if (c)
		*c = '\0';

	c = strchr(via, ' ');
	if (c) {
		*c = '\0';
		c = ast_skip_blanks(c+1);
		if (strcasecmp(via, "SIP/2.0/UDP") && strcasecmp(via, "SIP/2.0/TCP") && strcasecmp(via, "SIP/2.0/TLS")) {
			ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
			return;
		}
		pt = strchr(c, ':');
		if (pt)
			*pt++ = '\0';	/* remember port pointer */
		/* Use maddr if found */
		if (maddr)
			c = maddr;
		hp = ast_gethostbyname(c, &ahp);
		if (!hp) {
			ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
			return;
		}
		memset(&p->sa, 0, sizeof(p->sa));
		p->sa.sin_family = AF_INET;
		memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
		p->sa.sin_port = htons(port_str2int(pt, STANDARD_SIP_PORT));

		if (sip_debug_test_pvt(p)) {
			const struct sockaddr_in *dst = sip_real_dst(p);
			ast_verbose("Sending to %s : %d (%s)\n", ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), sip_nat_mode(p));
		}
	}
}

/*! \brief  Get caller id name from SIP headers */
static char *get_calleridname(const char *input, char *output, size_t outputsize)
{
	const char *end = strchr(input, '<');	/* first_bracket */
	const char *tmp = strchr(input, '"');	/* first quote */
	int bytes = 0;
	int maxbytes = outputsize - 1;

	if (!end || end == input)	/* we require a part in brackets */
		return NULL;

	end--; /* move just before "<" */

	if (tmp && tmp <= end) {
		/* The quote (tmp) precedes the bracket (end+1).
		 * Find the matching quote and return the content.
		 */
		end = strchr(tmp+1, '"');
		if (!end)
			return NULL;
		bytes = (int) (end - tmp);
		/* protect the output buffer */
		if (bytes > maxbytes)
			bytes = maxbytes;
		ast_copy_string(output, tmp + 1, bytes);
	} else {
		/* No quoted string, or it is inside brackets. */
		/* clear the empty characters in the begining*/
		input = ast_skip_blanks(input);
		/* clear the empty characters in the end */
		while(*end && *end < 33 && end > input)
			end--;
		if (end >= input) {
			bytes = (int) (end - input) + 2;
			/* protect the output buffer */
			if (bytes > maxbytes)
				bytes = maxbytes;
			ast_copy_string(output, input, bytes);
		} else
			return NULL;
	}
	return output;
}

/*! \brief  Get caller id number from Remote-Party-ID header field 
 *	Returns true if number should be restricted (privacy setting found)
 *	output is set to NULL if no number found
 */
static int get_rpid_num(const char *input, char *output, int maxlen)
{
	char *start;
	char *end;

	start = strchr(input, ':');
	if (!start) {
		output[0] = '\0';
		return 0;
	}
	start++;

	/* we found "number" */
	ast_copy_string(output, start, maxlen);
	output[maxlen-1] = '\0';

	end = strchr(output, '@');
	if (end)
		*end = '\0';
	else
		output[0] = '\0';
	if (strstr(input, "privacy=full") || strstr(input, "privacy=uri"))
		return AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;

	return 0;
}

/*!
 * duplicate a list of channel variables, \return the copy.
 */
static struct ast_variable *copy_vars(struct ast_variable *src)
{
	struct ast_variable *res = NULL, *tmp, *v = NULL;

	for (v = src ; v ; v = v->next) {
		if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
			tmp->next = res;
			res = tmp;
		}
	}
	return res;
}

/*! \brief helper function for check_{user|peer}_ok() */
static void replace_cid(struct sip_pvt *p, const char *rpid_num, const char *calleridname)
{
	/* replace callerid if rpid found, and not restricted */
	if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
		char *tmp = ast_strdupa(rpid_num); /* XXX the copy can be done later */
		if (!ast_strlen_zero(calleridname))
			ast_string_field_set(p, cid_name, calleridname);
		if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
			ast_shrink_phone_number(tmp);
		ast_string_field_set(p, cid_num, tmp);
	}
}

/*! \brief Validate user authentication */
static enum check_auth_result check_user_ok(struct sip_pvt *p, char *of,
	struct sip_request *req, int sipmethod, struct sockaddr_in *sin,
	enum xmittype reliable,
	char *rpid_num, char *calleridname, char *uri2)
{
	enum check_auth_result res;
	struct sip_user *user = find_user(of, 1);
	int debug=sip_debug_test_addr(sin);

	/* Find user based on user name in the from header */
	if (!user) {
		if (debug)
			ast_verbose("No user '%s' in SIP users list\n", of);
		return AUTH_DONT_KNOW;
	}
	if (!ast_apply_ha(user->ha, sin)) {
		if (debug)
			ast_verbose("Found user '%s' for '%s', but fails host access\n",
				user->name, of);
		unref_user(user);
		return AUTH_DONT_KNOW;
	}
	if (debug)
		ast_verbose("Found user '%s' for '%s'\n", user->name, of);

	ast_copy_flags(&p->flags[0], &user->flags[0], SIP_FLAGS_TO_COPY);
	ast_copy_flags(&p->flags[1], &user->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
	if (sipmethod == SIP_INVITE) {
		/* copy channel vars */
		p->chanvars = copy_vars(user->chanvars);
	}
	p->prefs = user->prefs;
	/* Set Frame packetization */
	if (p->rtp) {
		ast_rtp_codec_setpref(p->rtp, &p->prefs);
		p->autoframing = user->autoframing;
	}

	replace_cid(p, rpid_num, calleridname);
	do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE) );

	if (!(res = check_auth(p, req, user->name, user->secret, user->md5secret, sipmethod, uri2, reliable, req->ignore))) {
		sip_cancel_destroy(p);
		ast_copy_flags(&p->flags[0], &user->flags[0], SIP_FLAGS_TO_COPY);
		ast_copy_flags(&p->flags[1], &user->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
		/* Copy SIP extensions profile from INVITE */
		if (p->sipoptions)
			user->sipoptions = p->sipoptions;

		/* If we have a call limit, set flag */
		if (user->call_limit)
			ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
		if (!ast_strlen_zero(user->context))
			ast_string_field_set(p, context, user->context);
		if (!ast_strlen_zero(user->cid_num)) {
			char *tmp = ast_strdupa(user->cid_num);
			if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
				ast_shrink_phone_number(tmp);
			ast_string_field_set(p, cid_num, tmp);
		}
		if (!ast_strlen_zero(user->cid_name))
			ast_string_field_set(p, cid_name, user->cid_name);
		ast_string_field_set(p, username, user->name);
		ast_string_field_set(p, peername, user->name);
		ast_string_field_set(p, peersecret, user->secret);
		ast_string_field_set(p, peermd5secret, user->md5secret);
		ast_string_field_set(p, subscribecontext, user->subscribecontext);
		ast_string_field_set(p, accountcode, user->accountcode);
		ast_string_field_set(p, language, user->language);
		ast_string_field_set(p, mohsuggest, user->mohsuggest);
		ast_string_field_set(p, mohinterpret, user->mohinterpret);
		p->allowtransfer = user->allowtransfer;
		p->amaflags = user->amaflags;
		p->callgroup = user->callgroup;
		p->pickupgroup = user->pickupgroup;
		if (user->callingpres)	/* User callingpres setting will override RPID header */
			p->callingpres = user->callingpres;
		
		/* Set default codec settings for this call */
		p->capability = user->capability;		/* User codec choice */
		p->jointcapability = user->capability;		/* Our codecs */
		if (p->peercapability)				/* AND with peer's codecs */
			p->jointcapability &= p->peercapability;
		if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
		    (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
			p->noncodeccapability |= AST_RTP_DTMF;
		else
			p->noncodeccapability &= ~AST_RTP_DTMF;
		p->jointnoncodeccapability = p->noncodeccapability;
		p->maxcallbitrate = user->maxcallbitrate;
		/* If we do not support video, remove video from call structure */
		if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(p->capability & AST_FORMAT_VIDEO_MASK)) && p->vrtp) {
			ast_rtp_destroy(p->vrtp);
			p->vrtp = NULL;
		}
		/* If we do not support text, remove text from call structure */
 		if (!ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) && p->trtp) {
 			ast_rtp_destroy(p->trtp);
 			p->trtp = NULL;
 		}
		if (p->udptl) {
			p->t38_maxdatagram = user->t38_maxdatagram;
		}
	}
	unref_user(user);
	return res;
}

/*! \brief Validate peer authentication */
static enum check_auth_result check_peer_ok(struct sip_pvt *p, char *of,
	struct sip_request *req, int sipmethod, struct sockaddr_in *sin,
	struct sip_peer **authpeer,
	enum xmittype reliable,
	char *rpid_num, char *calleridname, char *uri2)
{
	enum check_auth_result res;
	int debug=sip_debug_test_addr(sin);
	struct sip_peer *peer;

	/* For subscribes, match on peer name only; for other methods,
	 * match on IP address-port of the incoming request.
	 */
	peer = (sipmethod == SIP_SUBSCRIBE) ? find_peer(of, NULL, 1, 0, 0) : find_peer(NULL, &p->recv, 1, 0, p->socket.type);

	if (!peer) {
		if (debug)
			ast_verbose("No matching peer for '%s' from '%s:%d'\n",
				of, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
		return AUTH_DONT_KNOW;
	}

	if (debug)
		ast_verbose("Found peer '%s' for '%s' from %s:%d\n",
			peer->name, of, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));

	/* XXX what about p->prefs = peer->prefs; ? */
	/* Set Frame packetization */
	if (p->rtp) {
		ast_rtp_codec_setpref(p->rtp, &peer->prefs);
		p->autoframing = peer->autoframing;
	}

	/* Take the peer */
	ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
	ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);

	if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && p->udptl) {
		p->t38_maxdatagram = peer->t38_maxdatagram;
		set_t38_capabilities(p);
	}

	/* Copy SIP extensions profile to peer */
	/* XXX is this correct before a successful auth ? */
	if (p->sipoptions)
		peer->sipoptions = p->sipoptions;

	replace_cid(p, rpid_num, calleridname);
	do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE));

	ast_string_field_set(p, peersecret, peer->secret);
	ast_string_field_set(p, peermd5secret, peer->md5secret);
	ast_string_field_set(p, subscribecontext, peer->subscribecontext);
	ast_string_field_set(p, mohinterpret, peer->mohinterpret);
	ast_string_field_set(p, mohsuggest, peer->mohsuggest);
	if (peer->callingpres)	/* Peer calling pres setting will override RPID */
		p->callingpres = peer->callingpres;
	if (peer->maxms && peer->lastms)
		p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
 	else
 		p->timer_t1 = peer->timer_t1;
 
 	/* Set timer B to control transaction timeouts */
 	if (peer->timer_b)
 		p->timer_b = peer->timer_b;
 	else
 		p->timer_b = 64 * p->timer_t1;
 
	if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
		/* Pretend there is no required authentication */
		ast_string_field_set(p, peersecret, NULL);
		ast_string_field_set(p, peermd5secret, NULL);
	}
	if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, req->ignore))) {
		ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
		ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
		/* If we have a call limit, set flag */
		if (peer->call_limit)
			ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
		ast_string_field_set(p, peername, peer->name);
		ast_string_field_set(p, authname, peer->name);

		if (sipmethod == SIP_INVITE) {
			/* copy channel vars */
			p->chanvars = copy_vars(peer->chanvars);
		}

		if (authpeer) {
			(*authpeer) = ASTOBJ_REF(peer);	/* Add a ref to the object here, to keep it in memory a bit longer if it is realtime */
		}

		if (!ast_strlen_zero(peer->username)) {
			ast_string_field_set(p, username, peer->username);
			/* Use the default username for authentication on outbound calls */
			/* XXX this takes the name from the caller... can we override ? */
			ast_string_field_set(p, authname, peer->username);
		}
		if (!ast_strlen_zero(peer->cid_num)) {
			char *tmp = ast_strdupa(peer->cid_num);
			if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
				ast_shrink_phone_number(tmp);
			ast_string_field_set(p, cid_num, tmp);
		}
		if (!ast_strlen_zero(peer->cid_name)) 
			ast_string_field_set(p, cid_name, peer->cid_name);
		ast_string_field_set(p, fullcontact, peer->fullcontact);
		if (!ast_strlen_zero(peer->context))
			ast_string_field_set(p, context, peer->context);
		ast_string_field_set(p, peersecret, peer->secret);
		ast_string_field_set(p, peermd5secret, peer->md5secret);
		ast_string_field_set(p, language, peer->language);
		ast_string_field_set(p, accountcode, peer->accountcode);
		p->amaflags = peer->amaflags;
		p->callgroup = peer->callgroup;
		p->pickupgroup = peer->pickupgroup;
		p->capability = peer->capability;
		p->prefs = peer->prefs;
		p->jointcapability = peer->capability;
		if (p->peercapability)
			p->jointcapability &= p->peercapability;
		p->maxcallbitrate = peer->maxcallbitrate;
		if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) || !(p->capability & AST_FORMAT_VIDEO_MASK)) && p->vrtp) {
			ast_rtp_destroy(p->vrtp);
			p->vrtp = NULL;
		}
		if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) || !(p->capability & AST_FORMAT_TEXT_MASK)) && p->trtp) {
			ast_rtp_destroy(p->trtp);
			p->trtp = NULL;
 		}
		if (p->udptl) {
			p->t38_maxdatagram = peer->t38_maxdatagram;
		}
		if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
		    (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
			p->noncodeccapability |= AST_RTP_DTMF;
		else
			p->noncodeccapability &= ~AST_RTP_DTMF;
		p->jointnoncodeccapability = p->noncodeccapability;
	}
	unref_peer(peer);
	return res;
}


/*! \brief  Check if matching user or peer is defined 
 	Match user on From: user name and peer on IP/port
	This is used on first invite (not re-invites) and subscribe requests 
    \return 0 on success, non-zero on failure
*/
static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
					      int sipmethod, char *uri, enum xmittype reliable,
					      struct sockaddr_in *sin, struct sip_peer **authpeer)
{
	char from[256];
	char *dummy;	/* dummy return value for parse_uri */
	char *domain;	/* dummy return value for parse_uri */
	char *of;
	char rpid_num[50];
	const char *rpid;
	enum check_auth_result res;
	char calleridname[50];
	char *uri2 = ast_strdupa(uri);

	terminate_uri(uri2);	/* trim extra stuff */

	ast_copy_string(from, get_header(req, "From"), sizeof(from));
	if (pedanticsipchecking)
		ast_uri_decode(from);
	/* XXX here tries to map the username for invite things */
	memset(calleridname, 0, sizeof(calleridname));
	get_calleridname(from, calleridname, sizeof(calleridname));
	if (calleridname[0])
		ast_string_field_set(p, cid_name, calleridname);

	rpid = get_header(req, "Remote-Party-ID");
	memset(rpid_num, 0, sizeof(rpid_num));
	if (!ast_strlen_zero(rpid)) 
		p->callingpres = get_rpid_num(rpid, rpid_num, sizeof(rpid_num));

	of = get_in_brackets(from);
	if (ast_strlen_zero(p->exten)) {
		char *t = uri2;
		if (!strncasecmp(t, "sip:", 4))
			t+= 4;
		else if (!strncasecmp(t, "sips:", 5))
			t += 5;
		ast_string_field_set(p, exten, t);
		t = strchr(p->exten, '@');
		if (t)
			*t = '\0';
		if (ast_strlen_zero(p->our_contact))
			build_contact(p);
	}
	/* save the URI part of the From header */
	ast_string_field_set(p, from, of);


	/* ignore all fields but name */
	if (parse_uri(of, "sip:,sips:", &of, &dummy, &domain, &dummy, &dummy, NULL)) {
		ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
	}

	if (ast_strlen_zero(of)) {
		/* XXX note: the original code considered a missing @host
		 * as a username-only URI. The SIP RFC (19.1.1) says that
		 * this is wrong, and it should be considered as a domain-only URI.
		 * For backward compatibility, we keep this block, but it is
		 * really a mistake and should go away.
		 */
		of = domain;
	} else {
		char *tmp = ast_strdupa(of);
		/* We need to be able to handle auth-headers looking like
			<sip:8164444422;phone-context=+1@1.2.3.4:5060;user=phone;tag=SDadkoa01-gK0c3bdb43>
		*/
		tmp = strsep(&tmp, ";");
		if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
			ast_shrink_phone_number(tmp);
		ast_string_field_set(p, cid_num, tmp);
	}

	if (global_match_auth_username) {
		/*
		 * XXX This is experimental code to grab the search key from the
		 * Auth header's username instead of the 'From' name, if available.
		 * Do not enable this block unless you understand the side effects (if any!)
		 * Note, the search for "username" should be done in a more robust way.
		 * Note2, at the moment we check both fields, though maybe we should
		 * pick one or another depending on the request ? XXX
		 */
		const char *hdr = get_header(req, "Authorization");
		if (ast_strlen_zero(hdr))
			hdr = get_header(req, "Proxy-Authorization");

		if ( !ast_strlen_zero(hdr) && (hdr = strstr(hdr, "username=\"")) ) {
			ast_copy_string(from, hdr + strlen("username=\""), sizeof(from));
			of = from;
			of = strsep(&of, "\"");
		}
	}

	if (!authpeer) {
		/* If we are looking for a peer, don't check the
		   user objects (or realtime) */
		res = check_user_ok(p, of, req, sipmethod, sin,
			reliable, rpid_num, calleridname, uri2);
		if (res != AUTH_DONT_KNOW)
			return res;
	}

	res = check_peer_ok(p, of, req, sipmethod, sin,
			authpeer, reliable, rpid_num, calleridname, uri2);
	if (res != AUTH_DONT_KNOW)
		return res;

	/* Finally, apply the guest policy */
	if (global_allowguest) {
		replace_cid(p, rpid_num, calleridname);
		res = AUTH_SUCCESSFUL;
	} else if (global_alwaysauthreject)
		res = AUTH_FAKE_AUTH; /* reject with fake authorization request */
	else
		res = AUTH_SECRET_FAILED; /* we don't want any guests, authentication will fail */


	if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT)) {
		ast_set_flag(&p->flags[0], SIP_NAT_ROUTE);
	}

	return res;
}

/*! \brief  Find user 
	If we get a match, this will add a reference pointer to the user object in ASTOBJ, that needs to be unreferenced
*/
static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin)
{
	return check_user_full(p, req, sipmethod, uri, reliable, sin, NULL);
}

/*! \brief  Get text out of a SIP MESSAGE packet */
static int get_msg_text(char *buf, int len, struct sip_request *req)
{
	int x;
	int y;

	buf[0] = '\0';
	y = len - strlen(buf) - 5;
	if (y < 0)
		y = 0;
	for (x=0;x<req->lines;x++) {
		strncat(buf, req->line[x], y); /* safe */
		y -= strlen(req->line[x]) + 1;
		if (y < 0)
			y = 0;
		if (y != 0)
			strcat(buf, "\n"); /* safe */
	}
	return 0;
}


/*! \brief  Receive SIP MESSAGE method messages
\note	We only handle messages within current calls currently 
	Reference: RFC 3428 */
static void receive_message(struct sip_pvt *p, struct sip_request *req)
{
	char buf[1024];
	struct ast_frame f;
	const char *content_type = get_header(req, "Content-Type");

	if (strncmp(content_type, "text/plain", strlen("text/plain"))) { /* No text/plain attachment */
		transmit_response(p, "415 Unsupported Media Type", req); /* Good enough, or? */
		if (!p->owner)
			sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
		return;
	}

	if (get_msg_text(buf, sizeof(buf), req)) {
		ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
		transmit_response(p, "202 Accepted", req);
		if (!p->owner)
			sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
		return;
	}

	if (p->owner) {
		if (sip_debug_test_pvt(p))
			ast_verbose("Message received: '%s'\n", buf);
		memset(&f, 0, sizeof(f));
		f.frametype = AST_FRAME_TEXT;
		f.subclass = 0;
		f.offset = 0;
		f.data = buf;
		f.datalen = strlen(buf);
		ast_queue_frame(p->owner, &f);
		transmit_response(p, "202 Accepted", req); /* We respond 202 accepted, since we relay the message */
	} else { /* Message outside of a call, we do not support that */
		ast_log(LOG_WARNING, "Received message to %s from %s, dropped it...\n  Content-Type:%s\n  Message: %s\n", get_header(req, "To"), get_header(req, "From"), content_type, buf);
		transmit_response(p, "405 Method Not Allowed", req);
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
	}
	return;
}

/*! \brief  CLI Command to show calls within limits set by call_limit */
static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
#define FORMAT "%-25.25s %-15.15s %-15.15s \n"
#define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
	char ilimits[40];
	char iused[40];
	int showall = FALSE;

	switch (cmd) {
	case CLI_INIT:
		e->command = "sip show inuse";
		e->usage =
			"Usage: sip show inuse [all]\n"
			"       List all SIP users and peers usage counters and limits.\n"
			"       Add option \"all\" to show all devices, not only those with a limit.\n";
		return NULL;
	case CLI_GENERATE:
		return NULL;
	}

	if (a->argc < 3) 
		return CLI_SHOWUSAGE;

	if (a->argc == 4 && !strcmp(a->argv[3], "all")) 
		showall = TRUE;
	
	ast_cli(a->fd, FORMAT, "* User name", "In use", "Limit");
	ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
		ASTOBJ_RDLOCK(iterator);
		if (iterator->call_limit)
			snprintf(ilimits, sizeof(ilimits), "%d", iterator->call_limit);
		else 
			ast_copy_string(ilimits, "N/A", sizeof(ilimits));
		snprintf(iused, sizeof(iused), "%d", iterator->inUse);
		if (showall || iterator->call_limit)
			ast_cli(a->fd, FORMAT2, iterator->name, iused, ilimits);
		ASTOBJ_UNLOCK(iterator);
	} while (0) );

	ast_cli(a->fd, FORMAT, "* Peer name", "In use", "Limit");

	ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
		ASTOBJ_RDLOCK(iterator);
		if (iterator->call_limit)
			snprintf(ilimits, sizeof(ilimits), "%d", iterator->call_limit);
		else 
			ast_copy_string(ilimits, "N/A", sizeof(ilimits));
		snprintf(iused, sizeof(iused), "%d/%d/%d", iterator->inUse, iterator->inRinging, iterator->onHold);
		if (showall || iterator->call_limit)
			ast_cli(a->fd, FORMAT2, iterator->name, iused, ilimits);
		ASTOBJ_UNLOCK(iterator);
	} while (0) );

	return CLI_SUCCESS;
#undef FORMAT
#undef FORMAT2
}


/*! \brief Convert transfer mode to text string */
static char *transfermode2str(enum transfermodes mode)
{
	if (mode == TRANSFER_OPENFORALL)
		return "open";
	else if (mode == TRANSFER_CLOSED)
		return "closed";
	return "strict";
}

static struct _map_x_s natmodes[] = {
	{ SIP_NAT_NEVER,        "No"},
	{ SIP_NAT_ROUTE,        "Route"},
	{ SIP_NAT_ALWAYS,       "Always"},
	{ SIP_NAT_RFC3581,      "RFC3581"},
	{ -1,                   NULL}, /* terminator */
};

/*! \brief  Convert NAT setting to text string */
static const char *nat2str(int nat)
{
	return map_x_s(natmodes, nat, "Unknown");
}

/*! \brief  Report Peer status in character string
 *  \return 0 if peer is unreachable, 1 if peer is online, -1 if unmonitored
 */


/* Session-Timer Modes */
static struct _map_x_s stmodes[] = {
        { SESSION_TIMER_MODE_ACCEPT,    "Accept"},
        { SESSION_TIMER_MODE_ORIGINATE, "Originate"},
        { SESSION_TIMER_MODE_REFUSE,    "Refuse"},
        { -1,                           NULL},
};

static const char *stmode2str(enum st_mode m)
{
	return map_x_s(stmodes, m, "Unknown");
}

static enum st_mode str2stmode(const char *s)
{
	return map_s_x(stmodes, s, -1);
}

/* Session-Timer Refreshers */
static struct _map_x_s strefreshers[] = {
        { SESSION_TIMER_REFRESHER_AUTO,     "auto"},
        { SESSION_TIMER_REFRESHER_UAC,      "uac"},
        { SESSION_TIMER_REFRESHER_UAS,      "uas"},
        { -1,                               NULL},
};

static const char *strefresher2str(enum st_refresher r)
{
	return map_x_s(strefreshers, r, "Unknown");
}

static enum st_refresher str2strefresher(const char *s)
{
	return map_s_x(strefreshers, s, -1);
}


static int peer_status(struct sip_peer *peer, char *status, int statuslen)
{
	int res = 0;
	if (peer->maxms) {
		if (peer->lastms < 0) {
			ast_copy_string(status, "UNREACHABLE", statuslen);
		} else if (peer->lastms > peer->maxms) {
			snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
			res = 1;
		} else if (peer->lastms) {
			snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
			res = 1;
		} else {
			ast_copy_string(status, "UNKNOWN", statuslen);
		}
	} else { 
		ast_copy_string(status, "Unmonitored", statuslen);
		/* Checking if port is 0 */
		res = -1;
	}
	return res;
}

/*! \brief return Yes or No depending on the argument.
 * This is used in many places in CLI command, having a function to generate
 * this helps maintaining a consistent output (and possibly emitting the
 * output in other languages, at some point).
 */
static const char *cli_yesno(int x)
{
	return x ? "Yes" : "No";
}

/*! \brief  Show active TCP connections */
static char *sip_show_tcp(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
	struct sip_threadinfo *th;

#define FORMAT2 "%-30.30s %3.6s %9.9s %6.6s\n"
#define FORMAT  "%-30.30s %-6d %-9.9s %-6.6s\n"

	switch (cmd) {
	case CLI_INIT:
		e->command = "sip show tcp";
		e->usage =
			"Usage: sip show tcp\n"
			"       Lists all active TCP/TLS sessions.\n";
		return NULL;
	case CLI_GENERATE:
		return NULL;
	}

	if (a->argc != 3)
		return CLI_SHOWUSAGE;

	ast_cli(a->fd, FORMAT2, "Host", "Port", "Transport", "Type");
	AST_LIST_LOCK(&threadl);
	AST_LIST_TRAVERSE(&threadl, th, list) {
		ast_cli(a->fd, FORMAT, ast_inet_ntoa(th->tcptls_session->requestor.sin_addr), 
			ntohs(th->tcptls_session->requestor.sin_port), 
			get_transport(th->type), 
			(th->tcptls_session->client ? "Client" : "Server"));

	}
	AST_LIST_UNLOCK(&threadl);
	return CLI_SUCCESS;
#undef FORMAT
#undef FORMAT2
}

/*! \brief  CLI Command 'SIP Show Users' */
static char *sip_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
	regex_t regexbuf;
	int havepattern = FALSE;

#define FORMAT  "%-25.25s  %-15.15s  %-15.15s  %-15.15s  %-5.5s%-10.10s\n"

	switch (cmd) {
	case CLI_INIT:
		e->command = "sip show users";
		e->usage =
			"Usage: sip show users [like <pattern>]\n"
			"       Lists all known SIP users.\n"
			"       Optional regular expression pattern is used to filter the user list.\n";
		return NULL;
	case CLI_GENERATE:
		return NULL;
	}

	switch (a->argc) {
	case 5:
		if (!strcasecmp(a->argv[3], "like")) {
			if (regcomp(&regexbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
				return CLI_SHOWUSAGE;
			havepattern = TRUE;
		} else
			return CLI_SHOWUSAGE;
	case 3:
		break;
	default:
		return CLI_SHOWUSAGE;
	}

	ast_cli(a->fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "NAT");
	ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
		ASTOBJ_RDLOCK(iterator);

		if (havepattern && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
			ASTOBJ_UNLOCK(iterator);
			continue;
		}

		ast_cli(a->fd, FORMAT, iterator->name, 
			iterator->secret, 
			iterator->accountcode,
			iterator->context,
			cli_yesno(iterator->ha != NULL),
			nat2str(ast_test_flag(&iterator->flags[0], SIP_NAT)));
		ASTOBJ_UNLOCK(iterator);
	} while (0)
	);

	if (havepattern)
		regfree(&regexbuf);

	return CLI_SUCCESS;
#undef FORMAT
}

/*! \brief Manager Action SIPShowRegistry description */
static char mandescr_show_registry[] =
"Description: Lists all registration requests and status\n"
"Registrations will follow as separate events. followed by a final event called\n"
"RegistrationsComplete.\n"
"Variables: \n"
"  ActionID: <id>       Action ID for this transaction. Will be returned.\n";

/*! \brief Show SIP registrations in the manager API */
static int manager_show_registry(struct mansession *s, const struct message *m)
{
	const char *id = astman_get_header(m, "ActionID");
	char idtext[256] = "";
	int total = 0;

	if (!ast_strlen_zero(id))
		snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);

	astman_send_listack(s, m, "Registrations will follow", "start");

	ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
		ASTOBJ_RDLOCK(iterator);
		astman_append(s,
			"Event: RegistryEntry\r\n"
			"%s"
			"Host: %s\r\n"
			"Port: %d\r\n"
			"Username: %s\r\n"
			"Refresh: %d\r\n"
			"State: %s\r\n"
			"RegistrationTime: %ld\r\n"
			"\r\n", idtext, iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT,
					  iterator->username, iterator->refresh, regstate2str(iterator->regstate), (long) iterator->regtime.tv_sec);
		ASTOBJ_UNLOCK(iterator);
		total++;
	} while(0));

	astman_append(s,
		"Event: RegistrationsComplete\r\n"
		"EventList: Complete\r\n"
		"ListItems: %d\r\n"
		"%s"
		"\r\n", total, idtext);
	
	return 0;
}

static char mandescr_show_peers[] = 
"Description: Lists SIP peers in text format with details on current status.\n"
"Peerlist will follow as separate events, followed by a final event called\n"
"PeerlistComplete.\n"
"Variables: \n"
"  ActionID: <id>	Action ID for this transaction. Will be returned.\n";

/*! \brief  Show SIP peers in the manager API */
/*    Inspired from chan_iax2 */
static int manager_sip_show_peers(struct mansession *s, const struct message *m)
{
	const char *id = astman_get_header(m, "ActionID");
	const char *a[] = {"sip", "show", "peers"};
	char idtext[256] = "";
	int total = 0;

	if (!ast_strlen_zero(id))
		snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);

	astman_send_listack(s, m, "Peer status list will follow", "start");
	/* List the peers in separate manager events */
	_sip_show_peers(-1, &total, s, m, 3, a);
	/* Send final confirmation */
	astman_append(s,
	"Event: PeerlistComplete\r\n"
	"EventList: Complete\r\n"
	"ListItems: %d\r\n"
	"%s"
	"\r\n", total, idtext);
	return 0;
}

/*! \brief  CLI Show Peers command */
static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
	switch (cmd) {
	case CLI_INIT:
		e->command = "sip show peers";
		e->usage =
			"Usage: sip show peers [like <pattern>]\n"
			"       Lists all known SIP peers.\n"
			"       Optional regular expression pattern is used to filter the peer list.\n";
		return NULL;
	case CLI_GENERATE:
		return NULL;
	}

	return _sip_show_peers(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
}

/*! \brief Execute sip show peers command */
static char *_sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
{
	regex_t regexbuf;
	int havepattern = FALSE;

/* the last argument is left-aligned, so we don't need a size anyways */
#define FORMAT2 "%-25.25s  %-15.15s %-3.3s %-3.3s %-3.3s %-8s %-10s %s\n"
#define FORMAT  "%-25.25s  %-15.15s %-3.3s %-3.3s %-3.3s %-8d %-10s %s\n"

	char name[256];
	int total_peers = 0;
	int peers_mon_online = 0;
	int peers_mon_offline = 0;
	int peers_unmon_offline = 0;
	int peers_unmon_online = 0;
	const char *id;
	char idtext[256] = "";
	int realtimepeers;

	realtimepeers = ast_check_realtime("sippeers");

	if (s) {	/* Manager - get ActionID */
		id = astman_get_header(m, "ActionID");
		if (!ast_strlen_zero(id))
			snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
	}

	switch (argc) {
	case 5:
		if (!strcasecmp(argv[3], "like")) {
			if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
				return CLI_SHOWUSAGE;
			havepattern = TRUE;
		} else
			return CLI_SHOWUSAGE;
	case 3:
		break;
	default:
		return CLI_SHOWUSAGE;
	}

	if (!s) /* Normal list */
		ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Nat", "ACL", "Port", "Status", (realtimepeers ? "Realtime" : ""));
	
	ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
		char status[20] = "";
		char srch[2000];
		char pstatus;
		
		ASTOBJ_RDLOCK(iterator);

		if (havepattern && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
			ASTOBJ_UNLOCK(iterator);
			continue;
		}

		if (!ast_strlen_zero(iterator->username) && !s)
			snprintf(name, sizeof(name), "%s/%s", iterator->name, iterator->username);
		else
			ast_copy_string(name, iterator->name, sizeof(name));
		
		pstatus = peer_status(iterator, status, sizeof(status));
		if (pstatus == 1)
			peers_mon_online++;
		else if (pstatus == 0)
			peers_mon_offline++;
		else {
			if (iterator->addr.sin_port == 0)
				peers_unmon_offline++;
			else
				peers_unmon_online++;
		}

		snprintf(srch, sizeof(srch), FORMAT, name,
			iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iterator->addr.sin_addr) : "(Unspecified)",
			iterator->host_dynamic ? " D " : "   ", 	/* Dynamic or not? */
			ast_test_flag(&iterator->flags[0], SIP_NAT_ROUTE) ? " N " : "   ",	/* NAT=yes? */
			iterator->ha ? " A " : "   ", 	/* permit/deny */
			ntohs(iterator->addr.sin_port), status,
			realtimepeers ? (iterator->is_realtime ? "Cached RT":"") : "");

		if (!s)  {/* Normal CLI list */
			ast_cli(fd, FORMAT, name, 
			iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iterator->addr.sin_addr) : "(Unspecified)",
			iterator->host_dynamic ? " D " : "   ", 	/* Dynamic or not? */
			ast_test_flag(&iterator->flags[0], SIP_NAT_ROUTE) ? " N " : "   ",	/* NAT=yes? */
			iterator->ha ? " A " : "   ",       /* permit/deny */
			
			ntohs(iterator->addr.sin_port), status,
			realtimepeers ? (iterator->is_realtime ? "Cached RT":"") : "");
		} else {	/* Manager format */
			/* The names here need to be the same as other channels */
			astman_append(s, 
			"Event: PeerEntry\r\n%s"
			"Channeltype: SIP\r\n"
			"ObjectName: %s\r\n"
			"ChanObjectType: peer\r\n"	/* "peer" or "user" */
			"IPaddress: %s\r\n"
			"IPport: %d\r\n"
			"Dynamic: %s\r\n"
			"Natsupport: %s\r\n"
			"VideoSupport: %s\r\n"
			"TextSupport: %s\r\n"
			"ACL: %s\r\n"
			"Status: %s\r\n"
			"RealtimeDevice: %s\r\n\r\n", 
			idtext,
			iterator->name, 
			iterator->addr.sin_addr.s_addr ? ast_inet_ntoa(iterator->addr.sin_addr) : "-none-",
			ntohs(iterator->addr.sin_port), 
			iterator->host_dynamic ? "yes" : "no", 	/* Dynamic or not? */
			ast_test_flag(&iterator->flags[0], SIP_NAT_ROUTE) ? "yes" : "no",	/* NAT=yes? */
			ast_test_flag(&iterator->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no",	/* VIDEOSUPPORT=yes? */
			ast_test_flag(&iterator->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "yes" : "no",	/* TEXTSUPPORT=yes? */
			iterator->ha ? "yes" : "no",       /* permit/deny */
			status,
			realtimepeers ? (iterator->is_realtime ? "yes":"no") : "no");
		}

		ASTOBJ_UNLOCK(iterator);

		total_peers++;
	} while(0) );
	
	if (!s)
		ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
		        total_peers, peers_mon_online, peers_mon_offline, peers_unmon_online, peers_unmon_offline);

	if (havepattern)
		regfree(&regexbuf);

	if (total)
		*total = total_peers;
	

	return CLI_SUCCESS;
#undef FORMAT
#undef FORMAT2
}

/*! \brief List all allocated SIP Objects (realtime or static) */
static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
	char tmp[256];
	
	switch (cmd) {
	case CLI_INIT:
		e->command = "sip show objects";
		e->usage =
			"Usage: sip show objects\n"
			"       Lists status of known SIP objects\n";
		return NULL;
	case CLI_GENERATE:
		return NULL;
	}	

	if (a->argc != 3)
		return CLI_SHOWUSAGE;
	ast_cli(a->fd, "-= User objects: %d static, %d realtime =-\n\n", suserobjs, ruserobjs);
	ASTOBJ_CONTAINER_DUMP(a->fd, tmp, sizeof(tmp), &userl);
	ast_cli(a->fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
	ASTOBJ_CONTAINER_DUMP(a->fd, tmp, sizeof(tmp), &peerl);
	ast_cli(a->fd, "-= Registry objects: %d =-\n\n", regobjs);
	ASTOBJ_CONTAINER_DUMP(a->fd, tmp, sizeof(tmp), &regl);
	return CLI_SUCCESS;
}
/*! \brief Print call group and pickup group */
static void  print_group(int fd, ast_group_t group, int crlf)
{
	char buf[256];
	ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
}

/*! \brief mapping between dtmf flags and strings */
static struct _map_x_s dtmfstr[] = {
	{ SIP_DTMF_RFC2833,     "rfc2833" },
	{ SIP_DTMF_INFO,        "info" },
	{ SIP_DTMF_SHORTINFO,   "shortinfo" },
	{ SIP_DTMF_INBAND,      "inband" },
	{ SIP_DTMF_AUTO,        "auto" },
	{ -1,                   NULL }, /* terminator */
};

/*! \brief Convert DTMF mode to printable string */
static const char *dtmfmode2str(int mode)
{
	return map_x_s(dtmfstr, mode, "<error>");
}

/*! \brief maps a string to dtmfmode, returns -1 on error */
static int str2dtmfmode(const char *str)
{
	return map_s_x(dtmfstr, str, -1);
}

static struct _map_x_s insecurestr[] = {
	{ SIP_INSECURE_PORT,    "port" },
	{ SIP_INSECURE_INVITE,  "invite" },
	{ SIP_INSECURE_PORT | SIP_INSECURE_INVITE, "port,invite" },
	{ 0,                    "no" },
	{ -1,                   NULL }, /* terminator */
};

/*! \brief Convert Insecure setting to printable string */
static const char *insecure2str(int mode)
{
	return map_x_s(insecurestr, mode, "<error>");
}

/*! \brief Destroy disused contexts between reloads
	Only used in reload_config so the code for regcontext doesn't get ugly
*/
static void cleanup_stale_contexts(char *new, char *old)
{
	char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];

	while ((oldcontext = strsep(&old, "&"))) {
		stalecontext = '\0';
		ast_copy_string(newlist, new, sizeof(newlist));
		stringp = newlist;
		while ((newcontext = strsep(&stringp, "&"))) {
			if (!strcmp(newcontext, oldcontext)) {
				/* This is not the context you're looking for */
				stalecontext = '\0';
				break;
			} else if (strcmp(newcontext, oldcontext)) {
				stalecontext = oldcontext;
			}
			
		}
		if (stalecontext)
			ast_context_destroy(ast_context_find(stalecontext), "SIP");
	}
}

/*! \brief Remove temporary realtime objects from memory (CLI) */
static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
	struct sip_peer *peer;
	struct sip_user *user;
	int pruneuser = FALSE;
	int prunepeer = FALSE;
	int multi = FALSE;
	char *name = NULL;
	regex_t regexbuf;

	if (cmd == CLI_INIT) {
		e->command = "sip prune realtime [peer|user|all] [all|like]";
		e->usage =
		"Usage: sip prune realtime [peer|user] [<name>|all|like <pattern>]\n"
		"       Prunes object(s) from the cache.\n"
		"       Optional regular expression pattern is used to filter the objects.\n";
		return NULL;
	} else if (cmd == CLI_GENERATE) {
		if (a->pos == 4) {
			if (strcasestr(a->line, "realtime peer"))
				return complete_sip_peer(a->word, a->n, SIP_PAGE2_RTCACHEFRIENDS);
			else if (strcasestr(a->line, "realtime user"))
				return complete_sip_user(a->word, a->n, SIP_PAGE2_RTCACHEFRIENDS);
		}
		return NULL;
	}
	switch (a->argc) {
	case 4:
		name = a->argv[3];
		/* we accept a name in position 3, but keywords are not good. */
		if (!strcasecmp(name, "user") || !strcasecmp(name, "peer") ||
		    !strcasecmp(name, "like"))
			return CLI_SHOWUSAGE;
		pruneuser = prunepeer = TRUE;
		if (!strcasecmp(name, "all")) {
			multi = TRUE;
			name = NULL;
		}
		/* else a single name, already set */
		break;
	case 5:
		/* sip prune realtime {user|peer|like} name */
		name = a->argv[4];
		if (!strcasecmp(a->argv[3], "user"))
			pruneuser = TRUE;
		else if (!strcasecmp(a->argv[3], "peer"))
			prunepeer = TRUE;
		else if (!strcasecmp(a->argv[3], "like")) {
			pruneuser = prunepeer = TRUE;
			multi = TRUE;
		} else
			return CLI_SHOWUSAGE;
		if (!strcasecmp(a->argv[4], "like"))
			return CLI_SHOWUSAGE;
		if (!multi && !strcasecmp(a->argv[4], "all")) {
			multi = TRUE;
			name = NULL;
		}
		break;
	case 6:
		name = a->argv[5];
		multi = TRUE;
		/* sip prune realtime {user|peer} like name */
		if (strcasecmp(a->argv[4], "like"))
			return CLI_SHOWUSAGE;
		if (!strcasecmp(a->argv[3], "user")) {
			pruneuser = TRUE;
		} else if (!strcasecmp(a->argv[3], "peer")) {
			prunepeer = TRUE;
		} else
			return CLI_SHOWUSAGE;
		break;
	default:
		return CLI_SHOWUSAGE;
	}

	if (multi && name) {
		if (regcomp(&regexbuf, name, REG_EXTENDED | REG_NOSUB))
			return CLI_SHOWUSAGE;
	}

	if (multi) {
		if (prunepeer) {
			int pruned = 0;

			ASTOBJ_CONTAINER_WRLOCK(&peerl);
			ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
				ASTOBJ_RDLOCK(iterator);
				if (name && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
					ASTOBJ_UNLOCK(iterator);
					continue;
				};
				if (ast_test_flag(&iterator->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
					ASTOBJ_MARK(iterator);
					pruned++;
				}
				ASTOBJ_UNLOCK(iterator);
			} while (0) );
			if (pruned) {
				ASTOBJ_CONTAINER_PRUNE_MARKED(&peerl, sip_destroy_peer);
				ast_cli(a->fd, "%d peers pruned.\n", pruned);
			} else
				ast_cli(a->fd, "No peers found to prune.\n");
			ASTOBJ_CONTAINER_UNLOCK(&peerl);
		}
		if (pruneuser) {
			int pruned = 0;

			ASTOBJ_CONTAINER_WRLOCK(&userl);
			ASTOBJ_CONTAINER_TRAVERSE(&userl, 1, do {
				ASTOBJ_RDLOCK(iterator);
				if (name && regexec(&regexbuf, iterator->name, 0, NULL, 0)) {
					ASTOBJ_UNLOCK(iterator);
					continue;
				};
				if (ast_test_flag(&iterator->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
					ASTOBJ_MARK(iterator);
					pruned++;
				}
				ASTOBJ_UNLOCK(iterator);
			} while (0) );
			if (pruned) {
				ASTOBJ_CONTAINER_PRUNE_MARKED(&userl, sip_destroy_user);
				ast_cli(a->fd, "%d users pruned.\n", pruned);
			} else
				ast_cli(a->fd, "No users found to prune.\n");
			ASTOBJ_CONTAINER_UNLOCK(&userl);
		}
	} else {
		if (prunepeer) {
			if ((peer = ASTOBJ_CONTAINER_FIND_UNLINK(&peerl, name))) {
				if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
					ast_cli(a->fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
					ASTOBJ_CONTAINER_LINK(&peerl, peer);
				} else
					ast_cli(a->fd, "Peer '%s' pruned.\n", name);
				unref_peer(peer);
			} else
				ast_cli(a->fd, "Peer '%s' not found.\n", name);
		}
		if (pruneuser) {
			if ((user = ASTOBJ_CONTAINER_FIND_UNLINK(&userl, name))) {
				if (!ast_test_flag(&user->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
					ast_cli(a->fd, "User '%s' is not a Realtime user, cannot be pruned.\n", name);
					ASTOBJ_CONTAINER_LINK(&userl, user);
				} else
					ast_cli(a->fd, "User '%s' pruned.\n", name);
				unref_user(user);
			} else
				ast_cli(a->fd, "User '%s' not found.\n", name);
		}
	}

	return CLI_SUCCESS;
}

/*! \brief Print codec list from preference to CLI/manager */
static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
{
	int x, codec;

	for(x = 0; x < 32 ; x++) {
		codec = ast_codec_pref_index(pref, x);
		if (!codec)
			break;
		ast_cli(fd, "%s", ast_getformatname(codec));
		ast_cli(fd, ":%d", pref->framing[x]);
		if (x < 31 && ast_codec_pref_index(pref, x + 1))
			ast_cli(fd, ",");
	}
	if (!x)
		ast_cli(fd, "none");
}

/*! \brief Print domain mode to cli */
static const char *domain_mode_to_text(const enum domain_mode mode)
{
	switch (mode) {
	case SIP_DOMAIN_AUTO:
		return "[Automatic]";
	case SIP_DOMAIN_CONFIG:
		return "[Configured]";
	}

	return "";
}

/*! \brief CLI command to list local domains */
static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
	struct domain *d;
#define FORMAT "%-40.40s %-20.20s %-16.16s\n"

	switch (cmd) {
	case CLI_INIT:
		e->command = "sip show domains";
		e->usage =
			"Usage: sip show domains\n"
			"       Lists all configured SIP local domains.\n"
			"       Asterisk only responds to SIP messages to local domains.\n";
		return NULL;
	case CLI_GENERATE:
		return NULL;
	}

	if (AST_LIST_EMPTY(&domain_list)) {
		ast_cli(a->fd, "SIP Domain support not enabled.\n\n");
		return CLI_SUCCESS;
	} else {
		ast_cli(a->fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
		AST_LIST_LOCK(&domain_list);
		AST_LIST_TRAVERSE(&domain_list, d, list)
			ast_cli(a->fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
				domain_mode_to_text(d->mode));
		AST_LIST_UNLOCK(&domain_list);
		ast_cli(a->fd, "\n");
		return CLI_SUCCESS;
	}
}
#undef FORMAT

static char mandescr_show_peer[] = 
"Description: Show one SIP peer with details on current status.\n"
"Variables: \n"
"  Peer: <name>           The peer name you want to check.\n"
"  ActionID: <id>	  Optional action ID for this AMI transaction.\n";

/*! \brief Show SIP peers in the manager API  */
static int manager_sip_show_peer(struct mansession *s, const struct message *m)
{
	const char *a[4];
	const char *peer;

	peer = astman_get_header(m, "Peer");
	if (ast_strlen_zero(peer)) {
		astman_send_error(s, m, "Peer: <name> missing.");
		return 0;
	}
	a[0] = "sip";
	a[1] = "show";
	a[2] = "peer";
	a[3] = peer;

	_sip_show_peer(1, -1, s, m, 4, a);
	astman_append(s, "\r\n\r\n" );
	return 0;
}

/*! \brief Show one peer in detail */
static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
	switch (cmd) {
	case CLI_INIT:
		e->command = "sip show peer";
		e->usage =
			"Usage: sip show peer <name> [load]\n"
			"       Shows all details on one SIP peer and the current status.\n"
			"       Option \"load\" forces lookup of peer in realtime storage.\n";
		return NULL;
	case CLI_GENERATE:
		return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
	}
	return _sip_show_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
}

/*! \brief list peer mailboxes to CLI */
static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer)
{
	struct sip_mailbox *mailbox;

	AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
		ast_str_append(mailbox_str, 0, "%s%s%s%s",
			mailbox->mailbox,
			ast_strlen_zero(mailbox->context) ? "" : "@",
			S_OR(mailbox->context, ""),
			AST_LIST_NEXT(mailbox, entry) ? "," : "");
	}
}

static struct _map_x_s faxecmodes[] = {
	{ SIP_PAGE2_T38SUPPORT_UDPTL,			"None"},
	{ SIP_PAGE2_T38SUPPORT_UDPTL_FEC,		"FEC"},
	{ SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY,	"Redundancy"},
	{ -1,						NULL},
};

static const char *faxec2str(int faxec)
{
	return map_x_s(faxecmodes, faxec, "Unknown");
}

/*! \brief Show one peer in detail (main function) */
static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
{
	char status[30] = "";
	char cbuf[256];
	struct sip_peer *peer;
	char codec_buf[512];
	struct ast_codec_pref *pref;
	struct ast_variable *v;
	struct sip_auth *auth;
	int x = 0, codec = 0, load_realtime;
	int realtimepeers;

	realtimepeers = ast_check_realtime("sippeers");

	if (argc < 4)
		return CLI_SHOWUSAGE;

	load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
	peer = find_peer(argv[3], NULL, load_realtime, 0, 0);
	if (s) { 	/* Manager */
		if (peer) {
			const char *id = astman_get_header(m, "ActionID");

			astman_append(s, "Response: Success\r\n");
			if (!ast_strlen_zero(id))
				astman_append(s, "ActionID: %s\r\n", id);
		} else {
			snprintf (cbuf, sizeof(cbuf), "Peer %s not found.", argv[3]);
			astman_send_error(s, m, cbuf);
			return CLI_SUCCESS;
		}
	}
	if (peer && type==0 ) { /* Normal listing */
		struct ast_str *mailbox_str = ast_str_alloca(512);
		ast_cli(fd, "\n\n");
		ast_cli(fd, "  * Name       : %s\n", peer->name);
		if (realtimepeers) {	/* Realtime is enabled */
			ast_cli(fd, "  Realtime peer: %s\n", peer->is_realtime ? "Yes, cached" : "No");
		}
		ast_cli(fd, "  Secret       : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
		ast_cli(fd, "  MD5Secret    : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
		for (auth = peer->auth; auth; auth = auth->next) {
			ast_cli(fd, "  Realm-auth   : Realm %-15.15s User %-10.20s ", auth->realm, auth->username);
			ast_cli(fd, "%s\n", !ast_strlen_zero(auth->secret)?"<Secret set>":(!ast_strlen_zero(auth->md5secret)?"<MD5secret set>" : "<Not set>"));
		}
		ast_cli(fd, "  Context      : %s\n", peer->context);
		ast_cli(fd, "  Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
		ast_cli(fd, "  Language     : %s\n", peer->language);
		if (!ast_strlen_zero(peer->accountcode))
			ast_cli(fd, "  Accountcode  : %s\n", peer->accountcode);
		ast_cli(fd, "  AMA flags    : %s\n", ast_cdr_flags2str(peer->amaflags));
		ast_cli(fd, "  Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
		ast_cli(fd, "  CallingPres  : %s\n", ast_describe_caller_presentation(peer->callingpres));
		if (!ast_strlen_zero(peer->fromuser))
			ast_cli(fd, "  FromUser     : %s\n", peer->fromuser);
		if (!ast_strlen_zero(peer->fromdomain))
			ast_cli(fd, "  FromDomain   : %s\n", peer->fromdomain);
		ast_cli(fd, "  Callgroup    : ");
		print_group(fd, peer->callgroup, 0);
		ast_cli(fd, "  Pickupgroup  : ");
		print_group(fd, peer->pickupgroup, 0);
		peer_mailboxes_to_str(&mailbox_str, peer);
		ast_cli(fd, "  Mailbox      : %s\n", mailbox_str->str);
		ast_cli(fd, "  VM Extension : %s\n", peer->vmexten);
		ast_cli(fd, "  LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
		ast_cli(fd, "  Call limit   : %d\n", peer->call_limit);
		if (peer->busy_level)
			ast_cli(fd, "  Busy level   : %d\n", peer->busy_level);
		ast_cli(fd, "  Dynamic      : %s\n", cli_yesno(peer->host_dynamic));
		ast_cli(fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
		ast_cli(fd, "  MaxCallBR    : %d kbps\n", peer->maxcallbitrate);
		ast_cli(fd, "  Expire       : %ld\n", ast_sched_when(sched, peer->expire));
		ast_cli(fd, "  Insecure     : %s\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
		ast_cli(fd, "  Nat          : %s\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
		ast_cli(fd, "  ACL          : %s\n", cli_yesno(peer->ha != NULL));
		ast_cli(fd, "  T.38 support : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
		ast_cli(fd, "  T.38 EC mode : %s\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
		ast_cli(fd, "  T.38 MaxDtgrm: %d\n", peer->t38_maxdatagram);
		ast_cli(fd, "  CanReinvite  : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_CAN_REINVITE)));
		ast_cli(fd, "  PromiscRedir : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)));
		ast_cli(fd, "  User=Phone   : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)));
		ast_cli(fd, "  Video Support: %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)));
		ast_cli(fd, "  Text Support : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)));
		ast_cli(fd, "  Ign SDP ver  : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_IGNORESDPVERSION)));
		ast_cli(fd, "  Trust RPID   : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_TRUSTRPID)));
		ast_cli(fd, "  Send RPID    : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_SENDRPID)));
		ast_cli(fd, "  Subscriptions: %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
		ast_cli(fd, "  Overlap dial : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP)));
		if (peer->outboundproxy)
			ast_cli(fd, "  Outb. proxy  : %s %s\n", ast_strlen_zero(peer->outboundproxy->name) ? "<not set>" : peer->outboundproxy->name,
							peer->outboundproxy->force ? "(forced)" : "");

		/* - is enumerated */
		ast_cli(fd, "  DTMFmode     : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
		ast_cli(fd, "  Timer T1     : %d\n", peer->timer_t1);
		ast_cli(fd, "  Timer B      : %d\n", peer->timer_b);
		ast_cli(fd, "  ToHost       : %s\n", peer->tohost);
		ast_cli(fd, "  Addr->IP     : %s Port %d\n",  peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)", ntohs(peer->addr.sin_port));
		ast_cli(fd, "  Defaddr->IP  : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
		ast_cli(fd, "  Transport    : %s\n", get_transport(peer->socket.type));
		if (!ast_strlen_zero(global_regcontext))
			ast_cli(fd, "  Reg. exten   : %s\n", peer->regexten);
		ast_cli(fd, "  Def. Username: %s\n", peer->username);
		ast_cli(fd, "  SIP Options  : ");
		if (peer->sipoptions) {
			int lastoption = -1;
			for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
				if (sip_options[x].id != lastoption) {
					if (peer->sipoptions & sip_options[x].id)
						ast_cli(fd, "%s ", sip_options[x].text);
					lastoption = x;
				}
			}
		} else
			ast_cli(fd, "(none)");

		ast_cli(fd, "\n");
		ast_cli(fd, "  Codecs       : ");
		ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
		ast_cli(fd, "%s\n", codec_buf);
		ast_cli(fd, "  Codec Order  : (");
		print_codec_to_cli(fd, &peer->prefs);
		ast_cli(fd, ")\n");

		ast_cli(fd, "  Auto-Framing :  %s \n", cli_yesno(peer->autoframing));
		ast_cli(fd, "  100 on REG   : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_REGISTERTRYING) ? "Yes" : "No");
		ast_cli(fd, "  Status       : ");
		peer_status(peer, status, sizeof(status));
		ast_cli(fd, "%s\n", status);
 		ast_cli(fd, "  Useragent    : %s\n", peer->useragent);
 		ast_cli(fd, "  Reg. Contact : %s\n", peer->fullcontact);
		ast_cli(fd, "  Qualify Freq : %d ms\n", peer->qualifyfreq);
		if (peer->chanvars) {
 			ast_cli(fd, "  Variables    :\n");
			for (v = peer->chanvars ; v ; v = v->next)
 				ast_cli(fd, "                 %s = %s\n", v->name, v->value);
		}

		ast_cli(fd, "  Sess-Timers  : %s\n", stmode2str(peer->stimer.st_mode_oper));
		ast_cli(fd, "  Sess-Refresh : %s\n", strefresher2str(peer->stimer.st_ref));
		ast_cli(fd, "  Sess-Expires : %d secs\n", peer->stimer.st_max_se);
		ast_cli(fd, "  Min-Sess     : %d secs\n", peer->stimer.st_min_se);
		ast_cli(fd, "\n");
		unref_peer(peer);
	} else  if (peer && type == 1) { /* manager listing */
		char buf[256];
		struct ast_str *mailbox_str = ast_str_alloca(512);
		astman_append(s, "Channeltype: SIP\r\n");
		astman_append(s, "ObjectName: %s\r\n", peer->name);
		astman_append(s, "ChanObjectType: peer\r\n");
		astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
		astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
		astman_append(s, "Context: %s\r\n", peer->context);
		astman_append(s, "Language: %s\r\n", peer->language);
		if (!ast_strlen_zero(peer->accountcode))
			astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
		astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
		astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
		if (!ast_strlen_zero(peer->fromuser))
			astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
		if (!ast_strlen_zero(peer->fromdomain))
			astman_append(s, "SIP-FromDomain: %s\r\n", peer->fromdomain);
		astman_append(s, "Callgroup: ");
		astman_append(s, "%s\r\n", ast_print_group(buf, sizeof(buf), peer->callgroup));
		astman_append(s, "Pickupgroup: ");
		astman_append(s, "%s\r\n", ast_print_group(buf, sizeof(buf), peer->pickupgroup));
		peer_mailboxes_to_str(&mailbox_str, peer);
		astman_append(s, "VoiceMailbox: %s\r\n", mailbox_str->str);
		astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
		astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
		astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
		astman_append(s, "Busy-level: %d\r\n", peer->busy_level);
		astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
		astman_append(s, "Dynamic: %s\r\n", peer->host_dynamic?"Y":"N");
		astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
		astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched, peer->expire));
		astman_append(s, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
		astman_append(s, "SIP-NatSupport: %s\r\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
		astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
		astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_CAN_REINVITE)?"Y":"N"));
		astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
		astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
		astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
		astman_append(s, "SIP-TextSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)?"Y":"N"));
		astman_append(s, "SIP-T.38Support: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)?"Y":"N"));
		astman_append(s, "SIP-T.38EC: %s\r\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
		astman_append(s, "SIP-T.38MaxDtgrm: %d\r\n", peer->t38_maxdatagram);
		astman_append(s, "SIP-Sess-Timers: %s\r\n", stmode2str(peer->stimer.st_mode_oper));
		astman_append(s, "SIP-Sess-Refresh: %s\r\n", strefresher2str(peer->stimer.st_ref));
		astman_append(s, "SIP-Sess-Expires: %d\r\n", peer->stimer.st_max_se);
		astman_append(s, "SIP-Sess-Min: %d\r\n", peer->stimer.st_min_se);

		/* - is enumerated */
		astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
		astman_append(s, "ToHost: %s\r\n", peer->tohost);
		astman_append(s, "Address-IP: %s\r\nAddress-Port: %d\r\n",  peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", ntohs(peer->addr.sin_port));
		astman_append(s, "Default-addr-IP: %s\r\nDefault-addr-port: %d\r\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
		astman_append(s, "Default-Username: %s\r\n", peer->username);
		if (!ast_strlen_zero(global_regcontext))
			astman_append(s, "RegExtension: %s\r\n", peer->regexten);
		astman_append(s, "Codecs: ");
		ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
		astman_append(s, "%s\r\n", codec_buf);
		astman_append(s, "CodecOrder: ");
		pref = &peer->prefs;
		for(x = 0; x < 32 ; x++) {
			codec = ast_codec_pref_index(pref, x);
			if (!codec)
				break;
			astman_append(s, "%s", ast_getformatname(codec));
			if (x < 31 && ast_codec_pref_index(pref, x+1))
				astman_append(s, ",");
		}

		astman_append(s, "\r\n");
		astman_append(s, "Status: ");
		peer_status(peer, status, sizeof(status));
		astman_append(s, "%s\r\n", status);
 		astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
 		astman_append(s, "Reg-Contact : %s\r\n", peer->fullcontact);
		astman_append(s, "QualifyFreq : %d ms\n", peer->qualifyfreq);
		if (peer->chanvars) {
			for (v = peer->chanvars ; v ; v = v->next) {
 				astman_append(s, "ChanVariable:\n");
 				astman_append(s, " %s,%s\r\n", v->name, v->value);
			}
		}

		unref_peer(peer);

	} else {
		ast_cli(fd, "Peer %s not found.\n", argv[3]);
		ast_cli(fd, "\n");
	}

	return CLI_SUCCESS;
}

/*! \brief Show one user in detail */
static char *sip_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
	char cbuf[256];
	struct sip_user *user;
	struct ast_variable *v;
	int load_realtime;

	switch (cmd) {
	case CLI_INIT:
		e->command = "sip show user";
		e->usage =
			"Usage: sip show user <name> [load]\n"
			"       Shows all details on one SIP user and the current status.\n"
			"       Option \"load\" forces lookup of peer in realtime storage.\n";
		return NULL;
	case CLI_GENERATE:
		return complete_sip_show_user(a->line, a->word, a->pos, a->n);
	}

	if (a->argc < 4)
		return CLI_SHOWUSAGE;

	/* Load from realtime storage? */
	load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? TRUE : FALSE;

	user = find_user(a->argv[3], load_realtime);
	if (user) {
		ast_cli(a->fd, "\n\n");
		ast_cli(a->fd, "  * Name       : %s\n", user->name);
		ast_cli(a->fd, "  Secret       : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
		ast_cli(a->fd, "  MD5Secret    : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
		ast_cli(a->fd, "  Context      : %s\n", user->context);
		ast_cli(a->fd, "  Language     : %s\n", user->language);
		if (!ast_strlen_zero(user->accountcode))
			ast_cli(a->fd, "  Accountcode  : %s\n", user->accountcode);
		ast_cli(a->fd, "  AMA flags    : %s\n", ast_cdr_flags2str(user->amaflags));
		ast_cli(a->fd, "  Transfer mode: %s\n", transfermode2str(user->allowtransfer));
		ast_cli(a->fd, "  MaxCallBR    : %d kbps\n", user->maxcallbitrate);
		ast_cli(a->fd, "  CallingPres  : %s\n", ast_describe_caller_presentation(user->callingpres));
		ast_cli(a->fd, "  Call limit   : %d\n", user->call_limit);
		ast_cli(a->fd, "  Callgroup    : ");
		print_group(a->fd, user->callgroup, 0);
		ast_cli(a->fd, "  Pickupgroup  : ");
		print_group(a->fd, user->pickupgroup, 0);
		ast_cli(a->fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
		ast_cli(a->fd, "  ACL          : %s\n", cli_yesno(user->ha != NULL));
 		ast_cli(a->fd, "  Sess-Timers  : %s\n", stmode2str(user->stimer.st_mode_oper));
 		ast_cli(a->fd, "  Sess-Refresh : %s\n", strefresher2str(user->stimer.st_ref));
 		ast_cli(a->fd, "  Sess-Expires : %d secs\n", user->stimer.st_max_se);
 		ast_cli(a->fd, "  Sess-Min-SE  : %d secs\n", user->stimer.st_min_se);
		ast_cli(a->fd, "  Ign SDP ver  : %s\n", cli_yesno(ast_test_flag(&user->flags[1], SIP_PAGE2_IGNORESDPVERSION)));

		ast_cli(a->fd, "  Codec Order  : (");
		print_codec_to_cli(a->fd, &user->prefs);
		ast_cli(a->fd, ")\n");

		ast_cli(a->fd, "  Auto-Framing:  %s \n", cli_yesno(user->autoframing));
		if (user->chanvars) {
 			ast_cli(a->fd, "  Variables    :\n");
			for (v = user->chanvars ; v ; v = v->next)
 				ast_cli(a->fd, "                 %s = %s\n", v->name, v->value);
		}

		ast_cli(a->fd, "\n");

		unref_user(user);
	} else {
		ast_cli(a->fd, "User %s not found.\n", a->argv[3]);
		ast_cli(a->fd, "\n");
	}

	return CLI_SUCCESS;
}

/*! \brief  Show SIP Registry (registrations with other SIP proxies */
static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
#define FORMAT2 "%-30.30s  %-12.12s  %8.8s %-20.20s %-25.25s\n"
#define FORMAT  "%-30.30s  %-12.12s  %8d %-20.20s %-25.25s\n"
	char host[80];
	char tmpdat[256];
	struct ast_tm tm;
	int counter = 0;

	switch (cmd) {
	case CLI_INIT:
		e->command = "sip show registry";
		e->usage =
			"Usage: sip show registry\n"
			"       Lists all registration requests and status.\n";
		return NULL;
	case CLI_GENERATE:
		return NULL;
	}

	if (a->argc != 3)
		return CLI_SHOWUSAGE;
	ast_cli(a->fd, FORMAT2, "Host", "Username", "Refresh", "State", "Reg.Time");
	ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
		ASTOBJ_RDLOCK(iterator);
		snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
		if (iterator->regtime.tv_sec) {
			ast_localtime(&iterator->regtime, &tm, NULL);
			ast_strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
		} else 
			tmpdat[0] = '\0';
		ast_cli(a->fd, FORMAT, host, iterator->username, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
		ASTOBJ_UNLOCK(iterator);
		counter++;
	} while(0));
	ast_cli(a->fd, "%d SIP registrations.\n", counter);
	return CLI_SUCCESS;
#undef FORMAT
#undef FORMAT2
}

/*! \brief Unregister (force expiration) a SIP peer in the registry via CLI 
	\note This function does not tell the SIP device what's going on,
	so use it with great care.
*/
static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
	struct sip_peer *peer;
	int load_realtime = 0;

	switch (cmd) {
	case CLI_INIT:
		e->command = "sip unregister";
		e->usage =
			"Usage: sip unregister <peer>\n"
			"       Unregister (force expiration) a SIP peer from the registry\n";
		return NULL;
	case CLI_GENERATE:
		return complete_sip_unregister(a->line, a->word, a->pos, a->n);
	}
	
	if (a->argc != 3)
		return CLI_SHOWUSAGE;
	
	if ((peer = find_peer(a->argv[2], NULL, load_realtime, 0, 0))) {
		if (peer->expire > 0) {
			AST_SCHED_DEL(sched, peer->expire);
			expire_register(peer);
			ast_cli(a->fd, "Unregistered peer \'%s\'\n\n", a->argv[2]);
		} else {
			ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
		}
	} else {
		ast_cli(a->fd, "Peer unknown: \'%s\'. Not unregistered.\n", a->argv[2]);
	}
	
	return CLI_SUCCESS;
}

/*! \brief List global settings for the SIP channel */
static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
	int realtimepeers;
	int realtimeusers;
	int realtimeregs;
	char codec_buf[SIPBUFSIZE];
	const char *msg;	/* temporary msg pointer */

	switch (cmd) {
	case CLI_INIT:
		e->command = "sip show settings";
		e->usage =
			"Usage: sip show settings\n"
			"       Provides detailed list of the configuration of the SIP channel.\n";
		return NULL;
	case CLI_GENERATE:
		return NULL;
	}


	realtimepeers = ast_check_realtime("sippeers");
	realtimeusers = ast_check_realtime("sipusers");
	realtimeregs = ast_check_realtime("sipregs");

	if (a->argc != 3)
		return CLI_SHOWUSAGE;
	ast_cli(a->fd, "\n\nGlobal Settings:\n");
	ast_cli(a->fd, "----------------\n");
	ast_cli(a->fd, "  UDP SIP Port:           %d\n", ntohs(bindaddr.sin_port));
	ast_cli(a->fd, "  UDP Bindaddress:        %s\n", ast_inet_ntoa(bindaddr.sin_addr));
	ast_cli(a->fd, "  TCP SIP Port:           ");
	if (sip_tcp_desc.sin.sin_family == AF_INET) {
		ast_cli(a->fd, "%d\n", ntohs(sip_tcp_desc.sin.sin_port));
		ast_cli(a->fd, "  TCP Bindaddress:        %s\n", ast_inet_ntoa(sip_tcp_desc.sin.sin_addr));
	} else {
		ast_cli(a->fd, "Disabled\n");
	}
	ast_cli(a->fd, "  TLS SIP Port:           ");
	if (default_tls_cfg.enabled != FALSE) {
		ast_cli(a->fd, "%d\n", ntohs(sip_tls_desc.sin.sin_port));
		ast_cli(a->fd, "  TLS Bindaddress:        %s\n", ast_inet_ntoa(sip_tls_desc.sin.sin_addr));
	} else {
		ast_cli(a->fd, "Disabled\n");
	}
	ast_cli(a->fd, "  Videosupport:           %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT)));
	ast_cli(a->fd, "  Textsupport:            %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT)));
	ast_cli(a->fd, "  AutoCreate Peer:        %s\n", cli_yesno(autocreatepeer));
	ast_cli(a->fd, "  Ignore SDP sess. ver.:  %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION)));
	ast_cli(a->fd, "  Match Auth Username:    %s\n", cli_yesno(global_match_auth_username));
	ast_cli(a->fd, "  Allow unknown access:   %s\n", cli_yesno(global_allowguest));
	ast_cli(a->fd, "  Allow subscriptions:    %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
	ast_cli(a->fd, "  Allow overlap dialing:  %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)));
	ast_cli(a->fd, "  Allow promsic. redir:   %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_PROMISCREDIR)));
	ast_cli(a->fd, "  Enable call counters:   %s\n", cli_yesno(global_callcounter));
	ast_cli(a->fd, "  SIP domain support:     %s\n", cli_yesno(!AST_LIST_EMPTY(&domain_list)));
	ast_cli(a->fd, "  Realm. auth:            %s\n", cli_yesno(authl != NULL));
	ast_cli(a->fd, "  Our auth realm          %s\n", global_realm);
	ast_cli(a->fd, "  Call to non-local dom.: %s\n", cli_yesno(allow_external_domains));
	ast_cli(a->fd, "  URI user is phone no:   %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_USEREQPHONE)));
 	ast_cli(a->fd, "  Always auth rejects:    %s\n", cli_yesno(global_alwaysauthreject));
	ast_cli(a->fd, "  Call limit peers only:  %s\n", cli_yesno(global_limitonpeers));
	ast_cli(a->fd, "  Direct RTP setup:       %s\n", cli_yesno(global_directrtpsetup));
	ast_cli(a->fd, "  User Agent:             %s\n", global_useragent);
	ast_cli(a->fd, "  SDP Session Name:       %s\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
	ast_cli(a->fd, "  SDP Owner Name:         %s\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner);
	ast_cli(a->fd, "  Reg. context:           %s\n", S_OR(global_regcontext, "(not set)"));
	ast_cli(a->fd, "  Regexten on Qualify:    %s\n", cli_yesno(global_regextenonqualify));
	ast_cli(a->fd, "  Caller ID:              %s\n", default_callerid);
	ast_cli(a->fd, "  From: Domain:           %s\n", default_fromdomain);
	ast_cli(a->fd, "  Record SIP history:     %s\n", recordhistory ? "On" : "Off");
	ast_cli(a->fd, "  Call Events:            %s\n", global_callevents ? "On" : "Off");

	ast_cli(a->fd, "  T.38 support:           %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
	ast_cli(a->fd, "  T.38 EC mode:           %s\n", faxec2str(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
	ast_cli(a->fd, "  T.38 MaxDtgrm:          %d\n", global_t38_maxdatagram);

	if (!realtimepeers && !realtimeusers && !realtimeregs)
		ast_cli(a->fd, "  SIP realtime:           Disabled\n" );
	else
		ast_cli(a->fd, "  SIP realtime:           Enabled\n" );
	ast_cli(a->fd, "  Qualify Freq :          %d ms\n", global_qualifyfreq);
	ast_cli(a->fd, "\nNetwork QoS Settings:\n");
	ast_cli(a->fd, "---------------------------\n");
	ast_cli(a->fd, "  IP ToS SIP:             %s\n", ast_tos2str(global_tos_sip));
	ast_cli(a->fd, "  IP ToS RTP audio:       %s\n", ast_tos2str(global_tos_audio));
	ast_cli(a->fd, "  IP ToS RTP video:       %s\n", ast_tos2str(global_tos_video));
	ast_cli(a->fd, "  IP ToS RTP text:        %s\n", ast_tos2str(global_tos_text));
	ast_cli(a->fd, "  802.1p CoS SIP:         %d\n", global_cos_sip);
	ast_cli(a->fd, "  802.1p CoS RTP audio:   %d\n", global_cos_audio);
	ast_cli(a->fd, "  802.1p CoS RTP video:   %d\n", global_cos_video);
	ast_cli(a->fd, "  802.1p CoS RTP text:    %d\n", global_cos_text);
	ast_cli(a->fd, "  Jitterbuffer enabled:   %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_ENABLED)));
	ast_cli(a->fd, "  Jitterbuffer forced:    %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_FORCED)));
	ast_cli(a->fd, "  Jitterbuffer max size:  %ld\n", global_jbconf.max_size);
	ast_cli(a->fd, "  Jitterbuffer resync:    %ld\n", global_jbconf.resync_threshold);
	ast_cli(a->fd, "  Jitterbuffer impl:      %s\n", global_jbconf.impl);
	ast_cli(a->fd, "  Jitterbuffer log:       %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_LOG)));

	ast_cli(a->fd, "\nNetwork Settings:\n");
	ast_cli(a->fd, "---------------------------\n");
	/* determine if/how SIP address can be remapped */
	if (localaddr == NULL)
		msg = "Disabled, no localnet list";
	else if (externip.sin_addr.s_addr == 0)
		msg = "Disabled, externip is 0.0.0.0";
	else if (stunaddr.sin_addr.s_addr != 0)
		msg = "Enabled using STUN";
	else if (!ast_strlen_zero(externhost))
		msg = "Enabled using externhost";
	else
		msg = "Enabled using externip";
	ast_cli(a->fd, "  SIP address remapping:  %s\n", msg);
	ast_cli(a->fd, "  Externhost:             %s\n", S_OR(externhost, "<none>"));
	ast_cli(a->fd, "  Externip:               %s:%d\n", ast_inet_ntoa(externip.sin_addr), ntohs(externip.sin_port));
	ast_cli(a->fd, "  Externrefresh:          %d\n", externrefresh);
	ast_cli(a->fd, "  Internal IP:            %s:%d\n", ast_inet_ntoa(internip.sin_addr), ntohs(internip.sin_port));
	{
		struct ast_ha *d;
		const char *prefix = "Localnet:";
		char buf[INET_ADDRSTRLEN]; /* need to print two addresses */

		for (d = localaddr; d ; prefix = "", d = d->next) {
			ast_cli(a->fd, "  %-24s%s/%s\n",
			    prefix, ast_inet_ntoa(d->netaddr),
			    inet_ntop(AF_INET, &d->netmask, buf, sizeof(buf)) );
		}
	}
	ast_cli(a->fd, "  STUN server:            %s:%d\n", ast_inet_ntoa(stunaddr.sin_addr), ntohs(stunaddr.sin_port));
 
	ast_cli(a->fd, "\nGlobal Signalling Settings:\n");
	ast_cli(a->fd, "---------------------------\n");
	ast_cli(a->fd, "  Codecs:                 ");
	ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, global_capability);
	ast_cli(a->fd, "%s\n", codec_buf);
	ast_cli(a->fd, "  Codec Order:            ");
	print_codec_to_cli(a->fd, &default_prefs);
	ast_cli(a->fd, "\n");
	ast_cli(a->fd, "  Relax DTMF:             %s\n", cli_yesno(global_relaxdtmf));
	ast_cli(a->fd, "  RFC2833 Compensation:   %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE)));
	ast_cli(a->fd, "  Compact SIP headers:    %s\n", cli_yesno(compactheaders));
	ast_cli(a->fd, "  RTP Keepalive:          %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
	ast_cli(a->fd, "  RTP Timeout:            %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
	ast_cli(a->fd, "  RTP Hold Timeout:       %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
	ast_cli(a->fd, "  MWI NOTIFY mime type:   %s\n", default_notifymime);
	ast_cli(a->fd, "  DNS SRV lookup:         %s\n", cli_yesno(global_srvlookup));
	ast_cli(a->fd, "  Pedantic SIP support:   %s\n", cli_yesno(pedanticsipchecking));
	ast_cli(a->fd, "  Reg. min duration       %d secs\n", min_expiry);
	ast_cli(a->fd, "  Reg. max duration:      %d secs\n", max_expiry);
	ast_cli(a->fd, "  Reg. default duration:  %d secs\n", default_expiry);
	ast_cli(a->fd, "  Outbound reg. timeout:  %d secs\n", global_reg_timeout);
	ast_cli(a->fd, "  Outbound reg. attempts: %d\n", global_regattempts_max);
	ast_cli(a->fd, "  Notify ringing state:   %s\n", cli_yesno(global_notifyringing));
	ast_cli(a->fd, "  Notify hold state:      %s\n", cli_yesno(global_notifyhold));
	ast_cli(a->fd, "  SIP Transfer mode:      %s\n", transfermode2str(global_allowtransfer));
	ast_cli(a->fd, "  Max Call Bitrate:       %d kbps\n", default_maxcallbitrate);
	ast_cli(a->fd, "  Auto-Framing:           %s\n", cli_yesno(global_autoframing));
	ast_cli(a->fd, "  Outb. proxy:            %s %s\n", ast_strlen_zero(global_outboundproxy.name) ? "<not set>" : global_outboundproxy.name,
							global_outboundproxy.force ? "(forced)" : "");
	ast_cli(a->fd, "  Session Timers:         %s\n", stmode2str(global_st_mode));
	ast_cli(a->fd, "  Session Refresher:      %s\n", strefresher2str (global_st_refresher));
	ast_cli(a->fd, "  Session Expires:        %d secs\n", global_max_se);
	ast_cli(a->fd, "  Session Min-SE:         %d secs\n", global_min_se);
 	ast_cli(a->fd, "  Timer T1:               %d\n", global_t1);
	ast_cli(a->fd, "  Timer T1 minimum:       %d\n", global_t1min);
 	ast_cli(a->fd, "  Timer B:                %d\n", global_timer_b);
	ast_cli(a->fd, "  No premature media:     %s\n", global_prematuremediafilter ? "Yes" : "No");

	ast_cli(a->fd, "\nDefault Settings:\n");
	ast_cli(a->fd, "-----------------\n");
	ast_cli(a->fd, "  Context:                %s\n", default_context);
	ast_cli(a->fd, "  Nat:                    %s\n", nat2str(ast_test_flag(&global_flags[0], SIP_NAT)));
	ast_cli(a->fd, "  DTMF:                   %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
	ast_cli(a->fd, "  Qualify:                %d\n", default_qualify);
	ast_cli(a->fd, "  Use ClientCode:         %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_USECLIENTCODE)));
	ast_cli(a->fd, "  Progress inband:        %s\n", (ast_test_flag(&global_flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER) ? "Never" : (ast_test_flag(&global_flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NO) ? "No" : "Yes" );
	ast_cli(a->fd, "  Language:               %s\n", default_language);
	ast_cli(a->fd, "  MOH Interpret:          %s\n", default_mohinterpret);
	ast_cli(a->fd, "  MOH Suggest:            %s\n", default_mohsuggest);
	ast_cli(a->fd, "  Voice Mail Extension:   %s\n", default_vmexten);

	
	if (realtimepeers || realtimeusers || realtimeregs) {
		ast_cli(a->fd, "\nRealtime SIP Settings:\n");
		ast_cli(a->fd, "----------------------\n");
		ast_cli(a->fd, "  Realtime Peers:         %s\n", cli_yesno(realtimepeers));
		ast_cli(a->fd, "  Realtime Users:         %s\n", cli_yesno(realtimeusers));
		ast_cli(a->fd, "  Realtime Regs:          %s\n", cli_yesno(realtimeregs));
		ast_cli(a->fd, "  Cache Friends:          %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)));
		ast_cli(a->fd, "  Update:                 %s\n", cli_yesno(sip_cfg.peer_rtupdate));
		ast_cli(a->fd, "  Ignore Reg. Expire:     %s\n", cli_yesno(sip_cfg.ignore_regexpire));
		ast_cli(a->fd, "  Save sys. name:         %s\n", cli_yesno(sip_cfg.rtsave_sysname));
		ast_cli(a->fd, "  Auto Clear:             %d\n", global_rtautoclear);
	}
	ast_cli(a->fd, "\n----\n");
	return CLI_SUCCESS;
}

/*! \brief Show subscription type in string format */
static const char *subscription_type2str(enum subscriptiontype subtype)
{
	int i;

	for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
		if (subscription_types[i].type == subtype) {
			return subscription_types[i].text;
		}
	}
	return subscription_types[0].text;
}

/*! \brief Find subscription type in array */
static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
{
	int i;

	for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
		if (subscription_types[i].type == subtype) {
			return &subscription_types[i];
		}
	}
	return &subscription_types[0];
}

/*
 * We try to structure all functions that loop on data structures as
 * a handler for individual entries, and a mainloop that iterates
 * on the main data structure. This way, moving the code to containers
 * that support iteration through callbacks will be a lot easier.
 */

/*! \brief argument for the 'show channels|subscriptions' callback. */
struct __show_chan_arg { 
	int fd;
	int subscriptions;
	int numchans;   /* return value */
};

#define FORMAT3 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-13.13s  %-15.15s %-10.10s\n"
#define FORMAT2 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-7.7s  %-15.15s\n"
#define FORMAT  "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-3.3s %-3.3s  %-15.15s %-10.10s\n"

/*! \brief callback for show channel|subscription */
static int show_channels_cb(void *__cur, void *__arg, int flags)
{
	struct sip_pvt *cur = __cur;
	struct __show_chan_arg *arg = __arg;
	const struct sockaddr_in *dst = sip_real_dst(cur);

		/* XXX indentation preserved to reduce diff. Will be fixed later */
		if (cur->subscribed == NONE && !arg->subscriptions) {
			/* set if SIP transfer in progress */
			const char *referstatus = cur->refer ? referstatus2str(cur->refer->status) : "";
			char formatbuf[SIPBUFSIZE/2];

			ast_cli(arg->fd, FORMAT, ast_inet_ntoa(dst->sin_addr), 
				S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
				cur->callid, 
				ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0),
				cli_yesno(ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD)),
				cur->needdestroy ? "(d)" : "",
				cur->lastmsg ,
				referstatus
			);
			arg->numchans++;
		}
		if (cur->subscribed != NONE && arg->subscriptions) {
			struct ast_str *mailbox_str = ast_str_alloca(512);
			if (cur->subscribed == MWI_NOTIFICATION && cur->relatedpeer)
				peer_mailboxes_to_str(&mailbox_str, cur->relatedpeer);
			ast_cli(arg->fd, FORMAT3, ast_inet_ntoa(dst->sin_addr),
				S_OR(cur->username, S_OR(cur->cid_num, "(None)")), 
			   	cur->callid,
				/* the 'complete' exten/context is hidden in the refer_to field for subscriptions */
				cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
				cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate), 
				subscription_type2str(cur->subscribed),
				cur->subscribed == MWI_NOTIFICATION ? S_OR(mailbox_str->str, "<none>") : "<none>"
);
			arg->numchans++;
		}

	return 0;	/* don't care, we scan all channels */
}

/*! \brief CLI for show channels or subscriptions.
 * This is a new-style CLI handler so a single function contains
 * the prototype for the function, the 'generator' to produce multiple
 * entries in case it is required, and the actual handler for the command.
 */
static char *sip_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
	struct sip_pvt *cur;
	struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };

	if (cmd == CLI_INIT) {
		e->command = "sip show {channels|subscriptions}";
		e->usage =
		"Usage: sip show channels\n"
		"       Lists all currently active SIP calls (dialogs).\n"
		"Usage: sip show subscriptions\n"
		"       Lists active SIP subscriptions.\n";
		return NULL;
	} else if (cmd == CLI_GENERATE)
		return NULL;

	if (a->argc != e->args)
		return CLI_SHOWUSAGE;
	arg.subscriptions = !strcasecmp(a->argv[e->args - 1], "subscriptions");
	if (!arg.subscriptions)
		ast_cli(arg.fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Format", "Hold", "Last Message");
	else
		ast_cli(arg.fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox");

	/* iterate on the container and invoke the callback on each item */
	dialoglist_lock();
	for (cur = dialoglist; cur; cur = cur->next) {
		show_channels_cb(cur, &arg, 0);
	}
	dialoglist_unlock();

	/* print summary information */
	ast_cli(arg.fd, "%d active SIP %s%s\n", arg.numchans,
		(arg.subscriptions ? "subscription" : "dialog"),
		ESS(arg.numchans));	/* ESS(n) returns an "s" if n>1 */
	return CLI_SUCCESS;
#undef FORMAT
#undef FORMAT2
#undef FORMAT3
}

/*! \brief Support routine for 'sip show channel' and 'sip show history' CLI
 * This is in charge of generating all strings that match a prefix in the
 * given position. As many functions of this kind, each invokation has
 * O(state) time complexity so be careful in using it.
 */
static char *complete_sipch(const char *line, const char *word, int pos, int state)
{
	int which=0;
	struct sip_pvt *cur;
	char *c = NULL;
	int wordlen = strlen(word);

	if (pos != 3) {
		return NULL;
	}

	dialoglist_lock();
	for (cur = dialoglist; cur; cur = cur->next) {
		if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
			c = ast_strdup(cur->callid);
			break;
		}
	}
	dialoglist_unlock();
	return c;
}

/*! \brief Do completion on peer name */
static char *complete_sip_peer(const char *word, int state, int flags2)
{
	char *result = NULL;
	int wordlen = strlen(word);
	int which = 0;

	ASTOBJ_CONTAINER_TRAVERSE(&peerl, !result, do {
		/* locking of the object is not required because only the name and flags are being compared */
		if (!strncasecmp(word, iterator->name, wordlen) &&
				(!flags2 || ast_test_flag(&iterator->flags[1], flags2)) &&
				++which > state)
			result = ast_strdup(iterator->name);
	} while(0) );
	return result;
}

/*! \brief Do completion on registered peer name */
static char *complete_sip_registered_peer(const char *word, int state, int flags2)
{
       char *result = NULL;
       int wordlen = strlen(word);
       int which = 0;

       ASTOBJ_CONTAINER_TRAVERSE(&peerl, !result, do {
               ASTOBJ_WRLOCK(iterator);
               if (!strncasecmp(word, iterator->name, wordlen) &&
                               (!flags2 || ast_test_flag(&iterator->flags[1], flags2)) &&
                               ++which > state && iterator->expire > 0)
                       result = ast_strdup(iterator->name);
               ASTOBJ_UNLOCK(iterator);
       } while(0) );
       return result;
}

/*! \brief Support routine for 'sip show history' CLI */
static char *complete_sip_show_history(const char *line, const char *word, int pos, int state)
{
	if (pos == 3)
		return complete_sipch(line, word, pos, state);

	return NULL;
}

/*! \brief Support routine for 'sip show peer' CLI */
static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
{
	if (pos == 3)
		return complete_sip_peer(word, state, 0);

	return NULL;
}

/*! \brief Support routine for 'sip unregister' CLI */
static char *complete_sip_unregister(const char *line, const char *word, int pos, int state)
{
       if (pos == 2)
               return complete_sip_registered_peer(word, state, 0);

       return NULL;
}

/*! \brief Do completion on user name */
static char *complete_sip_user(const char *word, int state, int flags2)
{
	char *result = NULL;
	int wordlen = strlen(word);
	int which = 0;

	ASTOBJ_CONTAINER_TRAVERSE(&userl, !result, do {
		/* locking of the object is not required because only the name and flags are being compared */
		if (!strncasecmp(word, iterator->name, wordlen)) {
			if (flags2 && !ast_test_flag(&iterator->flags[1], flags2))
				continue;
			if (++which > state) {
				result = ast_strdup(iterator->name);
			}
		}
	} while(0) );
	return result;
}

/*! \brief Support routine for 'sip show user' CLI */
static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
{
	if (pos == 3)
		return complete_sip_user(word, state, 0);

	return NULL;
}

/*! \brief Support routine for 'sip notify' CLI */
static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
{
	char *c = NULL;

	if (pos == 2) {
		int which = 0;
		char *cat = NULL;
		int wordlen = strlen(word);

		/* do completion for notify type */

		if (!notify_types)
			return NULL;
		
		while ( (cat = ast_category_browse(notify_types, cat)) ) {
			if (!strncasecmp(word, cat, wordlen) && ++which > state) {
				c = ast_strdup(cat);
				break;
			}
		}
		return c;
	}

	if (pos > 2)
		return complete_sip_peer(word, state, 0);

	return NULL;
}

/*! \brief Show details of one active dialog */
static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
	struct sip_pvt *cur;
	size_t len;
	int found = 0;

	switch (cmd) {
	case CLI_INIT:
		e->command = "sip show channel";
		e->usage =
			"Usage: sip show channel <call-id>\n"
			"       Provides detailed status on a given SIP dialog (identified by SIP call-id).\n";
		return NULL;
	case CLI_GENERATE:
		return complete_sipch(a->line, a->word, a->pos, a->n);
	}

	if (a->argc != 4)
		return CLI_SHOWUSAGE;
	len = strlen(a->argv[3]);
	dialoglist_lock();
	for (cur = dialoglist; cur; cur = cur->next) {
		if (!strncasecmp(cur->callid, a->argv[3], len)) {
			char formatbuf[SIPBUFSIZE/2];
			ast_cli(a->fd, "\n");
			if (cur->subscribed != NONE)
				ast_cli(a->fd, "  * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
			else
				ast_cli(a->fd, "  * SIP Call\n");
			ast_cli(a->fd, "  Curr. trans. direction:  %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
			ast_cli(a->fd, "  Call-ID:                %s\n", cur->callid);
			ast_cli(a->fd, "  Owner channel ID:       %s\n", cur->owner ? cur->owner->name : "<none>");
			ast_cli(a->fd, "  Our Codec Capability:   %d\n", cur->capability);
			ast_cli(a->fd, "  Non-Codec Capability (DTMF):   %d\n", cur->noncodeccapability);
			ast_cli(a->fd, "  Their Codec Capability:   %d\n", cur->peercapability);
			ast_cli(a->fd, "  Joint Codec Capability:   %d\n", cur->jointcapability);
			ast_cli(a->fd, "  Format:                 %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0) );
			ast_cli(a->fd, "  T.38 support            %s\n", cli_yesno(cur->udptl != NULL));
			ast_cli(a->fd, "  Video support           %s\n", cli_yesno(cur->vrtp != NULL));
			ast_cli(a->fd, "  MaxCallBR:              %d kbps\n", cur->maxcallbitrate);
			ast_cli(a->fd, "  Theoretical Address:    %s:%d\n", ast_inet_ntoa(cur->sa.sin_addr), ntohs(cur->sa.sin_port));
			ast_cli(a->fd, "  Received Address:       %s:%d\n", ast_inet_ntoa(cur->recv.sin_addr), ntohs(cur->recv.sin_port));
			ast_cli(a->fd, "  SIP Transfer mode:      %s\n", transfermode2str(cur->allowtransfer));
			ast_cli(a->fd, "  NAT Support:            %s\n", nat2str(ast_test_flag(&cur->flags[0], SIP_NAT)));
			ast_cli(a->fd, "  Audio IP:               %s %s\n", ast_inet_ntoa(cur->redirip.sin_addr.s_addr ? cur->redirip.sin_addr : cur->ourip.sin_addr), cur->redirip.sin_addr.s_addr ? "(Outside bridge)" : "(local)" );
			ast_cli(a->fd, "  Our Tag:                %s\n", cur->tag);
			ast_cli(a->fd, "  Their Tag:              %s\n", cur->theirtag);
			ast_cli(a->fd, "  SIP User agent:         %s\n", cur->useragent);
			if (!ast_strlen_zero(cur->username))
				ast_cli(a->fd, "  Username:               %s\n", cur->username);
			if (!ast_strlen_zero(cur->peername))
				ast_cli(a->fd, "  Peername:               %s\n", cur->peername);
			if (!ast_strlen_zero(cur->uri))
				ast_cli(a->fd, "  Original uri:           %s\n", cur->uri);
			if (!ast_strlen_zero(cur->cid_num))
				ast_cli(a->fd, "  Caller-ID:              %s\n", cur->cid_num);
			ast_cli(a->fd, "  Need Destroy:           %s\n", cli_yesno(cur->needdestroy));
			ast_cli(a->fd, "  Last Message:           %s\n", cur->lastmsg);
			ast_cli(a->fd, "  Promiscuous Redir:      %s\n", cli_yesno(ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR)));
			ast_cli(a->fd, "  Route:                  %s\n", cur->route ? cur->route->hop : "N/A");
			ast_cli(a->fd, "  DTMF Mode:              %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
			ast_cli(a->fd, "  SIP Options:            ");
			if (cur->sipoptions) {
				int x;
				for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
					if (cur->sipoptions & sip_options[x].id)
						ast_cli(a->fd, "%s ", sip_options[x].text);
				}
				ast_cli(a->fd, "\n");
			} else
				ast_cli(a->fd, "(none)\n");

			if (!cur->stimer)
 				ast_cli(a->fd, "  Session-Timer:          Uninitiallized\n");
			else {
 				ast_cli(a->fd, "  Session-Timer:          %s\n", cur->stimer->st_active ? "Active" : "Inactive");
 				if (cur->stimer->st_active == TRUE) {
 					ast_cli(a->fd, "  S-Timer Interval:       %d\n", cur->stimer->st_interval);
 					ast_cli(a->fd, "  S-Timer Refresher:      %s\n", strefresher2str(cur->stimer->st_ref));
 					ast_cli(a->fd, "  S-Timer Expirys:        %d\n", cur->stimer->st_expirys);
 					ast_cli(a->fd, "  S-Timer Sched Id:       %d\n", cur->stimer->st_schedid);
 					ast_cli(a->fd, "  S-Timer Peer Sts:       %s\n", cur->stimer->st_active_peer_ua ? "Active" : "Inactive");
 					ast_cli(a->fd, "  S-Timer Cached Min-SE:  %d\n", cur->stimer->st_cached_min_se);
 					ast_cli(a->fd, "  S-Timer Cached SE:      %d\n", cur->stimer->st_cached_max_se);
 					ast_cli(a->fd, "  S-Timer Cached Ref:     %s\n", strefresher2str(cur->stimer->st_cached_ref));
 					ast_cli(a->fd, "  S-Timer Cached Mode:    %s\n", stmode2str(cur->stimer->st_cached_mode));
 				}
			}

			ast_cli(a->fd, "\n\n");

			found++;
		}
	}
	dialoglist_unlock();
	if (!found) 
		ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
	return CLI_SUCCESS;
}

/*! \brief Show history details of one dialog */
static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
	struct sip_pvt *cur;
	size_t len;
	int found = 0;

	switch (cmd) {
	case CLI_INIT:
		e->command = "sip show history";
		e->usage =
			"Usage: sip show history <call-id>\n"
			"       Provides detailed dialog history on a given SIP call (specified by call-id).\n";
		return NULL;
	case CLI_GENERATE:
		return complete_sip_show_history(a->line, a->word, a->pos, a->n);
	}

	if (a->argc != 4)
		return CLI_SHOWUSAGE;
	if (!recordhistory)
		ast_cli(a->fd, "\n***Note: History recording is currently DISABLED.  Use 'sip set history on' to ENABLE.\n");
	len = strlen(a->argv[3]);
	dialoglist_lock();
	for (cur = dialoglist; cur; cur = cur->next) {
		if (!strncasecmp(cur->callid, a->argv[3], len)) {
			struct sip_history *hist;
			int x = 0;

			ast_cli(a->fd, "\n");
			if (cur->subscribed != NONE)
				ast_cli(a->fd, "  * Subscription\n");
			else
				ast_cli(a->fd, "  * SIP Call\n");
			if (cur->history)
				AST_LIST_TRAVERSE(cur->history, hist, list)
					ast_cli(a->fd, "%d. %s\n", ++x, hist->event);
			if (x == 0)
				ast_cli(a->fd, "Call '%s' has no history\n", cur->callid);
			found++;
		}
	}
	dialoglist_unlock();
	if (!found) 
		ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
	return CLI_SUCCESS;
}

/*! \brief Dump SIP history to debug log file at end of lifespan for SIP dialog */
static void sip_dump_history(struct sip_pvt *dialog)
{
	int x = 0;
	struct sip_history *hist;
	static int errmsg = 0;

	if (!dialog)
		return;

	if (!option_debug && !sipdebug) {
		if (!errmsg) {
			ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
			errmsg = 1;
		}
		return;
	}

	ast_debug(1, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
	if (dialog->subscribed)
		ast_debug(1, "  * Subscription\n");
	else
		ast_debug(1, "  * SIP Call\n");
	if (dialog->history)
		AST_LIST_TRAVERSE(dialog->history, hist, list)
			ast_debug(1, "  %-3.3d. %s\n", ++x, hist->event);
	if (!x)
		ast_debug(1, "Call '%s' has no history\n", dialog->callid);
	ast_debug(1, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
}


/*! \brief  Receive SIP INFO Message */
static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
{
	char buf[1024];
	unsigned int event;
	const char *c = get_header(req, "Content-Type");

	/* Need to check the media/type */
	if (!strcasecmp(c, "application/dtmf-relay") ||
	    !strcasecmp(c, "application/vnd.nortelnetworks.digits")) {
		unsigned int duration = 0;

		if (!p->owner) {	/* not a PBX call */
			transmit_response(p, "481 Call leg/transaction does not exist", req);
			sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
			return;
		}

		/* Try getting the "signal=" part */
		if (ast_strlen_zero(c = get_body(req, "Signal")) && ast_strlen_zero(c = get_body(req, "d"))) {
			ast_log(LOG_WARNING, "Unable to retrieve DTMF signal from INFO message from %s\n", p->callid);
			transmit_response(p, "200 OK", req); /* Should return error */
			return;
		} else {
			ast_copy_string(buf, c, sizeof(buf));
		}

		if (!ast_strlen_zero((c = get_body(req, "Duration"))))
			duration = atoi(c);
		if (!duration)
			duration = 100; /* 100 ms */


		if (ast_strlen_zero(buf)) {
			transmit_response(p, "200 OK", req);
			return;
		}

		if (buf[0] == '*')
			event = 10;
		else if (buf[0] == '#')
			event = 11;
		else if ((buf[0] >= 'A') && (buf[0] <= 'D'))
			event = 12 + buf[0] - 'A';
		else if (buf[0] == '!')
			event = 16;
		else
			event = atoi(buf);
		if (event == 16) {
			/* send a FLASH event */
			struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
			ast_queue_frame(p->owner, &f);
			if (sipdebug)
				ast_verbose("* DTMF-relay event received: FLASH\n");
		} else {
			/* send a DTMF event */
			struct ast_frame f = { AST_FRAME_DTMF, };
			if (event < 10) {
				f.subclass = '0' + event;
			} else if (event < 11) {
				f.subclass = '*';
			} else if (event < 12) {
				f.subclass = '#';
			} else if (event < 16) {
				f.subclass = 'A' + (event - 12);
			}
			f.len = duration;
			ast_queue_frame(p->owner, &f);
			if (sipdebug)
				ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
		}
		transmit_response(p, "200 OK", req);
		return;
	} else if (!strcasecmp(c, "application/dtmf")) {
		/*! \todo Note: Doesn't read the duration of the DTMF. Should be fixed. */
		unsigned int duration = 0;

		if (!p->owner) {	/* not a PBX call */
			transmit_response(p, "481 Call leg/transaction does not exist", req);
			sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
			return;
		}

		get_msg_text(buf, sizeof(buf), req);
		duration = 100; /* 100 ms */

		if (ast_strlen_zero(buf)) {
			transmit_response(p, "200 OK", req);
			return;
		}
		event = atoi(buf);
		if (event == 16) {
			/* send a FLASH event */
			struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
			ast_queue_frame(p->owner, &f);
			if (sipdebug)
				ast_verbose("* DTMF-relay event received: FLASH\n");
		} else {
			/* send a DTMF event */
			struct ast_frame f = { AST_FRAME_DTMF, };
			if (event < 10) {
				f.subclass = '0' + event;
			} else if (event < 11) {
				f.subclass = '*';
			} else if (event < 12) {
				f.subclass = '#';
			} else if (event < 16) {
				f.subclass = 'A' + (event - 12);
			}
			f.len = duration;
			ast_queue_frame(p->owner, &f);
			if (sipdebug)
				ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
		}
		transmit_response(p, "200 OK", req);
		return;

	} else if (!strcasecmp(c, "application/media_control+xml")) {
		/* Eh, we'll just assume it's a fast picture update for now */
		if (p->owner)
			ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
		transmit_response(p, "200 OK", req);
		return;
	} else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) {
		/* Client code (from SNOM phone) */
		if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
			if (p->owner && p->owner->cdr)
				ast_cdr_setuserfield(p->owner, c);
			if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
				ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
			transmit_response(p, "200 OK", req);
		} else {
			transmit_response(p, "403 Forbidden", req);
		}
		return;
	} else if (!ast_strlen_zero(c = get_header(req, "Record"))) {
		/* INFO messages generated by some phones to start/stop recording
			on phone calls. 
			OEJ: I think this should be something that is enabled/disabled
			per device. I don't want incoming callers to record calls in my
			pbx.
		*/
		/* first, get the feature string, if it exists */
		struct ast_call_feature *feat;
		int j;
		struct ast_frame f = { AST_FRAME_DTMF, };

		ast_rdlock_call_features();
		feat = ast_find_call_feature("automon");
		if (!feat || ast_strlen_zero(feat->exten)) {
			ast_log(LOG_WARNING, "Recording requested, but no One Touch Monitor registered. (See features.conf)\n");
			/* 403 means that we don't support this feature, so don't request it again */
			transmit_response(p, "403 Forbidden", req);
			ast_unlock_call_features();
			return;
		} 
		/* Send the feature code to the PBX as DTMF, just like the handset had sent it */
		f.len = 100;
		for (j=0; j < strlen(feat->exten); j++) {
			f.subclass = feat->exten[j];
			ast_queue_frame(p->owner, &f);
			if (sipdebug)
				ast_verbose("* DTMF-relay event faked: %c\n", f.subclass);
		}
		ast_unlock_call_features();

		ast_debug(1, "Got a Request to Record the channel, state %s\n", c);
		transmit_response(p, "200 OK", req);
		return;
	} else if (ast_strlen_zero(c = get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
		/* This is probably just a packet making sure the signalling is still up, just send back a 200 OK */
		transmit_response(p, "200 OK", req);
		return;
	}

	/* Other type of INFO message, not really understood by Asterisk */
	/* if (get_msg_text(buf, sizeof(buf), req)) { */

	ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
	transmit_response(p, "415 Unsupported media type", req);
	return;
}

/*! \brief Enable SIP Debugging for a single IP */
static char *sip_do_debug_ip(int fd, char *arg)
{
	struct hostent *hp;
	struct ast_hostent ahp;
	int port = 0;
	char *p;

	p = arg;
	strsep(&p, ":");
	if (p)
		port = atoi(p);
	hp = ast_gethostbyname(arg, &ahp);
	if (hp == NULL)
		return CLI_SHOWUSAGE;

	debugaddr.sin_family = AF_INET;
	memcpy(&debugaddr.sin_addr, hp->h_addr, sizeof(debugaddr.sin_addr));
	debugaddr.sin_port = htons(port);
	if (port == 0)
		ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_inet_ntoa(debugaddr.sin_addr));
	else
		ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), port);

	sipdebug |= sip_debug_console;

	return CLI_SUCCESS;
}

/*! \brief  Turn on SIP debugging for a given peer */
static char *sip_do_debug_peer(int fd, char *arg)
{
	struct sip_peer *peer = find_peer(arg, NULL, 1, 0, 0);
	if (!peer)
		ast_cli(fd, "No such peer '%s'\n", arg);
	else if (peer->addr.sin_addr.s_addr == 0)
		ast_cli(fd, "Unable to get IP address of peer '%s'\n", arg);
	else {
		debugaddr.sin_family = AF_INET;
		debugaddr.sin_addr = peer->addr.sin_addr;
		debugaddr.sin_port = peer->addr.sin_port;
		ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n",
			ast_inet_ntoa(debugaddr.sin_addr), ntohs(debugaddr.sin_port));
		sipdebug |= sip_debug_console;
	}
	if (peer)
		unref_peer(peer);
	return CLI_SUCCESS;
}

/*! \brief Turn on SIP debugging (CLI command) */
static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
	int oldsipdebug = sipdebug & sip_debug_console;
	char *what;

	if (cmd == CLI_INIT) {
		e->command = "sip set debug {on|off|ip|peer}";
		e->usage =
			"Usage: sip set debug {off|on|ip addr[:port]|peer peername}\n"
			"       Globally disables dumping of SIP packets,\n"
			"       or enables it either globally or for a (single)\n"
			"       IP address or registered peer.\n";
		return NULL;
	} else if (cmd == CLI_GENERATE) {
		if (a->pos == 4 && strcasestr(a->line, " peer")) /* XXX should check on argv too */
			return complete_sip_peer(a->word, a->n, 0);
		return NULL;
        }

	what = a->argv[e->args-1];      /* guaranteed to exist */
	if (a->argc == e->args) {       /* on/off */
		if (!strcasecmp(what, "on")) {
			sipdebug |= sip_debug_console;
			sipdebug_text = 1;	/*! \note this can be a special debug command - "sip debug text" or something */
			memset(&debugaddr, 0, sizeof(debugaddr));
			ast_cli(a->fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
			return CLI_SUCCESS;
		} else if (!strcasecmp(what, "off")) {
			sipdebug &= ~sip_debug_console;
			sipdebug_text = 0;
			ast_cli(a->fd, "SIP Debugging Disabled\n");
			return CLI_SUCCESS;
		}
	} else if (a->argc == e->args +1) {/* ip/peer */
		if (!strcasecmp(what, "ip"))
			return sip_do_debug_ip(a->fd, a->argv[e->args]);
		else if (!strcasecmp(what, "peer"))
			return sip_do_debug_peer(a->fd, a->argv[e->args]);
	}
	return CLI_SHOWUSAGE;   /* default, failure */
}

/*! \brief Cli command to send SIP notify to peer */
static char *sip_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
	struct ast_variable *varlist;
	int i;

	switch (cmd) {
	case CLI_INIT:
		e->command = "sip notify";
		e->usage =
			"Usage: sip notify <type> <peer> [<peer>...]\n"
			"       Send a NOTIFY message to a SIP peer or peers\n"
			"       Message types are defined in sip_notify.conf\n";
		return NULL;
	case CLI_GENERATE:
		return complete_sipnotify(a->line, a->word, a->pos, a->n);
	}


	if (a->argc < 4)
		return CLI_SHOWUSAGE;

	if (!notify_types) {
		ast_cli(a->fd, "No %s file found, or no types listed there\n", notify_config);
		return CLI_FAILURE;
	}

	varlist = ast_variable_browse(notify_types, a->argv[2]);

	if (!varlist) {
		ast_cli(a->fd, "Unable to find notify type '%s'\n", a->argv[2]);
		return CLI_FAILURE;
	}

	for (i = 3; i < a->argc; i++) {
		struct sip_pvt *p;
		struct sip_request req;
		struct ast_variable *var;

		if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
			ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
			return CLI_FAILURE;
		}

		if (create_addr(p, a->argv[i], 1)) {
			/* Maybe they're not registered, etc. */
			dialog_cleanup_and_destroy(p); /* sip_destroy(p); */
			ast_cli(a->fd, "Could not create address for '%s'\n", a->argv[i]);
			continue;
		}

		initreqprep(&req, p, SIP_NOTIFY);

		for (var = varlist; var; var = var->next) {
			char buf[512];
			ast_copy_string(buf, var->value, sizeof(buf));
			add_header(&req, var->name, ast_unescape_semicolon(buf));
		}

		/* Recalculate our side, and recalculate Call ID */
		ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
		build_via(p);
		build_callid_pvt(p);
		ast_cli(a->fd, "Sending NOTIFY of type '%s' to '%s'\n", a->argv[2], a->argv[i]);
		transmit_sip_request(p, &req);
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
	}

	return CLI_SUCCESS;
}

/*! \brief Enable/Disable SIP History logging (CLI) - deprecated. use sip_set_history instead */
static char *sip_do_history_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
	switch (cmd) {
	case CLI_INIT:
		e->command = "sip history [off]";
		e->usage =
			"Usage: sip history [off]\n"
			"       Enables/Disables recording of SIP dialog history for debugging purposes.\n"
			"       Use 'sip show history' to view the history of a call number.\n";
		return NULL;
	case CLI_GENERATE:
		return NULL;
	}

	if (a->argc < 2 || a->argc > 3) {
		return CLI_SHOWUSAGE;
	}
	if (a->argc == 2) {
		recordhistory = TRUE;
		ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
	} else {
		if (strncasecmp(a->argv[2], "off", 3))
			return CLI_SHOWUSAGE;
		recordhistory = FALSE;
		ast_cli(a->fd, "SIP History Recording Disabled\n");
	}
	return CLI_SUCCESS;
}

/*! \brief Enable/Disable SIP History logging (CLI) */
static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
	switch (cmd) {
	case CLI_INIT:
		e->command = "sip set history {on|off}";
		e->usage =
			"Usage: sip history {on|off}\n"
			"       Enables/Disables recording of SIP dialog history for debugging purposes.\n"
			"       Use 'sip show history' to view the history of a call number.\n";
		return NULL;
	case CLI_GENERATE:
		return NULL;
	}

	if (a->argc != e->args)
		return CLI_SHOWUSAGE;

	if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
		recordhistory = TRUE;
		ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
	} else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
		recordhistory = FALSE;
		ast_cli(a->fd, "SIP History Recording Disabled\n");
	} else {
		return CLI_SHOWUSAGE;
	}
	return CLI_SUCCESS;
}

/*! \brief Authenticate for outbound registration */
static int do_register_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code)
{
	char *header, *respheader;
	char digest[1024];

	p->authtries++;
	auth_headers(code, &header, &respheader);
	memset(digest, 0, sizeof(digest));
	if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
		/* There's nothing to use for authentication */
 		/* No digest challenge in request */
 		if (sip_debug_test_pvt(p) && p->registry)
 			ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
 			/* No old challenge */
		return -1;
	}
	if (p->do_history)
		append_history(p, "RegistryAuth", "Try: %d", p->authtries);
 	if (sip_debug_test_pvt(p) && p->registry)
 		ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
	return transmit_register(p->registry, SIP_REGISTER, digest, respheader); 
}

/*! \brief Add authentication on outbound SIP packet */
static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code, int sipmethod, int init)
{
	char *header, *respheader;
	char digest[1024];

	if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
		return -2;

	p->authtries++;
	auth_headers(code, &header, &respheader);
	ast_debug(2, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
	memset(digest, 0, sizeof(digest));
	if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
		/* No way to authenticate */
		return -1;
	}
	/* Now we have a reply digest */
	p->options->auth = digest;
	p->options->authheader = respheader;
	return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init); 
}

/*! \brief  reply to authentication for outbound registrations
\return	Returns -1 if we have no auth 
\note	This is used for register= servers in sip.conf, SIP proxies we register
	with  for receiving calls from.  */
static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod,  char *digest, int digest_len)
{
	char tmp[512];
	char *c;
	char oldnonce[256];

	/* table of recognised keywords, and places where they should be copied */
	const struct x {
		const char *key;
		const ast_string_field *field;
	} *i, keys[] = {
		{ "realm=", &p->realm },
		{ "nonce=", &p->nonce },
		{ "opaque=", &p->opaque },
		{ "qop=", &p->qop },
		{ "domain=", &p->domain },
		{ NULL, 0 },
	};

	ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
	if (ast_strlen_zero(tmp)) 
		return -1;
	if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
		ast_log(LOG_WARNING, "missing Digest.\n");
		return -1;
	}
	c = tmp + strlen("Digest ");
	ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
	while (c && *(c = ast_skip_blanks(c))) {	/* lookup for keys */
		for (i = keys; i->key != NULL; i++) {
			char *src, *separator;
			if (strncasecmp(c, i->key, strlen(i->key)) != 0)
				continue;
			/* Found. Skip keyword, take text in quotes or up to the separator. */
			c += strlen(i->key);
			if (*c == '"') {
				src = ++c;
				separator = "\"";
			} else {
				src = c;
				separator = ",";
			}
			strsep(&c, separator); /* clear separator and move ptr */
			ast_string_field_ptr_set(p, i->field, src);
			break;
		}
		if (i->key == NULL) /* not found, try ',' */
			strsep(&c, ",");
	}
	/* Reset nonce count */
	if (strcmp(p->nonce, oldnonce)) 
		p->noncecount = 0;

	/* Save auth data for following registrations */
	if (p->registry) {
		struct sip_registry *r = p->registry;

		if (strcmp(r->nonce, p->nonce)) {
			ast_string_field_set(r, realm, p->realm);
			ast_string_field_set(r, nonce, p->nonce);
			ast_string_field_set(r, domain, p->domain);
			ast_string_field_set(r, opaque, p->opaque);
			ast_string_field_set(r, qop, p->qop);
			r->noncecount = 0;
		}
	}
	return build_reply_digest(p, sipmethod, digest, digest_len); 
}

/*! \brief  Build reply digest 
\return	Returns -1 if we have no auth 
\note	Build digest challenge for authentication of peers (for registration) 
	and users (for calls). Also used for authentication of CANCEL and BYE 
*/
static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
{
	char a1[256];
	char a2[256];
	char a1_hash[256];
	char a2_hash[256];
	char resp[256];
	char resp_hash[256];
	char uri[256];
	char opaque[256] = "";
	char cnonce[80];
	const char *username;
	const char *secret;
	const char *md5secret;
	struct sip_auth *auth = NULL;	/* Realm authentication */

	if (!ast_strlen_zero(p->domain))
		ast_copy_string(uri, p->domain, sizeof(uri));
	else if (!ast_strlen_zero(p->uri))
		ast_copy_string(uri, p->uri, sizeof(uri));
	else
		snprintf(uri, sizeof(uri), "sip:%s@%s", p->username, ast_inet_ntoa(p->sa.sin_addr));

	snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());

 	/* Check if we have separate auth credentials */
 	if(!(auth = find_realm_authentication(p->peerauth, p->realm)))	/* Start with peer list */
 		auth = find_realm_authentication(authl, p->realm);	/* If not, global list */

 	if (auth) {
		ast_log(LOG_DEBUG, "use realm [%s] from peer [%s][%s]\n", auth->username, p->peername, p->username);
 		username = auth->username;
 		secret = auth->secret;
 		md5secret = auth->md5secret;
		if (sipdebug)
 			ast_debug(1, "Using realm %s authentication for call %s\n", p->realm, p->callid);
 	} else {
 		/* No authentication, use peer or register= config */
 		username = p->authname;
 		secret =  p->peersecret;
 		md5secret = p->peermd5secret;
 	}
	if (ast_strlen_zero(username))	/* We have no authentication */
		return -1;

 	/* Calculate SIP digest response */
 	snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
	snprintf(a2, sizeof(a2), "%s:%s", sip_methods[method].text, uri);
	if (!ast_strlen_zero(md5secret))
		ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
	else
		ast_md5_hash(a1_hash, a1);
	ast_md5_hash(a2_hash, a2);

	p->noncecount++;
	if (!ast_strlen_zero(p->qop))
		snprintf(resp, sizeof(resp), "%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
	else
		snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, p->nonce, a2_hash);
	ast_md5_hash(resp_hash, resp);

	/* only include the opaque string if it's set */
	if (!ast_strlen_zero(p->opaque)) {
	  snprintf(opaque, sizeof(opaque), ", opaque=\"%s\"", p->opaque);
	}

	/* XXX We hard code our qop to "auth" for now.  XXX */
	if (!ast_strlen_zero(p->qop))
		snprintf(digest, digest_len, "Digest username=\"%s\", realm=\"%s\", algorithm=MD5, uri=\"%s\", nonce=\"%s\", response=\"%s\"%s, qop=auth, cnonce=\"%s\", nc=%08x", username, p->realm, uri, p->nonce, resp_hash, opaque, cnonce, p->noncecount);
	else
		snprintf(digest, digest_len, "Digest username=\"%s\", realm=\"%s\", algorithm=MD5, uri=\"%s\", nonce=\"%s\", response=\"%s\"%s", username, p->realm, uri, p->nonce, resp_hash, opaque);

	append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);

	return 0;
}
	
/*! \brief Read SIP header (dialplan function) */
static int func_header_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len) 
{
	struct sip_pvt *p;
	const char *content = NULL;
	AST_DECLARE_APP_ARGS(args,
		AST_APP_ARG(header);
		AST_APP_ARG(number);
	);
	int i, number, start = 0;

 	if (ast_strlen_zero(data)) {
		ast_log(LOG_WARNING, "This function requires a header name.\n");
		return -1;
	}

	ast_channel_lock(chan);
	if (!IS_SIP_TECH(chan->tech)) {
		ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
		ast_channel_unlock(chan);
		return -1;
	}

	AST_STANDARD_APP_ARGS(args, data);
	if (!args.number) {
		number = 1;
	} else {
		sscanf(args.number, "%30d", &number);
		if (number < 1)
			number = 1;
	}

	p = chan->tech_pvt;

	/* If there is no private structure, this channel is no longer alive */
	if (!p) {
		ast_channel_unlock(chan);
		return -1;
	}

	for (i = 0; i < number; i++)
		content = __get_header(&p->initreq, args.header, &start);

	if (ast_strlen_zero(content)) {
		ast_channel_unlock(chan);
		return -1;
	}

	ast_copy_string(buf, content, len);
	ast_channel_unlock(chan);

	return 0;
}

static struct ast_custom_function sip_header_function = {
	.name = "SIP_HEADER",
	.synopsis = "Gets the specified SIP header",
	.syntax = "SIP_HEADER(<name>[,<number>])",
	.desc = "Since there are several headers (such as Via) which can occur multiple\n"
	"times, SIP_HEADER takes an optional second argument to specify which header with\n"
	"that name to retrieve. Headers start at offset 1.\n",
	.read = func_header_read,
};

/*! \brief  Dial plan function to check if domain is local */
static int func_check_sipdomain(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
{
	if (ast_strlen_zero(data)) {
		ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
		return -1;
	}
	if (check_sip_domain(data, NULL, 0))
		ast_copy_string(buf, data, len);
	else
		buf[0] = '\0';
	return 0;
}

static struct ast_custom_function checksipdomain_function = {
	.name = "CHECKSIPDOMAIN",
	.synopsis = "Checks if domain is a local domain",
	.syntax = "CHECKSIPDOMAIN(<domain|IP>)",
	.read = func_check_sipdomain,
	.desc = "This function checks if the domain in the argument is configured\n"
		"as a local SIP domain that this Asterisk server is configured to handle.\n"
		"Returns the domain name if it is locally handled, otherwise an empty string.\n"
		"Check the domain= configuration in sip.conf\n",
};

/*! \brief  ${SIPPEER()} Dialplan function - reads peer data */
static int function_sippeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
{
	struct sip_peer *peer;
	char *colname;

	if ((colname = strchr(data, ':'))) {	/*! \todo Will be deprecated after 1.4 */
		static int deprecation_warning = 0;
		*colname++ = '\0';
		if (deprecation_warning++ % 10 == 0)
			ast_log(LOG_WARNING, "SIPPEER(): usage of ':' to separate arguments is deprecated.  Please use ',' instead.\n");
	} else if ((colname = strchr(data, ',')))
		*colname++ = '\0';
	else
		colname = "ip";

	if (!(peer = find_peer(data, NULL, 1, 0, 0)))
		return -1;

	if (!strcasecmp(colname, "ip")) {
		ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", len);
	} else  if (!strcasecmp(colname, "port")) {
		snprintf(buf, len, "%d", ntohs(peer->addr.sin_port));
	} else  if (!strcasecmp(colname, "status")) {
		peer_status(peer, buf, len);
	} else  if (!strcasecmp(colname, "language")) {
		ast_copy_string(buf, peer->language, len);
	} else  if (!strcasecmp(colname, "regexten")) {
		ast_copy_string(buf, peer->regexten, len);
	} else  if (!strcasecmp(colname, "limit")) {
		snprintf(buf, len, "%d", peer->call_limit);
	} else  if (!strcasecmp(colname, "busylevel")) {
		snprintf(buf, len, "%d", peer->busy_level);
	} else  if (!strcasecmp(colname, "curcalls")) {
		snprintf(buf, len, "%d", peer->inUse);
	} else  if (!strcasecmp(colname, "accountcode")) {
		ast_copy_string(buf, peer->accountcode, len);
	} else  if (!strcasecmp(colname, "callgroup")) {
		ast_print_group(buf, len, peer->callgroup);
	} else  if (!strcasecmp(colname, "pickupgroup")) {
		ast_print_group(buf, len, peer->pickupgroup);
	} else  if (!strcasecmp(colname, "useragent")) {
		ast_copy_string(buf, peer->useragent, len);
	} else  if (!strcasecmp(colname, "mailbox")) {
		struct ast_str *mailbox_str = ast_str_alloca(512);
		peer_mailboxes_to_str(&mailbox_str, peer);
		ast_copy_string(buf, mailbox_str->str, len);
	} else  if (!strcasecmp(colname, "context")) {
		ast_copy_string(buf, peer->context, len);
	} else  if (!strcasecmp(colname, "expire")) {
		snprintf(buf, len, "%d", peer->expire);
	} else  if (!strcasecmp(colname, "dynamic")) {
		ast_copy_string(buf, peer->host_dynamic ? "yes" : "no", len);
	} else  if (!strcasecmp(colname, "callerid_name")) {
		ast_copy_string(buf, peer->cid_name, len);
	} else  if (!strcasecmp(colname, "callerid_num")) {
		ast_copy_string(buf, peer->cid_num, len);
	} else  if (!strcasecmp(colname, "codecs")) {
		ast_getformatname_multiple(buf, len -1, peer->capability);
	} else  if (!strncasecmp(colname, "chanvar[", 8)) {
		char *chanvar=colname + 8;
		struct ast_variable *v;
	
		chanvar = strsep(&chanvar, "]");
		for (v = peer->chanvars ; v ; v = v->next)
			if (!strcasecmp(v->name, chanvar))
				ast_copy_string(buf, v->value, len);
	} else  if (!strncasecmp(colname, "codec[", 6)) {
		char *codecnum;
		int index = 0, codec = 0;
		
		codecnum = colname + 6;	/* move past the '[' */
		codecnum = strsep(&codecnum, "]"); /* trim trailing ']' if any */
		index = atoi(codecnum);
		if((codec = ast_codec_pref_index(&peer->prefs, index))) {
			ast_copy_string(buf, ast_getformatname(codec), len);
		}
	}

	unref_peer(peer);

	return 0;
}

/*! \brief Structure to declare a dialplan function: SIPPEER */
struct ast_custom_function sippeer_function = {
	.name = "SIPPEER",
	.synopsis = "Gets SIP peer information",
	.syntax = "SIPPEER(<peername>[,item])",
	.read = function_sippeer,
	.desc = "Valid items are:\n"
	"- ip (default)          The IP address.\n"
	"- port                  The port number\n"
	"- mailbox               The configured mailbox.\n"
	"- context               The configured context.\n"
	"- expire                The epoch time of the next expire.\n"
	"- dynamic               Is it dynamic? (yes/no).\n"
	"- callerid_name         The configured Caller ID name.\n"
	"- callerid_num          The configured Caller ID number.\n"
	"- callgroup             The configured Callgroup.\n"
	"- pickupgroup           The configured Pickupgroup.\n"
	"- codecs                The configured codecs.\n"
	"- status                Status (if qualify=yes).\n"
	"- regexten              Registration extension\n"
	"- limit                 Call limit (call-limit)\n"
	"- busylevel             Configured call level for signalling busy\n"
	"- curcalls              Current amount of calls \n"
	"                        Only available if call-limit is set\n"
	"- language              Default language for peer\n"
	"- accountcode           Account code for this peer\n"
	"- useragent             Current user agent id for peer\n"
	"- chanvar[name]         A channel variable configured with setvar for this peer.\n"
	"- codec[x]              Preferred codec index number 'x' (beginning with zero).\n"
	"\n"
};

/*! \brief ${SIPCHANINFO()} Dialplan function - reads sip channel data */
static int function_sipchaninfo_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
{
	struct sip_pvt *p;

	*buf = 0;
	
 	if (!data) {
		ast_log(LOG_WARNING, "This function requires a parameter name.\n");
		return -1;
	}

	ast_channel_lock(chan);
	if (!IS_SIP_TECH(chan->tech)) {
		ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
		ast_channel_unlock(chan);
		return -1;
	}

	p = chan->tech_pvt;

	/* If there is no private structure, this channel is no longer alive */
	if (!p) {
		ast_channel_unlock(chan);
		return -1;
	}

	if (!strcasecmp(data, "peerip")) {
		ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", len);
	} else  if (!strcasecmp(data, "recvip")) {
		ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", len);
	} else  if (!strcasecmp(data, "from")) {
		ast_copy_string(buf, p->from, len);
	} else  if (!strcasecmp(data, "uri")) {
		ast_copy_string(buf, p->uri, len);
	} else  if (!strcasecmp(data, "useragent")) {
		ast_copy_string(buf, p->useragent, len);
	} else  if (!strcasecmp(data, "peername")) {
		ast_copy_string(buf, p->peername, len);
	} else if (!strcasecmp(data, "t38passthrough")) {
		if (p->t38.state == T38_DISABLED) {
			ast_copy_string(buf, "0", len);
		} else { /* T38 is offered or enabled in this call */
			ast_copy_string(buf, "1", len);
		}
	} else {
		ast_channel_unlock(chan);
		return -1;
	}
	ast_channel_unlock(chan);

	return 0;
}

/*! \brief Structure to declare a dialplan function: SIPCHANINFO */
static struct ast_custom_function sipchaninfo_function = {
	.name = "SIPCHANINFO",
	.synopsis = "Gets the specified SIP parameter from the current channel",
	.syntax = "SIPCHANINFO(item)",
	.read = function_sipchaninfo_read,
	.desc = "Valid items are:\n"
	"- peerip                The IP address of the peer.\n"
	"- recvip                The source IP address of the peer.\n"
	"- from                  The URI from the From: header.\n"
	"- uri                   The URI from the Contact: header.\n"
	"- useragent             The useragent.\n"
	"- peername              The name of the peer.\n"
	"- t38passthrough        1 if T38 is offered or enabled in this channel, otherwise 0\n"
};

/*! \brief Parse 302 Moved temporalily response */
static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req)
{
	char tmp[SIPBUFSIZE];
	char *s, *e, *t, *trans;
	char *domain;
	enum sip_transport transport = SIP_TRANSPORT_UDP;

	ast_copy_string(tmp, get_header(req, "Contact"), sizeof(tmp));
	if ((t = strchr(tmp, ',')))
		*t = '\0';

	s = get_in_brackets(tmp);
	if ((trans = strcasestr(s, ";transport="))) do {
		trans += 11;

		if ((e = strchr(trans, ';')))
			*e = '\0';

		if (!strncasecmp(trans, "tcp", 3))
			transport = SIP_TRANSPORT_TCP;
		else if (!strncasecmp(trans, "tls", 3))
			transport = SIP_TRANSPORT_TLS;
		else {
			if (strncasecmp(trans, "udp", 3))
				ast_debug(1, "received contact with an invalid transport, '%s'\n", s);
			transport = SIP_TRANSPORT_UDP;
		}
	} while(0);
	s = remove_uri_parameters(s);

	if (p->socket.tcptls_session) {
		ao2_ref(p->socket.tcptls_session, -1);
		p->socket.tcptls_session = NULL;
	}

	p->socket.fd = -1;
	p->socket.type = transport;

	if (ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
		char *host = NULL;
		if (!strncasecmp(s, "sip:", 4))
			s += 4;
		else if (!strncasecmp(s, "sips:", 5))
			s += 5;
		e = strchr(s, '/');
		if (e)
			*e = '\0';
		if ((host = strchr(s, '@'))) {
			*host++ = '\0';
			ast_debug(2, "Found promiscuous redirection to 'SIP/%s::::%s@%s'\n", s, get_transport(transport), host);
			if (p->owner)
				ast_string_field_build(p->owner, call_forward, "SIP/%s::::%s@%s", s, get_transport(transport), host);
		} else {
			ast_debug(2, "Found promiscuous redirection to 'SIP/::::%s@%s'\n", get_transport(transport), s);
			if (p->owner)
				ast_string_field_build(p->owner, call_forward, "SIP/::::%s@%s", get_transport(transport), s);
		}
	} else {
		e = strchr(tmp, '@');
		if (e) {
			*e++ = '\0';
			domain = e;
		} else {
			/* No username part */
			domain = tmp;
		}
		e = strchr(tmp, '/');	/* WHEN do we hae a forward slash in the URI? */
		if (e)
			*e = '\0';

		if (!strncasecmp(s, "sip:", 4))
			s += 4;
		else if (!strncasecmp(s, "sips:", 5))
			s += 5;
		e = strchr(s, ';');	/* And username ; parameters? */
		if (e)
			*e = '\0';	
		ast_debug(2, "Received 302 Redirect to extension '%s' (domain %s)\n", s, domain);
		if (p->owner) {
			pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
			ast_string_field_set(p->owner, call_forward, s);
		}
	}
}

/*! \brief Check pending actions on SIP call */
static void check_pendings(struct sip_pvt *p)
{
	if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
		/* if we can't BYE, then this is really a pending CANCEL */
		if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA)
			transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
			/* Actually don't destroy us yet, wait for the 487 on our original 
			   INVITE, but do set an autodestruct just in case we never get it. */
		else {
			/* We have a pending outbound invite, don't send someting
				new in-transaction */
			if (p->pendinginvite)
				return;

			/* Perhaps there is an SD change INVITE outstanding */
			transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
		}
		ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);	
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
	} else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
		/* if we can't REINVITE, hold it for later */
		if (p->pendinginvite || p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA || p->waitid > 0) {
			ast_debug(2, "NOT Sending pending reinvite (yet) on '%s'\n", p->callid);
		} else {
			ast_debug(2, "Sending pending reinvite on '%s'\n", p->callid);
			/* Didn't get to reinvite yet, so do it now */
			transmit_reinvite_with_sdp(p, (p->t38.state == T38_LOCAL_REINVITE ? TRUE : FALSE), FALSE);
			ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);	
		}
	}
}

/*! \brief Reset the NEEDREINVITE flag after waiting when we get 491 on a Re-invite
	to avoid race conditions between asterisk servers.
	Called from the scheduler.
*/
static int sip_reinvite_retry(const void *data)
{
	struct sip_pvt *p = (struct sip_pvt *) data;
	sip_pvt_lock(p); /* called from schedule thread which requires a lock */
	ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
	p->waitid = -1;
	check_pendings(p);
	sip_pvt_unlock(p);
	return 0;
}


/*! \brief Handle SIP response to INVITE dialogue */
static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
{
	int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
	int res = 0;
	int xmitres = 0;
	int reinvite = (p->owner && p->owner->_state == AST_STATE_UP);
	char *p_hdrval;
	int rtn;

	if (reinvite)
		ast_debug(4, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
	else
		ast_debug(4, "SIP response %d to standard invite\n", resp);

	if (p->alreadygone) { /* This call is already gone */
		ast_debug(1, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
		return;
	}

	/* Acknowledge sequence number - This only happens on INVITE from SIP-call */
	/* Don't auto congest anymore since we've gotten something useful back */
	AST_SCHED_DEL(sched, p->initid);

	/* RFC3261 says we must treat every 1xx response (but not 100)
	   that we don't recognize as if it was 183.
	*/
	if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 182 && resp != 183)
		resp = 183;

 	/* Any response between 100 and 199 is PROCEEDING */
 	if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING)
 		p->invitestate = INV_PROCEEDING;
 
 	/* Final response, not 200 ? */
 	if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA ))
 		p->invitestate = INV_COMPLETED;
 	
	/* Final response, clear out pending invite */
	if ((resp == 200 || resp >= 300) && p->pendinginvite && seqno == p->pendinginvite)
		p->pendinginvite = 0;

	switch (resp) {
	case 100:	/* Trying */
	case 101:	/* Dialog establishment */
		if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
			ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
		check_pendings(p);
		break;

	case 180:	/* 180 Ringing */
	case 182:       /* 182 Queued */
		if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
			ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
		if (!req->ignore && p->owner) {
			ast_queue_control(p->owner, AST_CONTROL_RINGING);
			if (p->owner->_state != AST_STATE_UP) {
				ast_setstate(p->owner, AST_STATE_RINGING);
			}
		}
		if (find_sdp(req)) {
			if (p->invitestate != INV_CANCELLED)
				p->invitestate = INV_EARLY_MEDIA;
			res = process_sdp(p, req, SDP_T38_NONE);
			if (!req->ignore && p->owner) {
				/* Queue a progress frame only if we have SDP in 180 or 182 */
				ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
			}
		}
		check_pendings(p);
		break;

	case 183:	/* Session progress */
		if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
			ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
		if (find_sdp(req)) {
			if (p->invitestate != INV_CANCELLED)
				p->invitestate = INV_EARLY_MEDIA;
			res = process_sdp(p, req, SDP_T38_NONE);
			if (!req->ignore && p->owner) {
				/* Queue a progress frame */
				ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
			}
		} else {
			/* Alcatel PBXs are known to send 183s with no SDP after sending
			 * a 100 Trying response. We're just going to treat this sort of thing
			 * the same as we would treat a 180 Ringing
			 */
			if (!req->ignore && p->owner) {
				ast_queue_control(p->owner, AST_CONTROL_RINGING);
			}
		}
		check_pendings(p);
		break;

	case 200:	/* 200 OK on invite - someone's answering our call */
		if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
			ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
		p->authtries = 0;
		if (find_sdp(req)) {
			if ((res = process_sdp(p, req, SDP_T38_ACCEPT)) && !req->ignore)
				if (!reinvite)
					/* This 200 OK's SDP is not acceptable, so we need to ack, then hangup */
					/* For re-invites, we try to recover */
					ast_set_flag(&p->flags[0], SIP_PENDINGBYE);	
		}

		/* Parse contact header for continued conversation */
		/* When we get 200 OK, we know which device (and IP) to contact for this call */
		/* This is important when we have a SIP proxy between us and the phone */
		if (outgoing) {
			update_call_counter(p, DEC_CALL_RINGING);
			parse_ok_contact(p, req);
			/* Save Record-Route for any later requests we make on this dialogue */
			if (!reinvite)
				build_route(p, req, 1);

			if(set_address_from_contact(p)) {
				/* Bad contact - we don't know how to reach this device */
				/* We need to ACK, but then send a bye */
				if (!p->route && !req->ignore)
					ast_set_flag(&p->flags[0], SIP_PENDINGBYE);	
			} 

		}

		if (!req->ignore && p->owner) {
			if (!reinvite) {
				ast_queue_control(p->owner, AST_CONTROL_ANSWER);
				if (global_callevents)
					manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
						"Channel: %s\r\nChanneltype: %s\r\nUniqueid: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
						p->owner->name, "SIP", p->owner->uniqueid, p->callid, p->fullcontact, p->peername);
			} else {	/* RE-invite */
				ast_queue_frame(p->owner, &ast_null_frame);
			}
		} else {
			 /* It's possible we're getting an 200 OK after we've tried to disconnect
				  by sending CANCEL */
			/* First send ACK, then send bye */
			if (!req->ignore)
				ast_set_flag(&p->flags[0], SIP_PENDINGBYE);	
		}

		/* Check for Session-Timers related headers */
		if (st_get_mode(p) != SESSION_TIMER_MODE_REFUSE && p->outgoing_call == TRUE && !reinvite) {
			p_hdrval = (char*)get_header(req, "Session-Expires");
        		if (!ast_strlen_zero(p_hdrval)) {
				/* UAS supports Session-Timers */
				enum st_refresher tmp_st_ref = SESSION_TIMER_REFRESHER_AUTO;
				int tmp_st_interval = 0;
				rtn = parse_session_expires(p_hdrval, &tmp_st_interval, &tmp_st_ref);
				if (rtn != 0) {
					ast_set_flag(&p->flags[0], SIP_PENDINGBYE);	
				}
				if (tmp_st_ref == SESSION_TIMER_REFRESHER_UAC || 
					tmp_st_ref == SESSION_TIMER_REFRESHER_UAS) {
					p->stimer->st_ref = tmp_st_ref;
				} 
				if (tmp_st_interval) {
					p->stimer->st_interval = tmp_st_interval;
				}
				p->stimer->st_active = TRUE;
				p->stimer->st_active_peer_ua = TRUE;
				start_session_timer(p);
			} else {
				/* UAS doesn't support Session-Timers */
				if (st_get_mode(p) == SESSION_TIMER_MODE_ORIGINATE) {
					p->stimer->st_ref = SESSION_TIMER_REFRESHER_UAC;
					p->stimer->st_active_peer_ua = FALSE;
					start_session_timer(p);
				}
			}
		}


		/* If I understand this right, the branch is different for a non-200 ACK only */
		p->invitestate = INV_TERMINATED;
		ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
		xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
		check_pendings(p);
		break;

	case 407: /* Proxy authentication */
	case 401: /* Www auth */
		/* First we ACK */
		xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
		if (p->options)
			p->options->auth_type = resp;

		/* Then we AUTH */
		ast_string_field_set(p, theirtag, NULL);	/* forget their old tag, so we don't match tags when getting response */
		if (!req->ignore) {
			if (p->authtries < MAX_AUTHTRIES)
				p->invitestate = INV_CALLING;
			if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, SIP_INVITE, 1)) {
				ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
				p->needdestroy = 1;
				sip_alreadygone(p);
				if (p->owner)
					ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
			}
		}
		break;

	case 403: /* Forbidden */
		/* First we ACK */
		xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
		ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", get_header(&p->initreq, "From"));
		if (!req->ignore && p->owner)
			ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
		p->needdestroy = 1;
		sip_alreadygone(p);
		break;

	case 404: /* Not found */
		xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
		if (p->owner && !req->ignore)
			ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
		sip_alreadygone(p);
		break;

	case 408: /* Request timeout */
	case 481: /* Call leg does not exist */
		/* Could be REFER caused INVITE with replaces */
		ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
		xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
		if (p->owner)
			ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
		break;

	case 422: /* Session-Timers: Session interval too small */
		xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
		ast_string_field_set(p, theirtag, NULL);
		proc_422_rsp(p, req);
		break;

	case 487: /* Cancelled transaction */
		/* We have sent CANCEL on an outbound INVITE 
			This transaction is already scheduled to be killed by sip_hangup().
		*/
		xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
		if (p->owner && !req->ignore) {
			ast_queue_hangup(p->owner);
			append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
 		} else if (!req->ignore) {
			update_call_counter(p, DEC_CALL_LIMIT);
			append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
			p->needdestroy = 1;
			sip_alreadygone(p);
		}
		break;
	case 415: /* Unsupported media type */
	case 488: /* Not acceptable here */
	case 606: /* Not Acceptable */
		xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
		if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
			change_t38_state(p, T38_DISABLED);
			/* Try to reset RTP timers */
			ast_rtp_set_rtptimers_onhold(p->rtp);

			/* Trigger a reinvite back to audio */
			transmit_reinvite_with_sdp(p, FALSE, FALSE);
		} else {
			/* We can't set up this call, so give up */
			if (p->owner && !req->ignore)
				ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
			p->needdestroy = 1;
			/* If there's no dialog to end, then mark p as already gone */
			if (!reinvite)
				sip_alreadygone(p);
		}
		break;
	case 491: /* Pending */
		xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
		if (p->owner && !req->ignore) {
			if (p->owner->_state != AST_STATE_UP) {
				ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
				p->needdestroy = 1;
			} else {
				/* This is a re-invite that failed. */
				/* Reset the flag after a while 
				 */
				int wait;
				/* RFC 3261, if owner of call, wait between 2.1 to 4 seconds,
				 * if not owner of call, wait 0 to 2 seconds */
				if (p->outgoing_call) {
					wait = 2100 + ast_random() % 2000;
				} else {
					wait = ast_random() % 2000;
				}
				p->waitid = ast_sched_add(sched, wait, sip_reinvite_retry, p);
				ast_debug(2, "Reinvite race. Waiting %d secs before retry\n", wait);
			}
		}
		break;

	case 501: /* Not implemented */
		xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
		if (p->owner)
			ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
		break;
	}
	if (xmitres == XMIT_ERROR)
		ast_log(LOG_WARNING, "Could not transmit message in dialog %s\n", p->callid);
}

/* \brief Handle SIP response in REFER transaction
	We've sent a REFER, now handle responses to it 
  */
static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
{
	/* If no refer structure exists, then do nothing */
	if (!p->refer)
		return;

	switch (resp) {
	case 202:   /* Transfer accepted */
		/* We need  to do something here */
		/* The transferee is now sending INVITE to target */
		p->refer->status = REFER_ACCEPTED;
		/* Now wait for next message */
		ast_debug(3, "Got 202 accepted on transfer\n");
		/* We should hang along, waiting for NOTIFY's here */
		break;

	case 401:   /* Not www-authorized on SIP method */
	case 407:   /* Proxy auth */
		if (ast_strlen_zero(p->authname)) {
			ast_log(LOG_WARNING, "Asked to authenticate REFER to %s:%d but we have no matching peer or realm auth!\n",
				ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
			p->needdestroy = 1;
		}
		if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_REFER, 0)) {
			ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", get_header(&p->initreq, "From"));
			p->refer->status = REFER_NOAUTH;
			p->needdestroy = 1;
		}
		break;
	case 481: /* Call leg does not exist */

		/* A transfer with Replaces did not work */
		/* OEJ: We should Set flag, cancel the REFER, go back
		to original call - but right now we can't */
		ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
		if (p->owner)
			ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
		p->needdestroy = 1;
		break;

	case 500:   /* Server error */
	case 501:   /* Method not implemented */
		/* Return to the current call onhold */
		/* Status flag needed to be reset */
		ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
		p->needdestroy = 1;
		p->refer->status = REFER_FAILED;
		break;
	case 603:   /* Transfer declined */
		ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
		p->refer->status = REFER_FAILED;
		p->needdestroy = 1;
		break;
	}
}

/*! \brief Handle responses on REGISTER to services */
static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
{
	int expires, expires_ms;
	struct sip_registry *r;
	r=p->registry;

	switch (resp) {
	case 401:	/* Unauthorized */
		if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
			ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
			p->needdestroy = 1;
		}
		break;
	case 403:	/* Forbidden */
		ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
		AST_SCHED_DEL(sched, r->timeout);
		r->regstate = REG_STATE_NOAUTH;
		p->needdestroy = 1;
		break;
	case 404:	/* Not found */
		ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username, p->registry->hostname);
		p->needdestroy = 1;
		r->call = NULL;
		r->regstate = REG_STATE_REJECTED;
		AST_SCHED_DEL(sched, r->timeout);
		break;
	case 407:	/* Proxy auth */
		if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
			ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
			p->needdestroy = 1;
		}
		break;
	case 408:	/* Request timeout */
		/* Got a timeout response, so reset the counter of failed responses */
		if (r) {
			r->regattempts = 0;
		} else {
			ast_log(LOG_WARNING, "Got a 408 response to our REGISTER on call %s after we had destroyed the registry object\n", p->callid);
		}
		break;
	case 423:	/* Interval too brief */
		r->expiry = atoi(get_header(req, "Min-Expires"));
		ast_log(LOG_WARNING, "Got 423 Interval too brief for service %s@%s, minimum is %d seconds\n", p->registry->username, p->registry->hostname, r->expiry);
		ast_sched_del(sched, r->timeout);
		r->timeout = -1;
		if (r->call) {
			r->call = NULL;
			p->needdestroy = 1;
		}
		if (r->expiry > max_expiry) {
			ast_log(LOG_WARNING, "Required expiration time from %s@%s is too high, giving up\n", p->registry->username, p->registry->hostname);
			r->expiry = r->configured_expiry;
			r->regstate = REG_STATE_REJECTED;
		} else {
			r->regstate = REG_STATE_UNREGISTERED;
			transmit_register(r, SIP_REGISTER, NULL, NULL);
		}
		manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nUsername: %s\r\nDomain: %s\r\nStatus: %s\r\n", r->username, r->hostname, regstate2str(r->regstate));
		break;
	case 479:	/* SER: Not able to process the URI - address is wrong in register*/
		ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username, p->registry->hostname);
		p->needdestroy = 1;
		r->call = NULL;
		r->regstate = REG_STATE_REJECTED;
		AST_SCHED_DEL(sched, r->timeout);
		break;
	case 200:	/* 200 OK */
		if (!r) {
			ast_log(LOG_WARNING, "Got 200 OK on REGISTER, but there isn't a registry entry for '%s' (we probably already got the OK)\n", S_OR(p->peername, p->username));
			p->needdestroy = 1;
			return 0;
		}

		r->regstate = REG_STATE_REGISTERED;
		r->regtime = ast_tvnow();		/* Reset time of last succesful registration */
		manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r->hostname, regstate2str(r->regstate));
		r->regattempts = 0;
		ast_debug(1, "Registration successful\n");
		if (r->timeout > -1) {
			ast_debug(1, "Cancelling timeout %d\n", r->timeout);
		}
		AST_SCHED_DEL(sched, r->timeout);
		r->call = NULL;
		p->registry = NULL;
		/* Let this one hang around until we have all the responses */
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
		/* p->needdestroy = 1; */

		/* set us up for re-registering */
		/* figure out how long we got registered for */
		AST_SCHED_DEL(sched, r->expire);
		/* according to section 6.13 of RFC, contact headers override
		   expires headers, so check those first */
		expires = 0;

		/* XXX todo: try to save the extra call */
		if (!ast_strlen_zero(get_header(req, "Contact"))) {
			const char *contact = NULL;
			const char *tmptmp = NULL;
			int start = 0;
			for(;;) {
				contact = __get_header(req, "Contact", &start);
				/* this loop ensures we get a contact header about our register request */
				if(!ast_strlen_zero(contact)) {
					if( (tmptmp=strstr(contact, p->our_contact))) {
						contact=tmptmp;
						break;
					}
				} else
					break;
			}
			tmptmp = strcasestr(contact, "expires=");
			if (tmptmp) {
				if (sscanf(tmptmp + 8, "%30d;", &expires) != 1)
					expires = 0;
			}

		}
		if (!expires) 
			expires=atoi(get_header(req, "expires"));
		if (!expires)
			expires=default_expiry;

		expires_ms = expires * 1000;
		if (expires <= EXPIRY_GUARD_LIMIT)
			expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT), EXPIRY_GUARD_MIN);
		else
			expires_ms -= EXPIRY_GUARD_SECS * 1000;
		if (sipdebug)
			ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000); 

		r->refresh= (int) expires_ms / 1000;

		/* Schedule re-registration before we expire */
		AST_SCHED_REPLACE(r->expire, sched, expires_ms, sip_reregister, r); 
		registry_unref(r);
	}
	return 1;
}

/*! \brief Handle qualification responses (OPTIONS) */
static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
{
	struct sip_peer *peer = p->relatedpeer;
	int statechanged, is_reachable, was_reachable;
	int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);

	/*
	 * Compute the response time to a ping (goes in peer->lastms.)
	 * -1 means did not respond, 0 means unknown,
	 * 1..maxms is a valid response, >maxms means late response.
	 */
	if (pingtime < 1)	/* zero = unknown, so round up to 1 */
		pingtime = 1;

	/* Now determine new state and whether it has changed.
	 * Use some helper variables to simplify the writing
	 * of the expressions.
	 */
	was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
	is_reachable = pingtime <= peer->maxms;
	statechanged = peer->lastms == 0 /* yes, unknown before */
		|| was_reachable != is_reachable;

	peer->lastms = pingtime;
	peer->call = NULL;
	if (statechanged) {
		const char *s = is_reachable ? "Reachable" : "Lagged";
		char str_lastms[20];
		snprintf(str_lastms, sizeof(str_lastms), "%d", pingtime);

		ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
			peer->name, s, pingtime, peer->maxms);
		ast_device_state_changed("SIP/%s", peer->name);
		if (sip_cfg.peer_rtupdate) {
			ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", str_lastms, NULL);
		}
		manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
			"ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
			peer->name, s, pingtime);
		if (is_reachable && global_regextenonqualify)
			register_peer_exten(peer, TRUE);
	}

	p->needdestroy = 1;

	/* Try again eventually */
	AST_SCHED_REPLACE(peer->pokeexpire, sched,
		is_reachable ? peer->qualifyfreq : DEFAULT_FREQ_NOTOK,
		sip_poke_peer_s, peer);
}

/*! \brief Immediately stop RTP, VRTP and UDPTL as applicable */
static void stop_media_flows(struct sip_pvt *p)
{
	/* Immediately stop RTP, VRTP and UDPTL as applicable */
	if (p->rtp)
		ast_rtp_stop(p->rtp);
	if (p->vrtp)
		ast_rtp_stop(p->vrtp);
	if (p->trtp)
		ast_rtp_stop(p->trtp);
	if (p->udptl)
		ast_udptl_stop(p->udptl);
}

/*! \brief Handle SIP response in dialogue */
/* XXX only called by handle_incoming */
static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
{
	struct ast_channel *owner;
	int sipmethod;
	int res = 1;
	const char *c = get_header(req, "Cseq");
	/* GCC 4.2 complains if I try to cast c as a char * when passing it to ast_skip_nonblanks, so make a copy of it */
	char *c_copy = ast_strdupa(c);
	/* Skip the Cseq and its subsequent spaces */
	const char *msg = ast_skip_blanks(ast_skip_nonblanks(c_copy));

	if (!msg)
		msg = "";

	sipmethod = find_sip_method(msg);

	owner = p->owner;
	if (owner) 
		owner->hangupcause = hangup_sip2cause(resp);

	if (p->socket.type == SIP_TRANSPORT_UDP) {
		int ack_res;

		/* Acknowledge whatever it is destined for */
		if ((resp >= 100) && (resp <= 199)) {
			ack_res = __sip_semi_ack(p, seqno, 0, sipmethod);
		} else {
			ack_res = __sip_ack(p, seqno, 0, sipmethod);
		}

		if (ack_res == FALSE) {
			append_history(p, "Ignore", "Ignoring this retransmit\n");
			return;
		}
	}

	/* If this is a NOTIFY for a subscription clear the flag that indicates that we have a NOTIFY pending */
	if (!p->owner && sipmethod == SIP_NOTIFY && p->pendinginvite) 
		p->pendinginvite = 0;

	/* Get their tag if we haven't already */
	if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
		char tag[128];

		gettag(req, "To", tag, sizeof(tag));
		ast_string_field_set(p, theirtag, tag);
	}
	/* This needs to be configurable on a channel/peer/user level,
	   not mandatory for all communication. Sadly enough, NAT implementations
	   are not so stable so we can always rely on these headers. 
		Temporarily disabled, while waiting for fix.
	   Fix assigned to Rizzo :-)
	*/
	/* check_via_response(p, req); */

	/* RFC 3261 Section 15 specifies that if we receive a 408 or 481
	 * in response to a BYE, then we should end the current dialog
	 * and session.  It is known that at least one phone manufacturer
	 * potentially will send a 404 in response to a BYE, so we'll be
	 * liberal in what we accept and end the dialog and session if we
	 * receive any of those responses to a BYE.
	 */
	if ((resp == 404 || resp == 408 || resp == 481) && sipmethod == SIP_BYE) {
		p->needdestroy = 1;
		return;
	}

	if (p->relatedpeer && p->method == SIP_OPTIONS) {
		/* We don't really care what the response is, just that it replied back. 
		   Well, as long as it's not a 100 response...  since we might
		   need to hang around for something more "definitive" */
		if (resp != 100)
			handle_response_peerpoke(p, resp, req);
	} else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
		switch(resp) {
		case 100:	/* 100 Trying */
		case 101:	/* 101 Dialog establishment */
			if (sipmethod == SIP_INVITE) 
				handle_response_invite(p, resp, rest, req, seqno);
			break;
		case 183:	/* 183 Session Progress */
			if (sipmethod == SIP_INVITE) 
				handle_response_invite(p, resp, rest, req, seqno);
			break;
		case 180:	/* 180 Ringing */
			if (sipmethod == SIP_INVITE) 
				handle_response_invite(p, resp, rest, req, seqno);
			break;
		case 182:       /* 182 Queued */
			if (sipmethod == SIP_INVITE)
				handle_response_invite(p, resp, rest, req, seqno);
			break;
		case 200:	/* 200 OK */
			p->authtries = 0;	/* Reset authentication counter */
			if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
				/* We successfully transmitted a message 
					or a video update request in INFO */
				/* Nothing happens here - the message is inside a dialog */
			} else if (sipmethod == SIP_INVITE) {
				handle_response_invite(p, resp, rest, req, seqno);
			} else if (sipmethod == SIP_NOTIFY) {
				/* They got the notify, this is the end */
				if (p->owner) {
					if (!p->refer) {
						ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", p->owner->name);
						ast_queue_hangup(p->owner);
					} else
						ast_debug(4, "Got OK on REFER Notify message\n");
				} else {
					if (p->subscribed == NONE) 
						p->needdestroy = 1;
					if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
						/* Ready to send the next state we have on queue */
						ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
						cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
					}
				}
			} else if (sipmethod == SIP_REGISTER) 
				res = handle_response_register(p, resp, rest, req, seqno);
			else if (sipmethod == SIP_BYE) {		/* Ok, we're ready to go */
				p->needdestroy = 1;
				ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
			} else if (sipmethod == SIP_SUBSCRIBE) {
				ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
			}
			break;
		case 202:   /* Transfer accepted */
			if (sipmethod == SIP_REFER) 
				handle_response_refer(p, resp, rest, req, seqno);
			break;
		case 401: /* Not www-authorized on SIP method */
		case 407: /* Proxy auth required */
			if (sipmethod == SIP_INVITE)
				handle_response_invite(p, resp, rest, req, seqno);
			else if (sipmethod == SIP_REFER)
				handle_response_refer(p, resp, rest, req, seqno);
			else if (p->registry && sipmethod == SIP_REGISTER)
				res = handle_response_register(p, resp, rest, req, seqno);
			else if (sipmethod == SIP_BYE) {
				if (p->options)
					p->options->auth_type = resp;
				if (ast_strlen_zero(p->authname)) {
					ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
							msg, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
					p->needdestroy = 1;
				} else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp,  sipmethod, 0)) {
					ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
					p->needdestroy = 1;
				}
			} else {
				ast_log(LOG_WARNING, "Got authentication request (%d) on %s to '%s'\n", resp, sip_methods[sipmethod].text, get_header(req, "To"));
				p->needdestroy = 1;
			}
			break;
		case 403: /* Forbidden - we failed authentication */
			if (sipmethod == SIP_INVITE)
				handle_response_invite(p, resp, rest, req, seqno);
			else if (p->registry && sipmethod == SIP_REGISTER) 
				res = handle_response_register(p, resp, rest, req, seqno);
			else {
				ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
				p->needdestroy = 1;
			}
			break;
		case 404: /* Not found */
			if (p->registry && sipmethod == SIP_REGISTER)
				res = handle_response_register(p, resp, rest, req, seqno);
			else if (sipmethod == SIP_INVITE)
				handle_response_invite(p, resp, rest, req, seqno);
			else if (owner)
				ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
			break;
		case 423: /* Interval too brief */
			if (sipmethod == SIP_REGISTER)
				res = handle_response_register(p, resp, rest, req, seqno);
			break;
		case 408: /* Request timeout - terminate dialog */
			if (sipmethod == SIP_INVITE)
				handle_response_invite(p, resp, rest, req, seqno);
			else if (sipmethod == SIP_REGISTER) 
				res = handle_response_register(p, resp, rest, req, seqno);
			else if (sipmethod == SIP_BYE) {
				p->needdestroy = 1;
				ast_debug(4, "Got timeout on bye. Thanks for the answer. Now, kill this call\n");
			} else {
				if (owner)
					ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
				p->needdestroy = 1;
			}
			break;

		case 422: /* Session-Timers: Session Interval Too Small */
			if (sipmethod == SIP_INVITE) {
				handle_response_invite(p, resp, rest, req, seqno);
			}
			break;

		case 481: /* Call leg does not exist */
			if (sipmethod == SIP_INVITE) {
				handle_response_invite(p, resp, rest, req, seqno);
			} else if (sipmethod == SIP_REFER) {
				handle_response_refer(p, resp, rest, req, seqno);
			} else if (sipmethod == SIP_BYE) {
				/* The other side has no transaction to bye,
				just assume it's all right then */
				ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
			} else if (sipmethod == SIP_CANCEL) {
				/* The other side has no transaction to cancel,
				just assume it's all right then */
				ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
			} else {
				ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
				/* Guessing that this is not an important request */
			}
			break;
		case 487:
			if (sipmethod == SIP_INVITE)
				handle_response_invite(p, resp, rest, req, seqno);
			break;
		case 415: /* Unsupported media type */
		case 488: /* Not acceptable here - codec error */
		case 606: /* Not Acceptable */
			if (sipmethod == SIP_INVITE)
				handle_response_invite(p, resp, rest, req, seqno);
			break;
		case 491: /* Pending */
			if (sipmethod == SIP_INVITE)
				handle_response_invite(p, resp, rest, req, seqno);
			else {
				ast_debug(1, "Got 491 on %s, unspported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
				p->needdestroy = 1;
			}
			break;
		case 501: /* Not Implemented */
			if (sipmethod == SIP_INVITE)
				handle_response_invite(p, resp, rest, req, seqno);
			else if (sipmethod == SIP_REFER)
				handle_response_refer(p, resp, rest, req, seqno);
			else
				ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_inet_ntoa(p->sa.sin_addr), msg);
			break;
		case 603:	/* Declined transfer */
			if (sipmethod == SIP_REFER) {
				handle_response_refer(p, resp, rest, req, seqno);
				break;
			}
			/* Fallthrough */
		default:
			if ((resp >= 300) && (resp < 700)) {
				/* Fatal response */
				if ((resp != 487))
					ast_verb(3, "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
	
				if (sipmethod == SIP_INVITE)
					stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */

				/* XXX Locking issues?? XXX */
				switch(resp) {
				case 300: /* Multiple Choices */
				case 301: /* Moved permanently */
				case 302: /* Moved temporarily */
				case 305: /* Use Proxy */
					parse_moved_contact(p, req);
					/* Fall through */
				case 486: /* Busy here */
				case 600: /* Busy everywhere */
				case 603: /* Decline */
					if (p->owner)
						ast_queue_control(p->owner, AST_CONTROL_BUSY);
					break;
				case 482: /*!
					\note SIP is incapable of performing a hairpin call, which
					is yet another failure of not having a layer 2 (again, YAY
					 IETF for thinking ahead).  So we treat this as a call
					 forward and hope we end up at the right place... */
					ast_debug(1, "Hairpin detected, setting up call forward for what it's worth\n");
					if (p->owner)
						ast_string_field_build(p->owner, call_forward,
								       "Local/%s@%s", p->username, p->context);
					/* Fall through */
				case 480: /* Temporarily Unavailable */
				case 404: /* Not Found */
				case 410: /* Gone */
				case 400: /* Bad Request */
				case 500: /* Server error */
					if (sipmethod == SIP_REFER) {
						handle_response_refer(p, resp, rest, req, seqno);
						break;
					}
					/* Fall through */
				case 502: /* Bad gateway */
				case 503: /* Service Unavailable */
				case 504: /* Server Timeout */
					if (owner)
						ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
					break;
				default:
					/* Send hangup */	
					if (owner && sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO && sipmethod != SIP_BYE)
						ast_queue_hangup(p->owner);
					break;
				}
				/* ACK on invite */
				if (sipmethod == SIP_INVITE) 
					transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
				if (sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO) 
					sip_alreadygone(p);
				if (!p->owner)
					p->needdestroy = 1;
			} else if ((resp >= 100) && (resp < 200)) {
				if (sipmethod == SIP_INVITE) {
					if (!req->ignore && sip_cancel_destroy(p))
						ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
					if (find_sdp(req))
						process_sdp(p, req, SDP_T38_NONE);
					if (p->owner) {
						/* Queue a progress frame */
						ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
					}
				}
			} else
				ast_log(LOG_NOTICE, "Dont know how to handle a %d %s response from %s\n", resp, rest, p->owner ? p->owner->name : ast_inet_ntoa(p->sa.sin_addr));
		}
	} else {	
		/* Responses to OUTGOING SIP requests on INCOMING calls 
		   get handled here. As well as out-of-call message responses */
		if (req->debug)
			ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);

		if (sipmethod == SIP_INVITE && resp == 200) {
			/* Tags in early session is replaced by the tag in 200 OK, which is 
		  	the final reply to our INVITE */
			char tag[128];

			gettag(req, "To", tag, sizeof(tag));
			ast_string_field_set(p, theirtag, tag);
		}

		switch(resp) {
		case 200:
			if (sipmethod == SIP_INVITE) {
				handle_response_invite(p, resp, rest, req, seqno);
			} else if (sipmethod == SIP_CANCEL) {
				ast_debug(1, "Got 200 OK on CANCEL\n");

				/* Wait for 487, then destroy */
			} else if (sipmethod == SIP_NOTIFY) {
				/* They got the notify, this is the end */
				if (p->owner) {
					if (p->refer) {
						ast_debug(1, "Got 200 OK on NOTIFY for transfer\n");
					} else
						ast_log(LOG_WARNING, "Notify answer on an owned channel?\n");
					/* ast_queue_hangup(p->owner); Disabled */
				} else {
					if (!p->subscribed && !p->refer)
						p->needdestroy = 1;
					if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
						/* Ready to send the next state we have on queue */
						ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
						cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
					}
				}
			} else if (sipmethod == SIP_BYE)
				p->needdestroy = 1;
			else if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO)
				/* We successfully transmitted a message or
					a video update request in INFO */
				;
			else if (sipmethod == SIP_BYE) 
				/* Ok, we're ready to go */
				p->needdestroy = 1;
			break;
		case 202:   /* Transfer accepted */
			if (sipmethod == SIP_REFER) 
				handle_response_refer(p, resp, rest, req, seqno);
			break;
		case 401:	/* www-auth */
		case 407:
			if (sipmethod == SIP_REFER)
				handle_response_refer(p, resp, rest, req, seqno);
			else if (sipmethod == SIP_INVITE) 
				handle_response_invite(p, resp, rest, req, seqno);
			else if (sipmethod == SIP_BYE) {
				if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, sipmethod, 0)) {
					ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
					p->needdestroy = 1;
				}
			}
			break;
		case 481:	/* Call leg does not exist */
			if (sipmethod == SIP_INVITE) {
				/* Re-invite failed */
				handle_response_invite(p, resp, rest, req, seqno);
			} else if (sipmethod == SIP_BYE) {
				p->needdestroy = 1;
			} else if (sipdebug) {
				ast_debug(1, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
			}
			break;
		case 501: /* Not Implemented */
			if (sipmethod == SIP_INVITE) 
				handle_response_invite(p, resp, rest, req, seqno);
			else if (sipmethod == SIP_REFER) 
				handle_response_refer(p, resp, rest, req, seqno);
			break;
		case 603:	/* Declined transfer */
			if (sipmethod == SIP_REFER) {
				handle_response_refer(p, resp, rest, req, seqno);
				break;
			}
			/* Fallthrough */
		default:	/* Errors without handlers */
			if ((resp >= 100) && (resp < 200)) {
				if (sipmethod == SIP_INVITE) { 	/* re-invite */
					if (!req->ignore && sip_cancel_destroy(p))
						ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
				}
			}
			if ((resp >= 300) && (resp < 700)) {
				if ((resp != 487))
					ast_verb(3, "Incoming call: Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
				switch(resp) {
				case 415: /* Unsupported media type */
				case 488: /* Not acceptable here - codec error */
				case 603: /* Decline */
				case 500: /* Server error */
				case 502: /* Bad gateway */
				case 503: /* Service Unavailable */
				case 504: /* Server timeout */

					/* re-invite failed */
					if (sipmethod == SIP_INVITE && sip_cancel_destroy(p))
						ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
					break;
				}
			}
			break;
		}
	}
}


/*! \brief Park SIP call support function 
	Starts in a new thread, then parks the call
	XXX Should we add a wait period after streaming audio and before hangup?? Sometimes the
		audio can't be heard before hangup
*/
static void *sip_park_thread(void *stuff)
{
	struct ast_channel *transferee, *transferer;	/* Chan1: The transferee, Chan2: The transferer */
	struct sip_dual *d;
	struct sip_request req;
	int ext;
	int res;

	d = stuff;
	transferee = d->chan1;
	transferer = d->chan2;
	copy_request(&req, &d->req);

	if (!transferee || !transferer) {
		ast_log(LOG_ERROR, "Missing channels for parking! Transferer %s Transferee %s\n", transferer ? "<available>" : "<missing>", transferee ? "<available>" : "<missing>" );
		free(d);
		return NULL;
	}
	ast_debug(4, "SIP Park: Transferer channel %s, Transferee %s\n", transferer->name, transferee->name);

	ast_channel_lock(transferee);
	if (ast_do_masquerade(transferee)) {
		ast_log(LOG_WARNING, "Masquerade failed.\n");
		transmit_response(transferer->tech_pvt, "503 Internal error", &req);
		ast_channel_unlock(transferee);
		free(d);
		return NULL;
	} 
	ast_channel_unlock(transferee);

	res = ast_park_call(transferee, transferer, 0, &ext);
	

#ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
	if (!res) {
		transmit_message_with_text(transferer->tech_pvt, "Unable to park call.\n");
	} else {
		/* Then tell the transferer what happened */
		sprintf(buf, "Call parked on extension '%d'", ext);
		transmit_message_with_text(transferer->tech_pvt, buf);
	}
#endif

	/* Any way back to the current call??? */
	/* Transmit response to the REFER request */
	transmit_response(transferer->tech_pvt, "202 Accepted", &req);
	if (!res)	{
		/* Transfer succeeded */
		append_history(transferer->tech_pvt, "SIPpark", "Parked call on %d", ext);
		transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "200 OK", TRUE);
		transferer->hangupcause = AST_CAUSE_NORMAL_CLEARING;
		ast_hangup(transferer); /* This will cause a BYE */
		ast_debug(1, "SIP Call parked on extension '%d'\n", ext);
	} else {
		transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "503 Service Unavailable", TRUE);
		append_history(transferer->tech_pvt, "SIPpark", "Parking failed\n");
		ast_debug(1, "SIP Call parked failed \n");
		/* Do not hangup call */
	}
	free(d);
	return NULL;
}

/*! \brief Park a call using the subsystem in res_features.c 
	This is executed in a separate thread
*/
static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno)
{
	struct sip_dual *d;
	struct ast_channel *transferee, *transferer;
		/* Chan2m: The transferer, chan1m: The transferee */
	pthread_t th;

	transferee = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan1->accountcode, chan1->exten, chan1->context, chan1->amaflags, "Parking/%s", chan1->name);
	transferer = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->amaflags, "SIPPeer/%s", chan2->name);
	if ((!transferer) || (!transferee)) {
		if (transferee) {
			transferee->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
			ast_hangup(transferee);
		}
		if (transferer) {
			transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
			ast_hangup(transferer);
		}
		return -1;
	}

	/* Make formats okay */
	transferee->readformat = chan1->readformat;
	transferee->writeformat = chan1->writeformat;

	/* Prepare for taking over the channel */
	ast_channel_masquerade(transferee, chan1);

	/* Setup the extensions and such */
	ast_copy_string(transferee->context, chan1->context, sizeof(transferee->context));
	ast_copy_string(transferee->exten, chan1->exten, sizeof(transferee->exten));
	transferee->priority = chan1->priority;
		
	/* We make a clone of the peer channel too, so we can play
	   back the announcement */

	/* Make formats okay */
	transferer->readformat = chan2->readformat;
	transferer->writeformat = chan2->writeformat;

	/* Prepare for taking over the channel.  Go ahead and grab this channel
	 * lock here to avoid a deadlock with callbacks into the channel driver
	 * that hold the channel lock and want the pvt lock.  */
	while (ast_channel_trylock(chan2)) {
		struct sip_pvt *pvt = chan2->tech_pvt;
		sip_pvt_unlock(pvt);
		usleep(1);
		sip_pvt_lock(pvt);
	}
	ast_channel_masquerade(transferer, chan2);
	ast_channel_unlock(chan2);

	/* Setup the extensions and such */
	ast_copy_string(transferer->context, chan2->context, sizeof(transferer->context));
	ast_copy_string(transferer->exten, chan2->exten, sizeof(transferer->exten));
	transferer->priority = chan2->priority;

	ast_channel_lock(transferer);
	if (ast_do_masquerade(transferer)) {
		ast_log(LOG_WARNING, "Masquerade failed :(\n");
		ast_channel_unlock(transferer);
		transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
		ast_hangup(transferer);
		return -1;
	}
	ast_channel_unlock(transferer);
	if (!transferer || !transferee) {
		if (!transferer) { 
			ast_debug(1, "No transferer channel, giving up parking\n");
		}
		if (!transferee) {
			ast_debug(1, "No transferee channel, giving up parking\n");
		}
		return -1;
	}
	if ((d = ast_calloc(1, sizeof(*d)))) {

		/* Save original request for followup */
		copy_request(&d->req, req);
		d->chan1 = transferee;	/* Transferee */
		d->chan2 = transferer;	/* Transferer */
		d->seqno = seqno;
		if (ast_pthread_create_detached_background(&th, NULL, sip_park_thread, d) < 0) {
			/* Could not start thread */
			ast_free(d);	/* We don't need it anymore. If thread is created, d will be free'd
					   by sip_park_thread() */
			return 0;
		}
	} 
	return -1;
}

/*! \brief Turn off generator data 
	XXX Does this function belong in the SIP channel?
*/
static void ast_quiet_chan(struct ast_channel *chan) 
{
	if (chan && chan->_state == AST_STATE_UP) {
		if (ast_test_flag(chan, AST_FLAG_MOH))
			ast_moh_stop(chan);
		else if (chan->generatordata)
			ast_deactivate_generator(chan);
	}
}

/*! \brief Attempt transfer of SIP call 
	This fix for attended transfers on a local PBX */
static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
{
	int res = 0;
	struct ast_channel *peera = NULL,	
		*peerb = NULL,
		*peerc = NULL,
		*peerd = NULL;


	/* We will try to connect the transferee with the target and hangup
	   all channels to the transferer */	
	ast_debug(4, "Sip transfer:--------------------\n");
	if (transferer->chan1)
		ast_debug(4, "-- Transferer to PBX channel: %s State %s\n", transferer->chan1->name, ast_state2str(transferer->chan1->_state));
	else
		ast_debug(4, "-- No transferer first channel - odd??? \n");
	if (target->chan1)
		ast_debug(4, "-- Transferer to PBX second channel (target): %s State %s\n", target->chan1->name, ast_state2str(target->chan1->_state));
	else
		ast_debug(4, "-- No target first channel ---\n");
	if (transferer->chan2)
		ast_debug(4, "-- Bridged call to transferee: %s State %s\n", transferer->chan2->name, ast_state2str(transferer->chan2->_state));
	else
		ast_debug(4, "-- No bridged call to transferee\n");
	if (target->chan2)
		ast_debug(4, "-- Bridged call to transfer target: %s State %s\n", target->chan2 ? target->chan2->name : "<none>", target->chan2 ? ast_state2str(target->chan2->_state) : "(none)");
	else
		ast_debug(4, "-- No target second channel ---\n");
	ast_debug(4, "-- END Sip transfer:--------------------\n");
	if (transferer->chan2) { /* We have a bridge on the transferer's channel */
		peera = transferer->chan1;	/* Transferer - PBX -> transferee channel * the one we hangup */
		peerb = target->chan1;		/* Transferer - PBX -> target channel - This will get lost in masq */
		peerc = transferer->chan2;	/* Asterisk to Transferee */
		peerd = target->chan2;		/* Asterisk to Target */
		ast_debug(3, "SIP transfer: Four channels to handle\n");
	} else if (target->chan2) {	/* Transferer has no bridge (IVR), but transferee */
		peera = target->chan1;		/* Transferer to PBX -> target channel */
		peerb = transferer->chan1;	/* Transferer to IVR*/
		peerc = target->chan2;		/* Asterisk to Target */
		peerd = transferer->chan2;	/* Nothing */
		ast_debug(3, "SIP transfer: Three channels to handle\n");
	}

	if (peera && peerb && peerc && (peerb != peerc)) {
		ast_quiet_chan(peera);		/* Stop generators */
		ast_quiet_chan(peerb);	
		ast_quiet_chan(peerc);
		if (peerd)
			ast_quiet_chan(peerd);

		ast_debug(4, "SIP transfer: trying to masquerade %s into %s\n", peerc->name, peerb->name);
		if (ast_channel_masquerade(peerb, peerc)) {
			ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
			res = -1;
		} else
			ast_debug(4, "SIP transfer: Succeeded to masquerade channels.\n");
		return res;
	} else {
		ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
		if (transferer->chan1)
			ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
		if (target->chan1)
			ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
		return -1;
	}
	return 0;
}

/*! \brief Get tag from packet 
 *
 * \return Returns the pointer to the provided tag buffer,
 *         or NULL if the tag was not found.
 */
static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
{
	const char *thetag;

	if (!tagbuf)
		return NULL;
	tagbuf[0] = '\0'; 	/* reset the buffer */
	thetag = get_header(req, header);
	thetag = strcasestr(thetag, ";tag=");
	if (thetag) {
		thetag += 5;
		ast_copy_string(tagbuf, thetag, tagbufsize);
		return strsep(&tagbuf, ";");
	}
	return NULL;
}

/*! \brief Handle incoming notifications */
static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
{
	/* This is mostly a skeleton for future improvements */
	/* Mostly created to return proper answers on notifications on outbound REFER's */
	int res = 0;
	const char *event = get_header(req, "Event");
	char *eventid = NULL;
	char *sep;

	if( (sep = strchr(event, ';')) ) {	/* XXX bug here - overwriting string ? */
		*sep++ = '\0';
		eventid = sep;
	}
	
	if (sipdebug)
		ast_debug(2, "Got NOTIFY Event: %s\n", event);

	if (strcmp(event, "refer")) {
		/* We don't understand this event. */
		/* Here's room to implement incoming voicemail notifications :-) */
		transmit_response(p, "489 Bad event", req);
		res = -1;
	} else {
		/* Save nesting depth for now, since there might be other events we will
			support in the future */

		/* Handle REFER notifications */

		char buf[1024];
		char *cmd, *code;
		int respcode;
		int success = TRUE;

		/* EventID for each transfer... EventID is basically the REFER cseq 

		 We are getting notifications on a call that we transfered
		 We should hangup when we are getting a 200 OK in a sipfrag
		 Check if we have an owner of this event */
		
		/* Check the content type */
		if (strncasecmp(get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
			/* We need a sipfrag */
			transmit_response(p, "400 Bad request", req);
			sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
			return -1;
		}

		/* Get the text of the attachment */
		if (get_msg_text(buf, sizeof(buf), req)) {
			ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
			transmit_response(p, "400 Bad request", req);
			sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
			return -1;
		}

		/*
		From the RFC...
		A minimal, but complete, implementation can respond with a single
		NOTIFY containing either the body:
			SIP/2.0 100 Trying
		
		if the subscription is pending, the body:
			SIP/2.0 200 OK
		if the reference was successful, the body:
			SIP/2.0 503 Service Unavailable
		if the reference failed, or the body:
			SIP/2.0 603 Declined

		if the REFER request was accepted before approval to follow the
		reference could be obtained and that approval was subsequently denied
		(see Section 2.4.7).
		
		If there are several REFERs in the same dialog, we need to
		match the ID of the event header...
		*/
		ast_debug(3, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
		cmd = ast_skip_blanks(buf);
		code = cmd;
		/* We are at SIP/2.0 */
		while(*code && (*code > 32)) {	/* Search white space */
			code++;
		}
		*code++ = '\0';
		code = ast_skip_blanks(code);
		sep = code;
		sep++;
		while(*sep && (*sep > 32)) {	/* Search white space */
			sep++;
		}
		*sep++ = '\0';			/* Response string */
		respcode = atoi(code);
		switch (respcode) {
		case 100:	/* Trying: */
		case 101:	/* dialog establishment */
			/* Don't do anything yet */
			break;
		case 183:	/* Ringing: */
			/* Don't do anything yet */
			break;
		case 200:	/* OK: The new call is up, hangup this call */
			/* Hangup the call that we are replacing */
			break;
		case 301: /* Moved permenantly */
		case 302: /* Moved temporarily */
			/* Do we get the header in the packet in this case? */
			success = FALSE;
			break;
		case 503:	/* Service Unavailable: The new call failed */
				/* Cancel transfer, continue the call */
			success = FALSE;
			break;
		case 603:	/* Declined: Not accepted */
				/* Cancel transfer, continue the current call */
			success = FALSE;
			break;
		}
		if (!success) {
			ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
		}
		
		/* Confirm that we received this packet */
		transmit_response(p, "200 OK", req);
	};

	if (!p->lastinvite)
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);

	return res;
}

/*! \brief Handle incoming OPTIONS request 
	An OPTIONS request should be answered like an INVITE from the same UA, including SDP
*/
static int handle_request_options(struct sip_pvt *p, struct sip_request *req)
{
	int res;

	/*! XXX get_destination assumes we're already authenticated. This means that a request from
		a known device (peer/user) will end up in the wrong context if this is out-of-dialog.
		However, we want to handle OPTIONS as light as possible, so we might want to have
		a configuration option whether we care or not. Some devices use this for testing
		capabilities, which means that we need to match device to answer with proper 
		capabilities (including SDP).
		\todo Fix handle_request_options device handling with optional authentication
			(this needs to be fixed in 1.4 as well)
	*/

	if (p->lastinvite) {
		/* if this is a request in an active dialog, just confirm that the dialog exists. */
		transmit_response_with_allow(p, "200 OK", req, 0);
		return 0;
	}

	res = get_destination(p, req);
	build_contact(p);

	if (ast_strlen_zero(p->context))
		ast_string_field_set(p, context, default_context);

	if (ast_shutting_down())
		transmit_response_with_allow(p, "503 Unavailable", req, 0);
	else if (res < 0)
		transmit_response_with_allow(p, "404 Not Found", req, 0);
	else 
		transmit_response_with_allow(p, "200 OK", req, 0);

	/* Destroy if this OPTIONS was the opening request, but not if
	   it's in the middle of a normal call flow. */
	sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);

	return res;
}

/*! \brief Handle the transfer part of INVITE with a replaces: header, 
    meaning a target pickup or an attended transfer.
    Used only once.
	XXX 'ignore' is unused.

	\note this function is called by handle_request_invite(). Four locks
	held at the beginning of this function, p, p->owner, p->refer->refer_call->owner...
	only p's lock should remain at the end of this function.  p's lock is held by sipsock_read()
 */
static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *nounlock)
{
	int earlyreplace = 0;
	int oneleggedreplace = 0;		/* Call with no bridge, propably IVR or voice message */
	struct ast_channel *c = p->owner;	/* Our incoming call */
	struct ast_channel *replacecall = p->refer->refer_call->owner;	/* The channel we're about to take over */
	struct ast_channel *targetcall;		/* The bridge to the take-over target */

	struct ast_channel *test;

	/* Check if we're in ring state */
	if (replacecall->_state == AST_STATE_RING)
		earlyreplace = 1;

	/* Check if we have a bridge */
	if (!(targetcall = ast_bridged_channel(replacecall))) {
		/* We have no bridge */
		if (!earlyreplace) {
			ast_debug(2, "	Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall->name);
			oneleggedreplace = 1;
		}
	} 
	if (targetcall && targetcall->_state == AST_STATE_RINGING)
		ast_debug(4, "SIP transfer: Target channel is in ringing state\n");

	if (targetcall) 
		ast_debug(4, "SIP transfer: Invite Replace incoming channel should bridge to channel %s while hanging up channel %s\n", targetcall->name, replacecall->name); 
	else
		ast_debug(4, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall->name); 

	if (req->ignore) {
		ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
		/* We should answer something here. If we are here, the
			call we are replacing exists, so an accepted 
			can't harm */
		transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE);
		/* Do something more clever here */
		if (c) {
			*nounlock = 1;
			ast_channel_unlock(c);
		}
		ast_channel_unlock(replacecall);
		sip_pvt_unlock(p->refer->refer_call);
		return 1;
	} 
	if (!c) {
		/* What to do if no channel ??? */
		ast_log(LOG_ERROR, "Unable to create new channel.  Invite/replace failed.\n");
		transmit_response_reliable(p, "503 Service Unavailable", req);
		append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
		ast_channel_unlock(replacecall);
		sip_pvt_unlock(p->refer->refer_call);
		return 1;
	}
	append_history(p, "Xfer", "INVITE/Replace received");
	/* We have three channels to play with
		channel c: New incoming call
		targetcall: Call from PBX to target
		p->refer->refer_call: SIP pvt dialog from transferer to pbx.
		replacecall: The owner of the previous
		We need to masq C into refer_call to connect to 
		targetcall;
		If we are talking to internal audio stream, target call is null.
	*/

	/* Fake call progress */
	transmit_response(p, "100 Trying", req);
	ast_setstate(c, AST_STATE_RING);

	/* Masquerade the new call into the referred call to connect to target call 
	   Targetcall is not touched by the masq */

	/* Answer the incoming call and set channel to UP state */
	transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE);
		
	ast_setstate(c, AST_STATE_UP);
	
	/* Stop music on hold and other generators */
	ast_quiet_chan(replacecall);
	ast_quiet_chan(targetcall);
	ast_debug(4, "Invite/Replaces: preparing to masquerade %s into %s\n", c->name, replacecall->name);

	/* Make sure that the masq does not free our PVT for the old call */
	if (! earlyreplace && ! oneleggedreplace )
		ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER);	/* Delay hangup */

	/* Prepare the masquerade - if this does not happen, we will be gone */
	if(ast_channel_masquerade(replacecall, c))
		ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
	else
		ast_debug(4, "Invite/Replaces: Going to masquerade %s into %s\n", c->name, replacecall->name);

	/* C should now be in place of replacecall */
	if (ast_do_masquerade(replacecall)) {
		ast_log(LOG_WARNING, "Failed to perform masquerade with INVITE replaces\n");
	}

	if (earlyreplace || oneleggedreplace ) {
		c->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
	}

	ast_setstate(c, AST_STATE_DOWN);
	ast_debug(4, "After transfer:----------------------------\n");
	ast_debug(4, " -- C:        %s State %s\n", c->name, ast_state2str(c->_state));
	if (replacecall)
		ast_debug(4, " -- replacecall:        %s State %s\n", replacecall->name, ast_state2str(replacecall->_state));
	if (p->owner) {
		ast_debug(4, " -- P->owner: %s State %s\n", p->owner->name, ast_state2str(p->owner->_state));
		test = ast_bridged_channel(p->owner);
		if (test)
			ast_debug(4, " -- Call bridged to P->owner: %s State %s\n", test->name, ast_state2str(test->_state));
		else
			ast_debug(4, " -- No call bridged to C->owner \n");
	} else 
		ast_debug(4, " -- No channel yet \n");
	ast_debug(4, "End After transfer:----------------------------\n");

	/* unlock sip pvt and owner so hangup can do its thing */
	ast_channel_unlock(replacecall);
	ast_channel_unlock(c);
	sip_pvt_unlock(p->refer->refer_call);
	sip_pvt_unlock(p);
	*nounlock = 1;

	/* The call should be down with no ast_channel, so hang it up */
	c->tech_pvt = NULL;
	ast_hangup(c);
	sip_pvt_lock(p); /* lock PVT structure again after hangup */

	return 0;
}

/*! \brief helper routine for sip_uri_cmp
 *
 * This takes the parameters from two SIP URIs and determines
 * if the URIs match. The rules for parameters *suck*. Here's a breakdown
 * 1. If a parameter appears in both URIs, then they must have the same value
 *    in order for the URIs to match
 * 2. If one URI has a user, maddr, ttl, or method parameter, then the other
 *    URI must also have that parameter and must have the same value
 *    in order for the URIs to match
 * 3. All other headers appearing in only one URI are not considered when
 *    determining if URIs match
 *
 * \param input1 Parameters from URI 1
 * \param input2 Parameters from URI 2
 * \return Return 0 if the URIs' parameters match, 1 if they do not
 */
static int sip_uri_params_cmp(const char *input1, const char *input2) 
{
	char *params1 = NULL;
	char *params2 = NULL;
	char *pos1;
	char *pos2;
	int zerolength1 = 0;
	int zerolength2 = 0;
	int maddrmatch = 0;
	int ttlmatch = 0;
	int usermatch = 0;
	int methodmatch = 0;

	if (ast_strlen_zero(input1)) {
		zerolength1 = 1;
	} else {
		params1 = ast_strdupa(input1);
	}
	if (ast_strlen_zero(input2)) {
		zerolength2 = 1;
	} else {
		params2 = ast_strdupa(input2);
	}

	/*Quick optimization. If both params are zero-length, then
	 * they match
	 */
	if (zerolength1 && zerolength2) {
		return 0;
	}

	pos1 = params1;
	while (!ast_strlen_zero(pos1)) {
		char *name1 = pos1;
		char *value1 = strchr(pos1, '=');
		char *semicolon1 = strchr(pos1, ';');
		int matched = 0;
		if (semicolon1) {
			*semicolon1++ = '\0';
		}
		if (!value1) {
			goto fail;
		}
		*value1++ = '\0';
		/* Checkpoint reached. We have the name and value parsed for param1 
		 * We have to duplicate params2 each time through the second loop
		 * or else we can't search and replace the semicolons with \0 each
		 * time
		 */
		pos2 = ast_strdupa(params2);
		while (!ast_strlen_zero(pos2)) {
			char *name2 = pos2;
			char *value2 = strchr(pos2, '=');
			char *semicolon2 = strchr(pos2, ';');
			if (semicolon2) {
				*semicolon2++ = '\0';
			}
			if (!value2) {
				goto fail;
			}
			*value2++ = '\0';
			if (!strcasecmp(name1, name2)) {
				if (strcasecmp(value1, value2)) {
					goto fail;
				} else {
					matched = 1;
					break;
				}
			}
			pos2 = semicolon2;
		}
		/* Need to see if the parameter we're looking at is one of the 'must-match' parameters */
		if (!strcasecmp(name1, "maddr")) {
			if (matched) {
				maddrmatch = 1;
			} else {
				goto fail;
			}
		} else if (!strcasecmp(name1, "ttl")) {
			if (matched) {
				ttlmatch = 1;
			} else {
				goto fail;
			}
		} else if (!strcasecmp(name1, "user")) {
			if (matched) {
				usermatch = 1;
			} else {
				goto fail;
			}
		} else if (!strcasecmp(name1, "method")) {
			if (matched) {
				methodmatch = 1;
			} else {
				goto fail;
			}
		}
		pos1 = semicolon1;
	}

	/* We've made it out of that horrible O(m*n) construct and there are no
	 * failures yet. We're not done yet, though, because params2 could have
	 * an maddr, ttl, user, or method header and params1 did not.
	 */
	pos2 = params2;
	while (!ast_strlen_zero(pos2)) {
		char *name2 = pos2;
		char *value2 = strchr(pos2, '=');
		char *semicolon2 = strchr(pos2, ';');
		if (semicolon2) {
			*semicolon2++ = '\0';
		}
		if (!value2) {
			goto fail;
		}
		*value2++ = '\0';
		if ((!strcasecmp(name2, "maddr") && !maddrmatch) ||
				(!strcasecmp(name2, "ttl") && !ttlmatch) ||
				(!strcasecmp(name2, "user") && !usermatch) ||
				(!strcasecmp(name2, "method") && !methodmatch)) {
			goto fail;
		}
	}
	return 0;

fail:
	return 1;
}

/*! \brief helper routine for sip_uri_cmp
 *
 * This takes the "headers" from two SIP URIs and determines
 * if the URIs match. The rules for headers is simple. If a header
 * appears in one URI, then it must also appear in the other URI. The
 * order in which the headers appear does not matter.
 *
 * \param input1 Headers from URI 1
 * \param input2 Headers from URI 2
 * \return Return 0 if the URIs' headers match, 1 if they do not
 */
static int sip_uri_headers_cmp(const char *input1, const char *input2)
{
	char *headers1 = NULL;
	char *headers2 = NULL;
	int zerolength1 = 0;
	int zerolength2 = 0;
	int different = 0;
	char *header1;

	if (ast_strlen_zero(input1)) {
		zerolength1 = 1;
	} else {
		headers1 = ast_strdupa(input1);
	}
	
	if (ast_strlen_zero(input2)) {
		zerolength2 = 1;
	} else {
		headers2 = ast_strdupa(input2);
	}

	if ((zerolength1 && !zerolength2) ||
			(zerolength2 && !zerolength1))
		return 1;

	if (zerolength1 && zerolength2)
		return 0;

	/* At this point, we can definitively state that both inputs are
	 * not zero-length. First, one more optimization. If the length
	 * of the headers is not equal, then we definitely have no match
	 */
	if (strlen(headers1) != strlen(headers2)) {
		return 1;
	}

	for (header1 = strsep(&headers1, "&"); header1; header1 = strsep(&headers1, "&")) {
		if (!strcasestr(headers2, header1)) {
			different = 1;
			break;
		}
	}

	return different;
}

static int sip_uri_cmp(const char *input1, const char *input2)
{
	char *uri1 = ast_strdupa(input1);
	char *uri2 = ast_strdupa(input2);
	char *host1;
	char *host2;
	char *params1;
	char *params2;
	char *headers1;
	char *headers2;

	/* Strip off "sip:" from the URI. We know this is present
	 * because it was checked back in parse_request()
	 */
	strsep(&uri1, ":");
	strsep(&uri2, ":");

	if ((host1 = strchr(uri1, '@'))) {
		*host1++ = '\0';
	}
	if ((host2 = strchr(uri2, '@'))) {
		*host2++ = '\0';
	}

	/* Check for mismatched username and passwords. This is the
	 * only case-sensitive comparison of a SIP URI
	 */
	if ((host1 && !host2) ||
			(host2 && !host1) ||
			(host1 && host2 && strcmp(uri1, uri2))) {
		return 1;
	}

	if (!host1)
		host1 = uri1;
	if (!host2)
		host2 = uri2;

	/* Strip off the parameters and headers so we can compare
	 * host and port
	 */

	if ((params1 = strchr(host1, ';'))) {
		*params1++ = '\0';
	}
	if ((params2 = strchr(host2, ';'))) {
		*params2++ = '\0';
	}

	/* Headers come after parameters, but there may be headers without
	 * parameters, thus the S_OR
	 */
	if ((headers1 = strchr(S_OR(params1, host1), '?'))) {
		*headers1++ = '\0';
	}
	if ((headers2 = strchr(S_OR(params2, host2), '?'))) {
		*headers2++ = '\0';
	}

	/* Now the host/port are properly isolated. We can get by with a string comparison
	 * because the SIP URI checking rules have some interesting exceptions that make
	 * this possible. I will note 2 in particular
	 * 1. hostnames which resolve to the same IP address as well as a hostname and its
	 *    IP address are not considered a match with SIP URI's.
	 * 2. If one URI specifies a port and the other does not, then the URIs do not match.
	 *    This includes if one URI explicitly contains port 5060 and the other implies it
	 *    by not having a port specified.
	 */

	if (strcasecmp(host1, host2)) {
		return 1;
	}

	/* Headers have easier rules to follow, so do those first */
	if (sip_uri_headers_cmp(headers1, headers2)) {
		return 1;
	}

	/* And now the parameters. Ugh */
	return sip_uri_params_cmp(params1, params2);
}

/*! \brief Called to deny a T38 reinvite if the core does not respond to our request */
static int sip_t38_abort(const void *data)
{
	struct sip_pvt *p = (struct sip_pvt *) data;

	change_t38_state(p, T38_DISABLED);
	transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
	p->t38id = -1;
	return 0;
}

/*! \brief Handle incoming INVITE request
\note 	If the INVITE has a Replaces header, it is part of an
 *	attended transfer. If so, we do not go through the dial
 *	plan but tries to find the active call and masquerade
 *	into it 
 */
static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *recount, char *e, int *nounlock)
{
	int res = 1;
	int gotdest;
	const char *p_replaces;
	char *replace_id = NULL;
	int refer_locked = 0;
	const char *required;
	unsigned int required_profile = 0;
	struct ast_channel *c = NULL;		/* New channel */
	int reinvite = 0;
	int rtn;

	const char *p_uac_se_hdr;       /* UAC's Session-Expires header string                      */
	const char *p_uac_min_se;       /* UAC's requested Min-SE interval (char string)            */
	int uac_max_se = -1;            /* UAC's Session-Expires in integer format                  */
	int uac_min_se = -1;            /* UAC's Min-SE in integer format                           */
	int st_active = FALSE;          /* Session-Timer on/off boolean                             */
	int st_interval = 0;            /* Session-Timer negotiated refresh interval                */
	enum st_refresher st_ref;       /* Session-Timer session refresher                          */
	int dlg_min_se = -1;
	st_ref = SESSION_TIMER_REFRESHER_AUTO;

	/* Find out what they support */
	if (!p->sipoptions) {
		const char *supported = get_header(req, "Supported");
		if (!ast_strlen_zero(supported))
			parse_sip_options(p, supported);
	}

	/* Find out what they require */
	required = get_header(req, "Require");
	if (!ast_strlen_zero(required)) {
		required_profile = parse_sip_options(NULL, required);
		if (required_profile && !(required_profile & (SIP_OPT_REPLACES | SIP_OPT_TIMER))) {
			/* At this point we only support REPLACES and Session-Timer */
			transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, required);
			ast_log(LOG_WARNING, "Received SIP INVITE with unsupported required extension: %s\n", required);
			p->invitestate = INV_COMPLETED;
			if (!p->lastinvite)
				sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
			res = -1;
			goto request_invite_cleanup;
		}
	}

	/* The option tags may be present in Supported: or Require: headers.
	Include the Require: option tags for further processing as well */
	p->sipoptions |= required_profile;
	p->reqsipoptions = required_profile;

	/* Check if this is a loop */
	if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && p->owner && (p->invitestate != INV_TERMINATED && p->invitestate != INV_CONFIRMED)) {
		/* This is a call to ourself.  Send ourselves an error code and stop
	   	processing immediately, as SIP really has no good mechanism for
	   	being able to call yourself */
		/* If pedantic is on, we need to check the tags. If they're different, this is
	   	in fact a forked call through a SIP proxy somewhere. */
		int different;
		if (pedanticsipchecking)
			different = sip_uri_cmp(p->initreq.rlPart2, req->rlPart2);
		else
			different = strcmp(p->initreq.rlPart2, req->rlPart2);
		if (!different) {
			transmit_response(p, "482 Loop Detected", req);
			p->invitestate = INV_COMPLETED;
			sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
			res = 0;
			goto request_invite_cleanup;
		} else {
			/* This is a spiral. What we need to do is to just change the outgoing INVITE
			 * so that it now routes to the new Request URI. Since we created the INVITE ourselves
			 * that should be all we need to do.
			 */
			char *uri = ast_strdupa(req->rlPart2);
			char *at = strchr(uri, '@');
			char *peerorhost;
			ast_debug(3, "Potential spiral detected. Original RURI was %s, new RURI is %s\n", p->initreq.rlPart2, req->rlPart2);
			transmit_response(p, "100 Trying", req);
			if (at) {
				*at = '\0';
			}
			/* Parse out "sip:" */
			if ((peerorhost = strchr(uri, ':'))) {
				*peerorhost++ = '\0';
			}
			ast_string_field_set(p, theirtag, NULL);
			/* Treat this as if there were a call forward instead...
			 */
			ast_string_field_set(p->owner, call_forward, peerorhost);
			ast_queue_control(p->owner, AST_CONTROL_BUSY);
			res = 0;
			goto request_invite_cleanup;
		}
	}

	if (!req->ignore && p->pendinginvite) {
		if (!ast_test_flag(&p->flags[0], SIP_OUTGOING) && (p->invitestate == INV_COMPLETED || p->invitestate == INV_TERMINATED)) {
			/* What do these circumstances mean? We have received an INVITE for an "incoming" dialog for which we
			 * have sent a final response. We have not yet received an ACK, though (which is why p->pendinginvite is non-zero).
			 * We also know that the INVITE is not a retransmission, because otherwise the "ignore" flag would be set.
			 * This means that either we are receiving a reinvite for a terminated dialog, or we are receiving an INVITE with
			 * credentials based on one we challenged earlier.
			 *
			 * The action to take in either case is to treat the INVITE as though it contains an implicit ACK for the previous
			 * transaction. Calling __sip_ack will take care of this by clearing the p->pendinginvite and removing the response
			 * from the previous transaction from the list of outstanding packets.
			 */
			__sip_ack(p, p->pendinginvite, 1, 0);
		} else {
			/* We already have a pending invite. Sorry. You are on hold. */
			p->glareinvite = seqno;
			if (p->rtp && find_sdp(req)) {
				struct sockaddr_in sin;
				if (get_ip_and_port_from_sdp(req, SDP_AUDIO, &sin)) {
					ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Audio may not work properly on this call.\n");
				} else {
					ast_rtp_set_alt_peer(p->rtp, &sin);
				}
				if (p->vrtp) {
					if (get_ip_and_port_from_sdp(req, SDP_VIDEO, &sin)) {
						ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Video may not work properly on this call.\n");
					} else {
						ast_rtp_set_alt_peer(p->vrtp, &sin);
					}
				}
			}
			transmit_response_reliable(p, "491 Request Pending", req);
			ast_debug(1, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
			/* Don't destroy dialog here */
			res = 0;
			goto request_invite_cleanup;
		}
	}

	p_replaces = get_header(req, "Replaces");
	if (!ast_strlen_zero(p_replaces)) {
		/* We have a replaces header */
		char *ptr;
		char *fromtag = NULL;
		char *totag = NULL;
		char *start, *to;
		int error = 0;

		if (p->owner) {
			ast_debug(3, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
			transmit_response_reliable(p, "400 Bad request", req);	/* The best way to not not accept the transfer */
			/* Do not destroy existing call */
			res = -1;
			goto request_invite_cleanup;
		}

		if (sipdebug)
			ast_debug(3, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
		/* Create a buffer we can manipulate */
		replace_id = ast_strdupa(p_replaces);
		ast_uri_decode(replace_id);

		if (!p->refer && !sip_refer_allocate(p)) {
			transmit_response_reliable(p, "500 Server Internal Error", req);
			append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
			sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
			p->invitestate = INV_COMPLETED;
			res = -1;
			goto request_invite_cleanup;
		}

		/*  Todo: (When we find phones that support this)
			if the replaces header contains ";early-only"
			we can only replace the call in early
			stage, not after it's up.

			If it's not in early mode, 486 Busy.
		*/
		
		/* Skip leading whitespace */
		replace_id = ast_skip_blanks(replace_id);

		start = replace_id;
		while ( (ptr = strsep(&start, ";")) ) {
			ptr = ast_skip_blanks(ptr); /* XXX maybe unnecessary ? */
			if ( (to = strcasestr(ptr, "to-tag=") ) )
				totag = to + 7;	/* skip the keyword */
			else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
				fromtag = to + 9;	/* skip the keyword */
				fromtag = strsep(&fromtag, "&"); /* trim what ? */
			}
		}

		if (sipdebug) 
			ast_debug(4, "Invite/replaces: Will use Replace-Call-ID : %s Fromtag: %s Totag: %s\n", replace_id, fromtag ? fromtag : "<no from tag>", totag ? totag : "<no to tag>");


		/* Try to find call that we are replacing 
			If we have a Replaces  header, we need to cancel that call if we succeed with this call 
		*/
		if ((p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
			ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
			transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
			error = 1;
		} else {
			refer_locked = 1;
		}

		/* At this point, bot the pvt and the owner of the call to be replaced is locked */

		/* The matched call is the call from the transferer to Asterisk .
			We want to bridge the bridged part of the call to the 
			incoming invite, thus taking over the refered call */

		if (p->refer->refer_call == p) {
			ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
			p->refer->refer_call = NULL;
			transmit_response_reliable(p, "400 Bad request", req);	/* The best way to not not accept the transfer */
			error = 1;
		}

		if (!error && !p->refer->refer_call->owner) {
			/* Oops, someting wrong anyway, no owner, no call */
			ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
			/* Check for better return code */
			transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replace)", req);
			error = 1;
		}

		if (!error && p->refer->refer_call->owner->_state != AST_STATE_RINGING && p->refer->refer_call->owner->_state != AST_STATE_RING && p->refer->refer_call->owner->_state != AST_STATE_UP ) {
			ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
			transmit_response_reliable(p, "603 Declined (Replaces)", req);
			error = 1;
		}

		if (error) {	/* Give up this dialog */
			append_history(p, "Xfer", "INVITE/Replace Failed.");
			sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
			sip_pvt_unlock(p);
			if (p->refer->refer_call) {
				sip_pvt_unlock(p->refer->refer_call);
				if (p->refer->refer_call->owner) {
					ast_channel_unlock(p->refer->refer_call->owner);
				}
			}
			refer_locked = 0;
			p->invitestate = INV_COMPLETED;
			res = -1;
			goto request_invite_cleanup;
		}
	}

	/* Check if this is an INVITE that sets up a new dialog or
	   a re-invite in an existing dialog */

	if (!req->ignore) {
		int newcall = (p->initreq.headers ? TRUE : FALSE);

		if (sip_cancel_destroy(p))
			ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
		/* This also counts as a pending invite */
		p->pendinginvite = seqno;
		check_via(p, req);

		copy_request(&p->initreq, req);		/* Save this INVITE as the transaction basis */
		if (sipdebug)
			ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
		if (!p->owner) {	/* Not a re-invite */
			if (debug)
				ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
			if (newcall)
				append_history(p, "Invite", "New call: %s", p->callid);
			parse_ok_contact(p, req);
		} else {	/* Re-invite on existing call */
			ast_clear_flag(&p->flags[0], SIP_OUTGOING);	/* This is now an inbound dialog */
			/* Handle SDP here if we already have an owner */
			if (find_sdp(req)) {
				if (process_sdp(p, req, SDP_T38_INITIATE)) {
					transmit_response_reliable(p, "488 Not acceptable here", req);
					if (!p->lastinvite)
						sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
					res = -1;
					goto request_invite_cleanup;
				}
				ast_queue_control(p->owner, AST_CONTROL_SRCUPDATE);
			} else {
				p->jointcapability = p->capability;
				ast_debug(1, "Hm....  No sdp for the moment\n");
			}
			if (p->do_history) /* This is a response, note what it was for */
				append_history(p, "ReInv", "Re-invite received");
		}
	} else if (debug)
		ast_verbose("Ignoring this INVITE request\n");

	
	if (!p->lastinvite && !req->ignore && !p->owner) {
		/* This is a new invite */
		/* Handle authentication if this is our first invite */
		res = check_user(p, req, SIP_INVITE, e, XMIT_RELIABLE, sin);
		if (res == AUTH_CHALLENGE_SENT) {
			p->invitestate = INV_COMPLETED;		/* Needs to restart in another INVITE transaction */
			res = 0;
			goto request_invite_cleanup;
		}
		if (res < 0) { /* Something failed in authentication */
			if (res == AUTH_FAKE_AUTH) {
				ast_log(LOG_NOTICE, "Sending fake auth rejection for user %s\n", get_header(req, "From"));
				transmit_fake_auth_response(p, SIP_INVITE, req, XMIT_RELIABLE);
			} else {
				ast_log(LOG_NOTICE, "Failed to authenticate user %s\n", get_header(req, "From"));
				transmit_response_reliable(p, "403 Forbidden", req);
			}
			p->invitestate = INV_COMPLETED;	
			sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
			ast_string_field_set(p, theirtag, NULL);
			res = 0;
			goto request_invite_cleanup;
		}

		/* If T38 is needed but not present, then make it magically appear */
		if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && !p->udptl && (p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr))) {
			set_t38_capabilities(p);
		}

		/* We have a succesful authentication, process the SDP portion if there is one */
		if (find_sdp(req)) {
			if (process_sdp(p, req, SDP_T38_INITIATE)) {
				/* Unacceptable codecs */
				transmit_response_reliable(p, "488 Not acceptable here", req);
				p->invitestate = INV_COMPLETED;	
				sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
				ast_debug(1, "No compatible codecs for this SIP call.\n");
				res = -1;
				goto request_invite_cleanup;
			}
		} else {	/* No SDP in invite, call control session */
			p->jointcapability = p->capability;
			ast_debug(2, "No SDP in Invite, third party call control\n");
		}

		/* Queue NULL frame to prod ast_rtp_bridge if appropriate */
		/* This seems redundant ... see !p-owner above */
		if (p->owner)
			ast_queue_frame(p->owner, &ast_null_frame);


		/* Initialize the context if it hasn't been already */
		if (ast_strlen_zero(p->context))
			ast_string_field_set(p, context, default_context);


		/* Check number of concurrent calls -vs- incoming limit HERE */
		ast_debug(1, "Checking SIP call limits for device %s\n", p->username);
		if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
			if (res < 0) {
				ast_log(LOG_NOTICE, "Failed to place call for user %s, too many calls\n", p->username);
				transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
				sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
				p->invitestate = INV_COMPLETED;	
			}
			res = 0;
			goto request_invite_cleanup;
		}
		gotdest = get_destination(p, NULL);	/* Get destination right away */
		get_rdnis(p, NULL);			/* Get redirect information */
		extract_uri(p, req);			/* Get the Contact URI */
		build_contact(p);			/* Build our contact header */

		if (p->rtp) {
			ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
			ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
		}

		if (!replace_id && gotdest) {	/* No matching extension found */
			if (gotdest == 1 && ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP))
				transmit_response_reliable(p, "484 Address Incomplete", req);
			else {
				char *decoded_exten = ast_strdupa(p->exten);
				
				transmit_response_reliable(p, "404 Not Found", req);
				ast_uri_decode(decoded_exten);
				ast_log(LOG_NOTICE, "Call from '%s' to extension"
					" '%s' rejected because extension not found in context '%s'.\n",
					S_OR(p->username, p->peername), decoded_exten, p->context);
			}
			p->invitestate = INV_COMPLETED;	
			update_call_counter(p, DEC_CALL_LIMIT);
			sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
			res = 0;
			goto request_invite_cleanup;
		} else {

			/* If no extension was specified, use the s one */
			/* Basically for calling to IP/Host name only */
			if (ast_strlen_zero(p->exten))
				ast_string_field_set(p, exten, "s");
			/* Initialize our tag */	

			make_our_tag(p->tag, sizeof(p->tag));
			/* First invitation - create the channel */
			c = sip_new(p, AST_STATE_DOWN, S_OR(p->peername, NULL));
			*recount = 1;

			/* Save Record-Route for any later requests we make on this dialogue */
			build_route(p, req, 0);

			if (c) {
				/* Pre-lock the call */
				ast_channel_lock(c);
			}
		}
	} else {
		if (sipdebug) {
			if (!req->ignore)
				ast_debug(2, "Got a SIP re-invite for call %s\n", p->callid);
			else
				ast_debug(2, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
		}
		if (!req->ignore)
			reinvite = 1;
		c = p->owner;
	}

	/* Session-Timers */
	if (p->sipoptions & SIP_OPT_TIMER) {
		/* The UAC has requested session-timers for this session. Negotiate
		the session refresh interval and who will be the refresher */
		ast_debug(2, "Incoming INVITE with 'timer' option enabled\n");

		/* Allocate Session-Timers struct w/in the dialog */
		if (!p->stimer)
			sip_st_alloc(p);

		/* Parse the Session-Expires header */
		p_uac_se_hdr = get_header(req, "Session-Expires");
		if (!ast_strlen_zero(p_uac_se_hdr)) {
			rtn = parse_session_expires(p_uac_se_hdr, &uac_max_se, &st_ref);
			if (rtn != 0) {
				transmit_response_reliable(p, "400 Session-Expires Invalid Syntax", req);
				p->invitestate = INV_COMPLETED;
				if (!p->lastinvite) {
					sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
				}
				res = -1;
				goto request_invite_cleanup;
			}
		}

		/* Parse the Min-SE header */
		p_uac_min_se = get_header(req, "Min-SE");
		if (!ast_strlen_zero(p_uac_min_se)) {
			rtn = parse_minse(p_uac_min_se, &uac_min_se); 
			if (rtn != 0) {
        			transmit_response_reliable(p, "400 Min-SE Invalid Syntax", req);
       	   			p->invitestate = INV_COMPLETED;
       	   			if (!p->lastinvite) {
					sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
				}
				res = -1;
				goto request_invite_cleanup;
			}
		}

		dlg_min_se = st_get_se(p, FALSE);
		switch (st_get_mode(p)) {
		case SESSION_TIMER_MODE_ACCEPT:
		case SESSION_TIMER_MODE_ORIGINATE:
			if (uac_max_se > 0 && uac_max_se < dlg_min_se) {
				transmit_response_with_minse(p, "422 Session Interval Too Small", req, dlg_min_se);
				p->invitestate = INV_COMPLETED;
				if (!p->lastinvite) {
					sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
				}
				res = -1;
				goto request_invite_cleanup;
			}

			p->stimer->st_active_peer_ua = TRUE;
			st_active = TRUE;
			if (st_ref == SESSION_TIMER_REFRESHER_AUTO) {
				st_ref = st_get_refresher(p);
			}

			if (uac_max_se > 0) {
				int dlg_max_se = st_get_se(p, TRUE);
				if (dlg_max_se >= uac_min_se) {
					st_interval = (uac_max_se < dlg_max_se) ? uac_max_se : dlg_max_se;
				} else {
					st_interval = uac_max_se;
				}
			} else {
				/* Set to default max value */
				st_interval = global_max_se;
			}
			break;

		case SESSION_TIMER_MODE_REFUSE:
			if (p->reqsipoptions & SIP_OPT_TIMER) {
				transmit_response_with_unsupported(p, "420 Option Disabled", req, required);
				ast_log(LOG_WARNING, "Received SIP INVITE with supported but disabled option: %s\n", required);
				p->invitestate = INV_COMPLETED;
				if (!p->lastinvite) {
					sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
				}
				res = -1;
				goto request_invite_cleanup;
			}
			break;

		default:
			ast_log(LOG_ERROR, "Internal Error %d at %s:%d\n", st_get_mode(p), __FILE__, __LINE__);
			break;
		}
	} else {
		/* The UAC did not request session-timers.  Asterisk (UAS), will now decide
		(based on session-timer-mode in sip.conf) whether to run session-timers for
		this session or not. */
		switch (st_get_mode(p)) {
		case SESSION_TIMER_MODE_ORIGINATE:
			st_active = TRUE;
			st_interval = st_get_se(p, TRUE);
			st_ref = SESSION_TIMER_REFRESHER_UAS;
			p->stimer->st_active_peer_ua = FALSE;
			break;

		default:
			break;
		}
	}

	if (reinvite == 0) {
		/* Session-Timers: Start session refresh timer based on negotiation/config */
		if (st_active == TRUE) {
			p->stimer->st_active   = TRUE;
			p->stimer->st_interval = st_interval;
			p->stimer->st_ref      = st_ref;
			start_session_timer(p);
		}
	} else {
		if (p->stimer->st_active == TRUE) {
			/* Session-Timers:  A re-invite request sent within a dialog will serve as 
			a refresh request, no matter whether the re-invite was sent for refreshing 
			the session or modifying it.*/
			ast_debug (2, "Restarting session-timers on a refresh - %s\n", p->callid);

			/* The UAC may be adjusting the session-timers mid-session */
			if (st_interval > 0) {
				p->stimer->st_interval = st_interval;
				p->stimer->st_ref      = st_ref;
			}

			restart_session_timer(p);
			if (p->stimer->st_expirys > 0) {
				p->stimer->st_expirys--;
			}
		}
	}

	if (!req->ignore && p)
		p->lastinvite = seqno;

	if (replace_id) { 	/* Attended transfer or call pickup - we're the target */
		/* Go and take over the target call */
		if (sipdebug)
			ast_debug(4, "Sending this call to the invite/replcaes handler %s\n", p->callid);
		res = handle_invite_replaces(p, req, debug, seqno, sin, nounlock);
		refer_locked = 0;
		goto request_invite_cleanup;

	}


	if (c) {	/* We have a call  -either a new call or an old one (RE-INVITE) */
		enum ast_channel_state c_state = c->_state;

		if (c_state != AST_STATE_UP && reinvite &&
			(p->invitestate == INV_TERMINATED || p->invitestate == INV_CONFIRMED)) {
			/* If these conditions are true, and the channel is still in the 'ringing'
			 * state, then this likely means that we have a situation where the initial
			 * INVITE transaction has completed *but* the channel's state has not yet been
			 * changed to UP. The reason this could happen is if the reinvite is received
			 * on the SIP socket prior to an application calling ast_read on this channel
			 * to read the answer frame we earlier queued on it. In this case, the reinvite
			 * is completely legitimate so we need to handle this the same as if the channel 
			 * were already UP. Thus we are purposely falling through to the AST_STATE_UP case.
			 */
			c_state = AST_STATE_UP;
		}

		switch(c_state) {
		case AST_STATE_DOWN:
			ast_debug(2, "%s: New call is still down.... Trying... \n", c->name);
			transmit_provisional_response(p, "100 Trying", req, FALSE);
			p->invitestate = INV_PROCEEDING;
			ast_setstate(c, AST_STATE_RING);
			if (strcmp(p->exten, ast_pickup_ext())) {	/* Call to extension -start pbx on this call */
				enum ast_pbx_result res;

				res = ast_pbx_start(c);

				switch(res) {
				case AST_PBX_FAILED:
					ast_log(LOG_WARNING, "Failed to start PBX :(\n");
					p->invitestate = INV_COMPLETED;
					transmit_response_reliable(p, "503 Unavailable", req);
					break;
				case AST_PBX_CALL_LIMIT:
					ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
					p->invitestate = INV_COMPLETED;
					transmit_response_reliable(p, "480 Temporarily Unavailable", req);
					break;
				case AST_PBX_SUCCESS:
					/* nothing to do */
					break;
				}

				if (res) {

					/* Unlock locks so ast_hangup can do its magic */
					ast_channel_unlock(c);
					sip_pvt_unlock(p);
					ast_hangup(c);
					sip_pvt_lock(p);
					c = NULL;
				}
			} else {	/* Pickup call in call group */
				ast_channel_unlock(c);
				*nounlock = 1;
				if (ast_pickup_call(c)) {
					ast_log(LOG_NOTICE, "Nothing to pick up for %s\n", p->callid);
					transmit_response_reliable(p, "503 Unavailable", req);
					sip_alreadygone(p);
					/* Unlock locks so ast_hangup can do its magic */
					sip_pvt_unlock(p);
					c->hangupcause = AST_CAUSE_CALL_REJECTED;
				} else {
					sip_pvt_unlock(p);
					ast_setstate(c, AST_STATE_DOWN);
					c->hangupcause = AST_CAUSE_NORMAL_CLEARING;
				}
				p->invitestate = INV_COMPLETED;
				ast_hangup(c);
				sip_pvt_lock(p);
				c = NULL;
			}
			break;
		case AST_STATE_RING:
			transmit_provisional_response(p, "100 Trying", req, 0);
			p->invitestate = INV_PROCEEDING;
			break;
		case AST_STATE_RINGING:
			transmit_provisional_response(p, "180 Ringing", req, 0);
			p->invitestate = INV_PROCEEDING;
			break;
		case AST_STATE_UP:
			ast_debug(2, "%s: This call is UP.... \n", c->name);

			transmit_response(p, "100 Trying", req);

			if (p->t38.state == T38_PEER_REINVITE) {
				p->t38id = ast_sched_add(sched, 5000, sip_t38_abort, p);
			} else if (p->t38.state == T38_ENABLED) {
				ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
				transmit_response_with_t38_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ?  XMIT_UNRELIABLE : XMIT_CRITICAL)));
			} else if (p->t38.state == T38_DISABLED) {
				/* If this is not a re-invite or something to ignore - it's critical */
				ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
				transmit_response_with_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ?  XMIT_UNRELIABLE : XMIT_CRITICAL)), p->session_modify == TRUE ? FALSE:TRUE); 
			}

			p->invitestate = INV_TERMINATED;
			break;
		default:
			ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
			transmit_response(p, "100 Trying", req);
			break;
		}
	} else {
		if (p && (p->autokillid == -1)) {
			const char *msg;

			if (!p->jointcapability)
				msg = "488 Not Acceptable Here (codec error)";
			else {
				ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
				msg = "503 Unavailable";
			}
			transmit_response_reliable(p, msg, req);
			p->invitestate = INV_COMPLETED;
			sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
		}
	}

request_invite_cleanup:

	if (refer_locked && p->refer && p->refer->refer_call) {
		sip_pvt_unlock(p->refer->refer_call);
		if (p->refer->refer_call->owner) {
			ast_channel_unlock(p->refer->refer_call->owner);
		}
	}

	return res;
}

/*! \brief  Find all call legs and bridge transferee with target 
 *	called from handle_request_refer */
static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno)
{
	struct sip_dual target;		/* Chan 1: Call from tranferer to Asterisk */
					/* Chan 2: Call from Asterisk to target */
	int res = 0;
	struct sip_pvt *targetcall_pvt;

	/* Check if the call ID of the replaces header does exist locally */
	if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag, 
		transferer->refer->replaces_callid_fromtag))) {
		if (transferer->refer->localtransfer) {
			/* We did not find the refered call. Sorry, can't accept then */
			transmit_response(transferer, "202 Accepted", req);
			/* Let's fake a response from someone else in order
		   	to follow the standard */
			transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
			append_history(transferer, "Xfer", "Refer failed");
			ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);	
			transferer->refer->status = REFER_FAILED;
			return -1;
		}
		/* Fall through for remote transfers that we did not find locally */
		ast_debug(3, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
		return 0;
	}

	/* Ok, we can accept this transfer */
	transmit_response(transferer, "202 Accepted", req);
	append_history(transferer, "Xfer", "Refer accepted");
	if (!targetcall_pvt->owner) {	/* No active channel */
		ast_debug(4, "SIP attended transfer: Error: No owner of target call\n");
		/* Cancel transfer */
		transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
		append_history(transferer, "Xfer", "Refer failed");
		ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
		transferer->refer->status = REFER_FAILED;
		sip_pvt_unlock(targetcall_pvt);
		return -1;
	}

	/* We have a channel, find the bridge */
	target.chan1 = targetcall_pvt->owner;				/* Transferer to Asterisk */
	target.chan2 = ast_bridged_channel(targetcall_pvt->owner);	/* Asterisk to target */

	if (!target.chan2 || !(target.chan2->_state == AST_STATE_UP || target.chan2->_state == AST_STATE_RINGING) ) {
		/* Wrong state of new channel */
		if (target.chan2) 
			ast_debug(4, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target.chan2->_state));
		else if (target.chan1->_state != AST_STATE_RING)
			ast_debug(4, "SIP attended transfer: Error: No target channel\n");
		else
			ast_debug(4, "SIP attended transfer: Attempting transfer in ringing state\n");
	}

	/* Transfer */
	if (sipdebug) {
		if (current->chan2)	/* We have two bridges */
			ast_debug(4, "SIP attended transfer: trying to bridge %s and %s\n", target.chan1->name, current->chan2->name);
		else			/* One bridge, propably transfer of IVR/voicemail etc */
			ast_debug(4, "SIP attended transfer: trying to make %s take over (masq) %s\n", target.chan1->name, current->chan1->name);
	}

	ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);	/* Delay hangup */

	/* Perform the transfer */
	manager_event(EVENT_FLAG_CALL, "Transfer", "TransferMethod: SIP\r\nTransferType: Attended\r\nChannel: %s\r\nUniqueid: %s\r\nSIP-Callid: %s\r\nTargetChannel: %s\r\nTargetUniqueid: %s\r\n",
		transferer->owner->name,
		transferer->owner->uniqueid,
		transferer->callid,
		target.chan1->name,
		target.chan1->uniqueid);
	res = attempt_transfer(current, &target);
	sip_pvt_unlock(targetcall_pvt);
	if (res) {
		/* Failed transfer */
		transmit_notify_with_sipfrag(transferer, seqno, "486 Busy Here", TRUE);
		append_history(transferer, "Xfer", "Refer failed");
		if (targetcall_pvt->owner)
			ast_channel_unlock(targetcall_pvt->owner);
		ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
	} else {
		/* Transfer succeeded! */

		/* Tell transferer that we're done. */
		transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
		append_history(transferer, "Xfer", "Refer succeeded");
		transferer->refer->status = REFER_200OK;
		if (targetcall_pvt->owner) {
			ast_debug(1, "SIP attended transfer: Unlocking channel %s\n", targetcall_pvt->owner->name);
			ast_channel_unlock(targetcall_pvt->owner);
		}
	}
	return 1;
}


/*! \brief Handle incoming REFER request */
/*! \page SIP_REFER SIP transfer Support (REFER)

	REFER is used for call transfer in SIP. We get a REFER
	to place a new call with an INVITE somwhere and then
	keep the transferor up-to-date of the transfer. If the
	transfer fails, get back on line with the orginal call. 

	- REFER can be sent outside or inside of a dialog.
	  Asterisk only accepts REFER inside of a dialog.

	- If we get a replaces header, it is an attended transfer

	\par Blind transfers
	The transferor provides the transferee
	with the transfer targets contact. The signalling between
	transferer or transferee should not be cancelled, so the
	call is recoverable if the transfer target can not be reached 
	by the transferee.

	In this case, Asterisk receives a TRANSFER from
	the transferor, thus is the transferee. We should
	try to set up a call to the contact provided
	and if that fails, re-connect the current session.
	If the new call is set up, we issue a hangup.
	In this scenario, we are following section 5.2
	in the SIP CC Transfer draft. (Transfer without
	a GRUU)

	\par Transfer with consultation hold
	In this case, the transferor
	talks to the transfer target before the transfer takes place.
	This is implemented with SIP hold and transfer.
	Note: The invite From: string could indicate a transfer.
	(Section 6. Transfer with consultation hold)
	The transferor places the transferee on hold, starts a call
	with the transfer target to alert them to the impending
	transfer, terminates the connection with the target, then
	proceeds with the transfer (as in Blind transfer above)

	\par Attended transfer
	The transferor places the transferee
	on hold, calls the transfer target to alert them,
	places the target on hold, then proceeds with the transfer
	using a Replaces header field in the Refer-to header. This
	will force the transfee to send an Invite to the target,
	with a replaces header that instructs the target to
	hangup the call between the transferor and the target.
	In this case, the Refer/to: uses the AOR address. (The same
	URI that the transferee used to establish the session with
	the transfer target (To: ). The Require: replaces header should
	be in the INVITE to avoid the wrong UA in a forked SIP proxy
	scenario to answer and have no call to replace with.

	The referred-by header is *NOT* required, but if we get it,
	can be copied into the INVITE to the transfer target to 
	inform the target about the transferor

	"Any REFER request has to be appropriately authenticated.".
	
	We can't destroy dialogs, since we want the call to continue.
	
	*/
static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock)
{
	struct sip_dual current;	/* Chan1: Call between asterisk and transferer */
					/* Chan2: Call between asterisk and transferee */

	int res = 0;

	if (req->debug)
		ast_verbose("Call %s got a SIP call transfer from %s: (REFER)!\n", p->callid, ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "callee" : "caller");

	if (!p->owner) {
		/* This is a REFER outside of an existing SIP dialog */
		/* We can't handle that, so decline it */
		ast_debug(3, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
		transmit_response(p, "603 Declined (No dialog)", req);
		if (!req->ignore) {
			append_history(p, "Xfer", "Refer failed. Outside of dialog.");
			sip_alreadygone(p);
			p->needdestroy = 1;
		}
		return 0;
	}	


	/* Check if transfer is allowed from this device */
	if (p->allowtransfer == TRANSFER_CLOSED ) {
		/* Transfer not allowed, decline */
		transmit_response(p, "603 Declined (policy)", req);
		append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
		/* Do not destroy SIP session */
		return 0;
	}

	if (!req->ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
		/* Already have a pending REFER */	
		transmit_response(p, "491 Request pending", req);
		append_history(p, "Xfer", "Refer failed. Request pending.");
		return 0;
	}

	/* Allocate memory for call transfer data */
	if (!p->refer && !sip_refer_allocate(p)) {
		transmit_response(p, "500 Internal Server Error", req);
		append_history(p, "Xfer", "Refer failed. Memory allocation error.");
		return -3;
	}

	res = get_refer_info(p, req);	/* Extract headers */

	p->refer->status = REFER_SENT;

	if (res != 0) {
		switch (res) {
		case -2:	/* Syntax error */
			transmit_response(p, "400 Bad Request (Refer-to missing)", req);
			append_history(p, "Xfer", "Refer failed. Refer-to missing.");
			if (req->debug)
				ast_debug(1, "SIP transfer to black hole can't be handled (no refer-to: )\n");
			break;
		case -3:
			transmit_response(p, "603 Declined (Non sip: uri)", req);
			append_history(p, "Xfer", "Refer failed. Non SIP uri");
			if (req->debug)
				ast_debug(1, "SIP transfer to non-SIP uri denied\n");
			break;
		default:
			/* Refer-to extension not found, fake a failed transfer */
			transmit_response(p, "202 Accepted", req);
			append_history(p, "Xfer", "Refer failed. Bad extension.");
			transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
			ast_clear_flag(&p->flags[0], SIP_GOTREFER);	
			if (req->debug)
				ast_debug(1, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
			break;
		} 
		return 0;
	}
	if (ast_strlen_zero(p->context))
		ast_string_field_set(p, context, default_context);

	/* If we do not support SIP domains, all transfers are local */
	if (allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
		p->refer->localtransfer = 1;
		if (sipdebug)
			ast_debug(3, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
	} else if (AST_LIST_EMPTY(&domain_list) || check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
		/* This PBX doesn't bother with SIP domains or domain is local, so this transfer is local */
		p->refer->localtransfer = 1;
	} else if (sipdebug)
			ast_debug(3, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
	
	/* Is this a repeat of a current request? Ignore it */
	/* Don't know what else to do right now. */
	if (req->ignore) 
		return res;

	/* If this is a blind transfer, we have the following
	channels to work with:
	- chan1, chan2: The current call between transferer and transferee (2 channels)
	- target_channel: A new call from the transferee to the target (1 channel)
	We need to stay tuned to what happens in order to be able
	to bring back the call to the transferer */

	/* If this is a attended transfer, we should have all call legs within reach:
	- chan1, chan2: The call between the transferer and transferee (2 channels)
	- target_channel, targetcall_pvt: The call between the transferer and the target (2 channels)
	We want to bridge chan2 with targetcall_pvt!
	
	The replaces call id in the refer message points
	to the call leg between Asterisk and the transferer.
	So we need to connect the target and the transferee channel
	and hangup the two other channels silently 
	
	If the target is non-local, the call ID could be on a remote
	machine and we need to send an INVITE with replaces to the
	target. We basically handle this as a blind transfer
	and let the sip_call function catch that we need replaces
	header in the INVITE.
	*/


	/* Get the transferer's channel */
	current.chan1 = p->owner;

	/* Find the other part of the bridge (2) - transferee */
	current.chan2 = ast_bridged_channel(current.chan1);
	
	if (sipdebug)
		ast_debug(3, "SIP %s transfer: Transferer channel %s, transferee channel %s\n", p->refer->attendedtransfer ? "attended" : "blind", current.chan1->name, current.chan2 ? current.chan2->name : "<none>");

	if (!current.chan2 && !p->refer->attendedtransfer) {
		/* No bridged channel, propably IVR or echo or similar... */
		/* Guess we should masquerade or something here */
		/* Until we figure it out, refuse transfer of such calls */
		if (sipdebug)
			ast_debug(3, "Refused SIP transfer on non-bridged channel.\n");
		p->refer->status = REFER_FAILED;
		append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
		transmit_response(p, "603 Declined", req);
		return -1;
	}

	if (current.chan2) {
		if (sipdebug)
			ast_debug(4, "Got SIP transfer, applying to bridged peer '%s'\n", current.chan2->name);

		ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
	}

	ast_set_flag(&p->flags[0], SIP_GOTREFER);	

	/* Attended transfer: Find all call legs and bridge transferee with target*/
	if (p->refer->attendedtransfer) {
		if ((res = local_attended_transfer(p, &current, req, seqno)))
			return res;	/* We're done with the transfer */
		/* Fall through for remote transfers that we did not find locally */
		if (sipdebug)
			ast_debug(4, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
		/* Fallthrough if we can't find the call leg internally */
	}


	/* Parking a call */
	if (p->refer->localtransfer && !strcmp(p->refer->refer_to, ast_parking_ext())) {
		/* Must release c's lock now, because it will not longer be accessible after the transfer! */
		*nounlock = 1;
		ast_channel_unlock(current.chan1);
		copy_request(&current.req, req);
		ast_clear_flag(&p->flags[0], SIP_GOTREFER);	
		p->refer->status = REFER_200OK;
		append_history(p, "Xfer", "REFER to call parking.");
		manager_event(EVENT_FLAG_CALL, "Transfer", "TransferMethod: SIP\r\nTransferType: Blind\r\nChannel: %s\r\nUniqueid: %s\r\nSIP-Callid: %s\r\nTargetChannel: %s\r\nTargetUniqueid: %s\r\nTransferExten: %s\r\nTransfer2Parking: Yes\r\n",
			current.chan1->name,
			current.chan1->uniqueid,
			p->callid,
			current.chan2->name,
			current.chan2->uniqueid,
			p->refer->refer_to);
		if (sipdebug)
			ast_debug(4, "SIP transfer to parking: trying to park %s. Parked by %s\n", current.chan2->name, current.chan1->name);
		sip_park(current.chan2, current.chan1, req, seqno);
		return res;
	} 

	/* Blind transfers and remote attended xfers */
	transmit_response(p, "202 Accepted", req);

	if (current.chan1 && current.chan2) {
		ast_debug(3, "chan1->name: %s\n", current.chan1->name);
		pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", current.chan2->name);
	}
	if (current.chan2) {
		pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", current.chan1->name);
		pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", p->refer->refer_to_domain);
		pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
		/* One for the new channel */
		pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
		/* Attended transfer to remote host, prepare headers for the INVITE */
		if (p->refer->referred_by) 
			pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", p->refer->referred_by);
	}
	/* Generate a Replaces string to be used in the INVITE during attended transfer */
	if (!ast_strlen_zero(p->refer->replaces_callid)) {
		char tempheader[SIPBUFSIZE];
		snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid, 
				p->refer->replaces_callid_totag ? ";to-tag=" : "", 
				p->refer->replaces_callid_totag, 
				p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
				p->refer->replaces_callid_fromtag);
		if (current.chan2)
			pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
	}
	/* Must release lock now, because it will not longer
	   be accessible after the transfer! */
	*nounlock = 1;
	ast_channel_unlock(current.chan1);

	/* Connect the call */

	/* FAKE ringing if not attended transfer */
	if (!p->refer->attendedtransfer)
		transmit_notify_with_sipfrag(p, seqno, "183 Ringing", FALSE); 
		
	/* For blind transfer, this will lead to a new call */
	/* For attended transfer to remote host, this will lead to
	   a new SIP call with a replaces header, if the dial plan allows it 
	*/
	if (!current.chan2) {
		/* We have no bridge, so we're talking with Asterisk somehow */
		/* We need to masquerade this call */
		/* What to do to fix this situation:
		   * Set up the new call in a new channel 
		   * Let the new channel masq into this channel
		   Please add that code here :-)
		*/
		p->refer->status = REFER_FAILED;
		transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
		ast_clear_flag(&p->flags[0], SIP_GOTREFER);	
		append_history(p, "Xfer", "Refer failed (only bridged calls).");
		return -1;
	}
	ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);	/* Delay hangup */


	/* For blind transfers, move the call to the new extensions. For attended transfers on multiple
	   servers - generate an INVITE with Replaces. Either way, let the dial plan decided  */
	res = ast_async_goto(current.chan2, p->refer->refer_to_context, p->refer->refer_to, 1);

	if (!res) {
		manager_event(EVENT_FLAG_CALL, "Transfer", "TransferMethod: SIP\r\nTransferType: Blind\r\nChannel: %s\r\nUniqueid: %s\r\nSIP-Callid: %s\r\nTargetChannel: %s\r\nTargetUniqueid: %s\r\nTransferExten: %s\r\nTransferContext: %s\r\n",
			current.chan1->name,
			current.chan1->uniqueid,
			p->callid,
			current.chan2->name,
			current.chan2->uniqueid,
			p->refer->refer_to, p->refer->refer_to_context);
		/* Success  - we have a new channel */
		ast_debug(3, "%s transfer succeeded. Telling transferer.\n", p->refer->attendedtransfer? "Attended" : "Blind");
		transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
		if (p->refer->localtransfer)
			p->refer->status = REFER_200OK;
		if (p->owner)
			p->owner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
		append_history(p, "Xfer", "Refer succeeded.");
		ast_clear_flag(&p->flags[0], SIP_GOTREFER);	
		/* Do not hangup call, the other side do that when we say 200 OK */
		/* We could possibly implement a timer here, auto congestion */
		res = 0;
	} else {
		ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);	/* Don't delay hangup */
		ast_debug(3, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
		append_history(p, "Xfer", "Refer failed.");
		/* Failure of some kind */
		p->refer->status = REFER_FAILED;
		transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
		ast_clear_flag(&p->flags[0], SIP_GOTREFER);	
		res = -1;
	}
	return res;
}

/*! \brief Handle incoming CANCEL request */
static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
{
		
	check_via(p, req);
	sip_alreadygone(p);

	/* At this point, we could have cancelled the invite at the same time
	   as the other side sends a CANCEL. Our final reply with error code
	   might not have been received by the other side before the CANCEL
	   was sent, so let's just give up retransmissions and waiting for
	   ACK on our error code. The call is hanging up any way. */
	if (p->invitestate == INV_TERMINATED)
		__sip_pretend_ack(p);
	else
		p->invitestate = INV_CANCELLED;
	
	if (p->owner && p->owner->_state == AST_STATE_UP) {
		/* This call is up, cancel is ignored, we need a bye */
		transmit_response(p, "200 OK", req);
		ast_debug(1, "Got CANCEL on an answered call. Ignoring... \n");
		return 0;
	}

	if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) 
		update_call_counter(p, DEC_CALL_LIMIT);

	stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
	if (p->owner)
		ast_queue_hangup(p->owner);
	else
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
	if (p->initreq.len > 0) {
		struct sip_pkt *pkt, *prev_pkt;
		/* If the CANCEL we are receiving is a retransmission, and we already have scheduled
		 * a reliable 487, then we don't want to schedule another one on top of the previous
		 * one.
		 *
		 * As odd as this may sound, we can't rely on the previously-transmitted "reliable" 
		 * response in this situation. What if we've sent all of our reliable responses 
		 * already and now all of a sudden, we get this second CANCEL?
		 *
		 * The only way to do this correctly is to cancel our previously-scheduled reliably-
		 * transmitted response and send a new one in its place.
		 */
		for (pkt = p->packets, prev_pkt = NULL; pkt; prev_pkt = pkt, pkt = pkt->next) {
			if (pkt->seqno == p->lastinvite && pkt->response_code == 487) {
				AST_SCHED_DEL(sched, pkt->retransid);
				UNLINK(pkt, p->packets, prev_pkt);
				ast_free(pkt);
				break;
			}
		}
		transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
		transmit_response(p, "200 OK", req);
		return 1;
	} else {
		transmit_response(p, "481 Call Leg Does Not Exist", req);
		return 0;
	}
}

static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen)
{
	struct sip_pvt *p = chan->tech_pvt;
	char *all = "", *parse = ast_strdupa(preparse);
	int res = 0;
	AST_DECLARE_APP_ARGS(args,
		AST_APP_ARG(param);
		AST_APP_ARG(type);
		AST_APP_ARG(field);
	);
	AST_STANDARD_APP_ARGS(args, parse);

	/* Sanity check */
	if (!IS_SIP_TECH(chan->tech)) {
		ast_log(LOG_ERROR, "Cannot call %s on a non-SIP channel\n", funcname);
		return 0;
	}

	memset(buf, 0, buflen);

	if (p == NULL) {
		return -1;
	}

	if (!strcasecmp(args.param, "rtpdest")) {
		struct sockaddr_in sin;
		struct ast_rtp *stream = NULL;

		if (ast_strlen_zero(args.type))
			args.type = "audio";

		if (!strcasecmp(args.type, "audio")) {
			stream = p->rtp;
		} else if (!strcasecmp(args.type, "video")) {
			stream = p->vrtp;
		} else if (!strcasecmp(args.type, "text")) {
			stream = p->trtp;
		}

		if (!stream) {
			return -1;
		}

		ast_rtp_get_peer(stream, &sin);
		snprintf(buf, buflen, "%s:%d", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
	} else if (!strcasecmp(args.param, "rtpqos")) {
		struct ast_rtp_quality qos;
		
		memset(&qos, 0, sizeof(qos));

		if (ast_strlen_zero(args.type))
			args.type = "audio";
		if (ast_strlen_zero(args.field))
			args.field = "all";
		
		if (!strcasecmp(args.type, "AUDIO")) {
			all = ast_rtp_get_quality(p->rtp, &qos);
		} else if (!strcasecmp(args.type, "VIDEO")) {
			all = ast_rtp_get_quality(p->vrtp, &qos);
		} else if (!strcasecmp(args.type, "TEXT")) {
			all = ast_rtp_get_quality(p->trtp, &qos);
		}
		
		if (!strcasecmp(args.field, "local_ssrc"))
			snprintf(buf, buflen, "%u", qos.local_ssrc);
		else if (!strcasecmp(args.field, "local_lostpackets"))
			snprintf(buf, buflen, "%u", qos.local_lostpackets);
		else if (!strcasecmp(args.field, "local_jitter"))
			snprintf(buf, buflen, "%.0f", qos.local_jitter * 1000.0);
		else if (!strcasecmp(args.field, "local_count"))
			snprintf(buf, buflen, "%u", qos.local_count);
		else if (!strcasecmp(args.field, "remote_ssrc"))
			snprintf(buf, buflen, "%u", qos.remote_ssrc);
		else if (!strcasecmp(args.field, "remote_lostpackets"))
			snprintf(buf, buflen, "%u", qos.remote_lostpackets);
		else if (!strcasecmp(args.field, "remote_jitter"))
			snprintf(buf, buflen, "%.0f", qos.remote_jitter * 1000.0);
		else if (!strcasecmp(args.field, "remote_count"))
			snprintf(buf, buflen, "%u", qos.remote_count);
		else if (!strcasecmp(args.field, "rtt"))
			snprintf(buf, buflen, "%.0f", qos.rtt * 1000.0);
		else if (!strcasecmp(args.field, "all"))
			ast_copy_string(buf, all, buflen);
		else {
			ast_log(LOG_WARNING, "Unrecognized argument '%s' to %s\n", preparse, funcname);
			return -1;
		}
	} else {
		res = -1;
	}
	return res;
}

/*! \brief Handle incoming BYE request */
static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
{
	struct ast_channel *c=NULL;
	int res;
	struct ast_channel *bridged_to;
	
	/* If we have an INCOMING invite that we haven't answered, terminate that transaction */
	if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !req->ignore) {
		transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
	}

	__sip_pretend_ack(p);

	p->invitestate = INV_TERMINATED;

	copy_request(&p->initreq, req);
	if (sipdebug)
		ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
	check_via(p, req);
	sip_alreadygone(p);

	/* Get RTCP quality before end of call */
	if (p->do_history || p->owner) {
		char *audioqos, *videoqos, *textqos;
		if (p->rtp) {
			audioqos = ast_rtp_get_quality(p->rtp, NULL);
			if (p->do_history)
				append_history(p, "RTCPaudio", "Quality:%s", audioqos);
			if (p->owner)
				pbx_builtin_setvar_helper(p->owner, "RTPAUDIOQOS", audioqos);
		}
		if (p->vrtp) {
			videoqos = ast_rtp_get_quality(p->vrtp, NULL);
			if (p->do_history)
				append_history(p, "RTCPvideo", "Quality:%s", videoqos);
			if (p->owner)
				pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", videoqos);
		}
		if (p->trtp) {
			textqos = ast_rtp_get_quality(p->trtp, NULL);
			if (p->do_history)
				append_history(p, "RTCPtext", "Quality:%s", textqos);
			if (p->owner)
				pbx_builtin_setvar_helper(p->owner, "RTPTEXTQOS", textqos);
		}
	}

	stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
	stop_session_timer(p); /* Stop Session-Timer */

	if (!ast_strlen_zero(get_header(req, "Also"))) {
		ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method.  Ask vendor to support REFER instead\n",
			ast_inet_ntoa(p->recv.sin_addr));
		if (ast_strlen_zero(p->context))
			ast_string_field_set(p, context, default_context);
		res = get_also_info(p, req);
		if (!res) {
			c = p->owner;
			if (c) {
				bridged_to = ast_bridged_channel(c);
				if (bridged_to) {
					/* Don't actually hangup here... */
					ast_queue_control(c, AST_CONTROL_UNHOLD);
					ast_async_goto(bridged_to, p->context, p->refer->refer_to, 1);
				} else
					ast_queue_hangup(p->owner);
			}
		} else {
			ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_inet_ntoa(p->recv.sin_addr));
			if (p->owner)
				ast_queue_hangup(p->owner);
		}
	} else if (p->owner) {
		ast_queue_hangup(p->owner);
		ast_debug(3, "Received bye, issuing owner hangup\n");
	} else {
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
			ast_debug(3, "Received bye, no owner, selfdestruct soon.\n");
	}
	ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
	transmit_response(p, "200 OK", req);

	return 1;
}

/*! \brief Handle incoming MESSAGE request */
static int handle_request_message(struct sip_pvt *p, struct sip_request *req)
{
	if (!req->ignore) {
		if (req->debug)
			ast_verbose("Receiving message!\n");
		receive_message(p, req);
	} else
		transmit_response(p, "202 Accepted", req);
	return 1;
}

static void add_peer_mwi_subs(struct sip_peer *peer)
{
	struct sip_mailbox *mailbox;

	AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
		mailbox->event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, peer,
			AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
			AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
			AST_EVENT_IE_END);
	}
}

/*! \brief  Handle incoming SUBSCRIBE request */
static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
{
	int gotdest = 0;
	int res = 0;
	int firststate = AST_EXTENSION_REMOVED;
	struct sip_peer *authpeer = NULL;
	const char *eventheader = get_header(req, "Event");	/* Get Event package name */
	const char *accept = get_header(req, "Accept");
	int resubscribe = (p->subscribed != NONE);
	char *temp, *event;

	if (p->initreq.headers) {	
		/* We already have a dialog */
		if (p->initreq.method != SIP_SUBSCRIBE) {
			/* This is a SUBSCRIBE within another SIP dialog, which we do not support */
			/* For transfers, this could happen, but since we haven't seen it happening, let us just refuse this */
 			transmit_response(p, "403 Forbidden (within dialog)", req);
			/* Do not destroy session, since we will break the call if we do */
			ast_debug(1, "Got a subscription within the context of another call, can't handle that - %s (Method %s)\n", p->callid, sip_methods[p->initreq.method].text);
			return 0;
		} else if (req->debug) {
			if (resubscribe)
				ast_debug(1, "Got a re-subscribe on existing subscription %s\n", p->callid);
			else
				ast_debug(1, "Got a new subscription %s (possibly with auth)\n", p->callid);
		}
	}

	/* Check if we have a global disallow setting on subscriptions. 
		if so, we don't have to check peer/user settings after auth, which saves a lot of processing
	*/
	if (!global_allowsubscribe) {
 		transmit_response(p, "403 Forbidden (policy)", req);
		p->needdestroy = 1;
		return 0;
	}

	if (!req->ignore && !resubscribe) {	/* Set up dialog, new subscription */
		const char *to = get_header(req, "To");
		char totag[128];

		/* Check to see if a tag was provided, if so this is actually a resubscription of a dialog we no longer know about */
		if (!ast_strlen_zero(to) && gettag(req, "To", totag, sizeof(totag))) {
			if (req->debug)
				ast_verbose("Received resubscription for a dialog we no longer know about. Telling remote side to subscribe again.\n");
			transmit_response(p, "481 Subscription does not exist", req);
			p->needdestroy = 1;
			return 0;
		}

		/* Use this as the basis */
		if (req->debug)
			ast_verbose("Creating new subscription\n");

		copy_request(&p->initreq, req);
		if (sipdebug)
			ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
		check_via(p, req);
		build_route(p, req, 0);
	} else if (req->debug && req->ignore)
		ast_verbose("Ignoring this SUBSCRIBE request\n");

	/* Find parameters to Event: header value and remove them for now */
	if (ast_strlen_zero(eventheader)) {
		transmit_response(p, "489 Bad Event", req);
		ast_debug(2, "Received SIP subscribe for unknown event package: <none>\n");
		p->needdestroy = 1;
		return 0;
	}

	if ( (strchr(eventheader, ';'))) {
		event = ast_strdupa(eventheader);	/* Since eventheader is a const, we can't change it */
		temp = strchr(event, ';'); 		
		*temp = '\0';				/* Remove any options for now */
							/* We might need to use them later :-) */
	} else
		event = (char *) eventheader;		/* XXX is this legal ? */

	/* Handle authentication */
	res = check_user_full(p, req, SIP_SUBSCRIBE, e, 0, sin, &authpeer);
	/* if an authentication response was sent, we are done here */
	if (res == AUTH_CHALLENGE_SENT)	/* authpeer = NULL here */
		return 0;
	if (res < 0) {
		if (res == AUTH_FAKE_AUTH) {
			ast_log(LOG_NOTICE, "Sending fake auth rejection for user %s\n", get_header(req, "From"));
			transmit_fake_auth_response(p, SIP_SUBSCRIBE, req, XMIT_UNRELIABLE);
		} else {
			ast_log(LOG_NOTICE, "Failed to authenticate user %s for SUBSCRIBE\n", get_header(req, "From"));
			transmit_response_reliable(p, "403 Forbidden", req);
		}
		p->needdestroy = 1;
		return 0;
	}

	/* At this point, authpeer cannot be NULL. Remember we hold a reference,
	 * so we must release it when done.
	 * XXX must remove all the checks for authpeer == NULL.
	 */

	/* Check if this user/peer is allowed to subscribe at all */
	if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
		transmit_response(p, "403 Forbidden (policy)", req);
		p->needdestroy = 1;
		if (authpeer)
			unref_peer(authpeer);
		return 0;
	}

	if (strcmp(event, "message-summary")) {
		/* Get destination right away */
		gotdest = get_destination(p, NULL);
	}

	/* Get full contact header - this needs to be used as a request URI in NOTIFY's */
	parse_ok_contact(p, req);

	build_contact(p);
	if (gotdest) {
		transmit_response(p, "404 Not Found", req);
		p->needdestroy = 1;
		if (authpeer)
			unref_peer(authpeer);
		return 0;
	}

	/* Initialize tag for new subscriptions */	
	if (ast_strlen_zero(p->tag))
		make_our_tag(p->tag, sizeof(p->tag));

	if (!strcmp(event, "presence") || !strcmp(event, "dialog")) { /* Presence, RFC 3842 */
		unsigned int pidf_xml;

		if (authpeer)	/* We do not need the authpeer any more */
			unref_peer(authpeer);

		/* Header from Xten Eye-beam Accept: multipart/related, application/rlmi+xml, application/pidf+xml, application/xpidf+xml */

		pidf_xml = strstr(accept, "application/pidf+xml") ? 1 : 0;

		/* Older versions of Polycom firmware will claim pidf+xml, but really
		 * they only support xpidf+xml. */
		if (pidf_xml && strstr(p->useragent, "Polycom")) {
			p->subscribed = XPIDF_XML;
		} else if (pidf_xml) {
			p->subscribed = PIDF_XML;         /* RFC 3863 format */
		} else if (strstr(accept, "application/dialog-info+xml")) {
			p->subscribed = DIALOG_INFO_XML;
			/* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
		} else if (strstr(accept, "application/cpim-pidf+xml")) {
			p->subscribed = CPIM_PIDF_XML;    /* RFC 3863 format */
		} else if (strstr(accept, "application/xpidf+xml")) {
			p->subscribed = XPIDF_XML;        /* Early pre-RFC 3863 format with MSN additions (Microsoft Messenger) */
		} else if (ast_strlen_zero(accept)) {
			if (p->subscribed == NONE) { /* if the subscribed field is not already set, and there is no accept header... */
				transmit_response(p, "489 Bad Event", req);
  
				ast_log(LOG_WARNING, "SUBSCRIBE failure: no Accept header: pvt: stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
					p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
				p->needdestroy = 1;
				return 0;
			}
			/* if p->subscribed is non-zero, then accept is not obligatory; according to rfc 3265 section 3.1.3, at least.
			   so, we'll just let it ride, keeping the value from a previous subscription, and not abort the subscription */
		} else {
			/* Can't find a format for events that we know about */
			char mybuf[200];
			snprintf(mybuf, sizeof(mybuf), "489 Bad Event (format %s)", accept);
			transmit_response(p, mybuf, req);
 
			ast_log(LOG_WARNING, "SUBSCRIBE failure: unrecognized format: '%s' pvt: subscribed: %d, stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
				accept, (int)p->subscribed, p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
			p->needdestroy = 1;
			return 0;
		}
	} else if (!strcmp(event, "message-summary")) { 
		if (!ast_strlen_zero(accept) && strcmp(accept, "application/simple-message-summary")) {
			/* Format requested that we do not support */
			transmit_response(p, "406 Not Acceptable", req);
			ast_debug(2, "Received SIP mailbox subscription for unknown format: %s\n", accept);
			p->needdestroy = 1;
			if (authpeer)
				unref_peer(authpeer);
			return 0;
		}
		/* Looks like they actually want a mailbox status 
		  This version of Asterisk supports mailbox subscriptions
		  The subscribed URI needs to exist in the dial plan
		  In most devices, this is configurable to the voicemailmain extension you use
		*/
		if (!authpeer || AST_LIST_EMPTY(&authpeer->mailboxes)) {
			transmit_response(p, "404 Not found (no mailbox)", req);
			p->needdestroy = 1;
			ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", authpeer->name);
			if (authpeer)
				unref_peer(authpeer);
			return 0;
		}

		p->subscribed = MWI_NOTIFICATION;
		if (ast_test_flag(&authpeer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY)) {
			add_peer_mwi_subs(authpeer);
		}
		if (authpeer->mwipvt && authpeer->mwipvt != p) {	/* Destroy old PVT if this is a new one */
			/* We only allow one subscription per peer */
			dialog_cleanup_and_destroy(authpeer->mwipvt); /* sip_destroy(authpeer->mwipvt);*/
		}
		authpeer->mwipvt = p;		/* Link from peer to pvt */
		p->relatedpeer = authpeer;	/* Link from pvt to peer */
		/* Do not release authpeer here */
	} else { /* At this point, Asterisk does not understand the specified event */
		transmit_response(p, "489 Bad Event", req);
		ast_debug(2, "Received SIP subscribe for unknown event package: %s\n", event);
		p->needdestroy = 1;
		if (authpeer)
			unref_peer(authpeer);
		return 0;
	}

	/* Add subscription for extension state from the PBX core */
	if (p->subscribed != MWI_NOTIFICATION && !resubscribe) {
		if (p->stateid > -1)
			ast_extension_state_del(p->stateid, cb_extensionstate);
		p->stateid = ast_extension_state_add(p->context, p->exten, cb_extensionstate, p);
	}

	if (!req->ignore && p)
		p->lastinvite = seqno;
	if (p && !p->needdestroy) {
		p->expiry = atoi(get_header(req, "Expires"));

		/* check if the requested expiry-time is within the approved limits from sip.conf */
		if (p->expiry > max_expiry)
			p->expiry = max_expiry;
		if (p->expiry < min_expiry && p->expiry > 0)
			p->expiry = min_expiry;

		if (sipdebug) {
			if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer)
				ast_debug(2, "Adding subscription for mailbox notification - peer %s\n", p->relatedpeer->name);
			else
				ast_debug(2, "Adding subscription for extension %s context %s for peer %s\n", p->exten, p->context, p->username);
		}
		if (p->autokillid > -1 && sip_cancel_destroy(p))	/* Remove subscription expiry for renewals */
			ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
		if (p->expiry > 0)
			sip_scheddestroy(p, (p->expiry + 10) * 1000);	/* Set timer for destruction of call at expiration */

		if (p->subscribed == MWI_NOTIFICATION) {
			ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
			transmit_response(p, "200 OK", req);
			if (p->relatedpeer) {	/* Send first notification */
				ASTOBJ_WRLOCK(p->relatedpeer);
				sip_send_mwi_to_peer(p->relatedpeer, NULL, 0);
				ASTOBJ_UNLOCK(p->relatedpeer);
			}
		} else {
			struct sip_pvt *p_old;

			if ((firststate = ast_extension_state(NULL, p->context, p->exten)) < 0) {

				ast_log(LOG_NOTICE, "Got SUBSCRIBE for extension %s@%s from %s, but there is no hint for that extension.\n", p->exten, p->context, ast_inet_ntoa(p->sa.sin_addr));
				transmit_response(p, "404 Not found", req);
				p->needdestroy = 1;
				return 0;
			}
			ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
			transmit_response(p, "200 OK", req);
			transmit_state_notify(p, firststate, 1, FALSE);	/* Send first notification */
			append_history(p, "Subscribestatus", "%s", ast_extension_state2str(firststate));
			/* hide the 'complete' exten/context in the refer_to field for later display */
			ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);

			/* remove any old subscription from this peer for the same exten/context,
			as the peer has obviously forgotten about it and it's wasteful to wait
			for it to expire and send NOTIFY messages to the peer only to have them
			ignored (or generate errors)
			*/
			dialoglist_lock();
			for (p_old = dialoglist; p_old; p_old = p_old->next) {
				if (p_old == p)
					continue;
				if (p_old->initreq.method != SIP_SUBSCRIBE)
					continue;
				if (p_old->subscribed == NONE)
					continue;
				sip_pvt_lock(p_old);
				if (!strcmp(p_old->username, p->username)) {
					if (!strcmp(p_old->exten, p->exten) &&
					    !strcmp(p_old->context, p->context)) {
						p_old->needdestroy = 1;
						sip_pvt_unlock(p_old);
						break;
					}
				}
				sip_pvt_unlock(p_old);
			}
			dialoglist_unlock();
		}
		if (!p->expiry)
			p->needdestroy = 1;
	}
	return 1;
}

/*! \brief Handle incoming REGISTER request */
static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e)
{
	enum check_auth_result res;

	/* Use this as the basis */
	copy_request(&p->initreq, req);
	if (sipdebug)
		ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
	check_via(p, req);
	if ((res = register_verify(p, sin, req, e)) < 0) {
		const char *reason;

		switch (res) {
		case AUTH_SECRET_FAILED:
			reason = "Wrong password";
			break;
		case AUTH_USERNAME_MISMATCH:
			reason = "Username/auth name mismatch";
			break;
		case AUTH_NOT_FOUND:
			reason = "No matching peer found";
			break;
		case AUTH_UNKNOWN_DOMAIN:
			reason = "Not a local domain";
			break;
		case AUTH_PEER_NOT_DYNAMIC:
			reason = "Peer is not supposed to register";
			break;
		case AUTH_ACL_FAILED:
			reason = "Device does not match ACL";
			break;
		case AUTH_BAD_TRANSPORT:
			reason = "Device not configured to use this transport type";
			break;
		default:
			reason = "Unknown failure";
			break;
		}
		ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
			get_header(req, "To"), ast_inet_ntoa(sin->sin_addr),
			reason);
		append_history(p, "RegRequest", "Failed : Account %s : %s", get_header(req, "To"), reason);
	} else
		append_history(p, "RegRequest", "Succeeded : Account %s", get_header(req, "To"));

	if (res < 1) {
		/* Destroy the session, but keep us around for just a bit in case they don't
		   get our 200 OK */
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
	}
	return res;
}

/*! \brief Handle incoming SIP requests (methods) 
\note	This is where all incoming requests go first   */
/* called with p and p->owner locked */
static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock)
{
	/* Called with p->lock held, as well as p->owner->lock if appropriate, keeping things
	   relatively static */
	const char *cmd;
	const char *cseq;
	const char *useragent;
	int seqno;
	int len;
	int respid;
	int res = 0;
	int debug = sip_debug_test_pvt(p);
	char *e;
	int error = 0;
	int oldmethod = p->method;
	int acked = 0;

	/* Get Method and Cseq */
	cseq = get_header(req, "Cseq");
	cmd = req->header[0];

	/* Must have Cseq */
	if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq)) {
		ast_log(LOG_ERROR, "Missing Cseq. Dropping this SIP message, it's incomplete.\n");
		error = 1;
	}
	if (!error && sscanf(cseq, "%30d%n", &seqno, &len) != 1) {
		ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
		error = 1;
	}
	if (error) {
		if (!p->initreq.headers)	/* New call */
			p->needdestroy = 1; /* Make sure we destroy this dialog */
		return -1;
	}
	/* Get the command XXX */

	cmd = req->rlPart1;
	e = ast_skip_blanks(req->rlPart2);

	/* Save useragent of the client */
	useragent = get_header(req, "User-Agent");
	if (!ast_strlen_zero(useragent))
		ast_string_field_set(p, useragent, useragent);

	/* Find out SIP method for incoming request */
	if (req->method == SIP_RESPONSE) {	/* Response to our request */
		/* ignore means "don't do anything with it" but still have to 
		 * respond appropriately.
		 * But in this case this is a response already, so we really
		 * have nothing to do with this message, and even setting the
		 * ignore flag is pointless.
		 */
		if (ast_strlen_zero(e)) {
			return 0;
		}
		if (sscanf(e, "%30d %n", &respid, &len) != 1) {
			ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
			return 0;
		}
		if (respid <= 0) {
			ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
			return 0;
		}
		if (p->ocseq && (p->ocseq < seqno)) {
			if (option_debug)
				ast_log(LOG_DEBUG, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
			return -1;
		} else {
			if ((respid == 200) || ((respid >= 300) && (respid <= 399))) {
				extract_uri(p, req);
			}
			handle_response(p, respid, e + len, req, seqno);
		}
		return 0;
	}

	/* New SIP request coming in 
	   (could be new request in existing SIP dialog as well...) 
	 */			
	
	p->method = req->method;	/* Find out which SIP method they are using */
	ast_debug(4, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd); 

	if (p->icseq && (p->icseq > seqno) ) {
		if (p->pendinginvite && seqno == p->pendinginvite && (req->method == SIP_ACK || req->method == SIP_CANCEL)) {
			ast_debug(2, "Got CANCEL or ACK on INVITE with transactions in between.\n");
		}  else {
			ast_debug(1, "Ignoring too old SIP packet packet %d (expecting >= %d)\n", seqno, p->icseq);
			if (req->method != SIP_ACK)
				transmit_response(p, "503 Server error", req);	/* We must respond according to RFC 3261 sec 12.2 */
			return -1;
		}
	} else if (p->icseq &&
		   p->icseq == seqno &&
		   req->method != SIP_ACK &&
		   (p->method != SIP_CANCEL || p->alreadygone)) {
		/* ignore means "don't do anything with it" but still have to 
		   respond appropriately.  We do this if we receive a repeat of
		   the last sequence number  */
		req->ignore = 1;
		ast_debug(3, "Ignoring SIP message because of retransmit (%s Seqno %d, ours %d)\n", sip_methods[p->method].text, p->icseq, seqno);
	}
		
	if (seqno >= p->icseq)
		/* Next should follow monotonically (but not necessarily 
		   incrementally -- thanks again to the genius authors of SIP --
		   increasing */
		p->icseq = seqno;

	/* Find their tag if we haven't got it */
	if (ast_strlen_zero(p->theirtag)) {
		char tag[128];

		gettag(req, "From", tag, sizeof(tag));
		ast_string_field_set(p, theirtag, tag);
	}
	snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);

	if (pedanticsipchecking) {
		/* If this is a request packet without a from tag, it's not
			correct according to RFC 3261  */
		/* Check if this a new request in a new dialog with a totag already attached to it,
			RFC 3261 - section 12.2 - and we don't want to mess with recovery  */
		if (!p->initreq.headers && req->has_to_tag) {
			/* If this is a first request and it got a to-tag, it is not for us */
			if (!req->ignore && req->method == SIP_INVITE) {
				transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
				/* Will cease to exist after ACK */
			} else if (req->method != SIP_ACK) {
				transmit_response(p, "481 Call/Transaction Does Not Exist", req);
				sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
			} else {
				ast_debug(1, "Got ACK for unknown dialog... strange.\n");
			}
			return res;
		}
	}

	if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY)) {
		transmit_response(p, "400 Bad request", req);
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
		return -1;
	}

	/* Handle various incoming SIP methods in requests */
	switch (p->method) {
	case SIP_OPTIONS:
		res = handle_request_options(p, req);
		break;
	case SIP_INVITE:
		res = handle_request_invite(p, req, debug, seqno, sin, recount, e, nounlock);
		break;
	case SIP_REFER:
		res = handle_request_refer(p, req, debug, seqno, nounlock);
		break;
	case SIP_CANCEL:
		res = handle_request_cancel(p, req);
		break;
	case SIP_BYE:
		res = handle_request_bye(p, req);
		break;
	case SIP_MESSAGE:
		res = handle_request_message(p, req);
		break;
	case SIP_SUBSCRIBE:
		res = handle_request_subscribe(p, req, sin, seqno, e);
		break;
	case SIP_REGISTER:
		res = handle_request_register(p, req, sin, e);
		break;
	case SIP_INFO:
		if (req->debug)
			ast_verbose("Receiving INFO!\n");
		if (!req->ignore) 
			handle_request_info(p, req);
		else  /* if ignoring, transmit response */
			transmit_response(p, "200 OK", req);
		break;
	case SIP_NOTIFY:
		res = handle_request_notify(p, req, sin, seqno, e);
		break;
	case SIP_ACK:
		/* Make sure we don't ignore this */
		if (seqno == p->pendinginvite) {
			p->invitestate = INV_TERMINATED;
			p->pendinginvite = 0;
			acked = __sip_ack(p, seqno, 1 /* response */, 0);
			if (find_sdp(req)) {
				if (process_sdp(p, req, SDP_T38_NONE))
					return -1;
			}
			check_pendings(p);
		} else if (p->glareinvite == seqno) {
			/* handle ack for the 491 pending sent for glareinvite */
			p->glareinvite = 0;
			acked = __sip_ack(p, seqno, 1, 0);
		}
		if (!acked) {
			/* Got an ACK that did not match anything. Ignore
			 * silently and restore previous method */
			p->method = oldmethod;
		}
		if (!p->lastinvite && ast_strlen_zero(p->randdata))
			p->needdestroy = 1;
		break;
	default:
		transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
		ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n", 
			cmd, ast_inet_ntoa(p->sa.sin_addr));
		/* If this is some new method, and we don't have a call, destroy it now */
		if (!p->initreq.headers)
			p->needdestroy = 1;
		break;
	}
	return res;
}

static void process_request_queue(struct sip_pvt *p, int *recount, int *nounlock)
{
	struct sip_request *req;

	while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
		if (handle_incoming(p, req, &p->recv, recount, nounlock) == -1) {
			/* Request failed */
			if (option_debug) {
				ast_log(LOG_DEBUG, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
			}
		}
		ast_free(req);
	}
}

static int scheduler_process_request_queue(const void *data)
{
	struct sip_pvt *p = (struct sip_pvt *) data;
	int recount = 0;
	int nounlock = 0;
	int lockretry;

	for (lockretry = 10; lockretry > 0; lockretry--) {
		sip_pvt_lock(p);

		/* lock the owner if it has one -- we may need it */
		/* because this is deadlock-prone, we need to try and unlock if failed */
		if (!p->owner || !ast_channel_trylock(p->owner)) {
			break;	/* locking succeeded */
		}

		if (lockretry != 1) {
			sip_pvt_unlock(p);
			/* Sleep for a very short amount of time */
			usleep(1);
		}
	}

	if (!lockretry) {
		int retry = !AST_LIST_EMPTY(&p->request_queue);

		/* we couldn't get the owner lock, which is needed to process
		   the queued requests, so return a non-zero value, which will
		   cause the scheduler to run this request again later if there
		   still requests to be processed
		*/
		sip_pvt_unlock(p);
		return retry;
	};

	process_request_queue(p, &recount, &nounlock);
	p->request_queue_sched_id = -1;

	if (p->owner && !nounlock) {
		ast_channel_unlock(p->owner);
	}
	sip_pvt_unlock(p);

	if (recount) {
		ast_update_use_count();
	}

	return 0;
}

static int queue_request(struct sip_pvt *p, const struct sip_request *req)
{
	struct sip_request *newreq;

	if (!(newreq = ast_calloc(1, sizeof(*newreq)))) {
		return -1;
	}

	copy_request(newreq, req);
	AST_LIST_INSERT_TAIL(&p->request_queue, newreq, next);
	if (p->request_queue_sched_id == -1) {
		p->request_queue_sched_id = ast_sched_add(sched, 10, scheduler_process_request_queue, p);
	}

	return 0;
}

/*! \brief Read data from SIP socket
\note sipsock_read locks the owner channel while we are processing the SIP message
\return 1 on error, 0 on success
\note Successful messages is connected to SIP call and forwarded to handle_incoming() 
*/
static int sipsock_read(int *id, int fd, short events, void *ignore)
{
	struct sip_request req;
	struct sockaddr_in sin = { 0, };
	int res;
	socklen_t len = sizeof(sin);

	memset(&req, 0, sizeof(req));
	res = recvfrom(fd, req.data, sizeof(req.data) - 1, 0, (struct sockaddr *)&sin, &len);
	if (res < 0) {
#if !defined(__FreeBSD__)
		if (errno == EAGAIN)
			ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
		else 
#endif
		if (errno != ECONNREFUSED)
			ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
		return 1;
	}
	if (res == sizeof(req.data) - 1)
		ast_debug(1, "Received packet exceeds buffer. Data is possibly lost\n");

	req.data[res] = '\0';
	req.len = res;

	req.socket.fd = sipsock;
	set_socket_transport(&req.socket, SIP_TRANSPORT_UDP);
	req.socket.tcptls_session	= NULL;
	req.socket.port = bindaddr.sin_port;

	handle_request_do(&req, &sin);

	return 1;
}

static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin) 
{
	struct sip_pvt *p;
	int recount = 0;
	int nounlock = 0;
	int lockretry;

	if (sip_debug_test_addr(sin))	/* Set the debug flag early on packet level */
		req->debug = 1;
	if (pedanticsipchecking)
		req->len = lws2sws(req->data, req->len);	/* Fix multiline headers */
	if (req->debug) {
		ast_verbose("\n<--- SIP read from %s://%s:%d --->\n%s\n<------------->\n", 
			get_transport(req->socket.type), ast_inet_ntoa(sin->sin_addr), 
			ntohs(sin->sin_port), req->data);
	}

	if (parse_request(req) == -1) { /* Bad packet, can't parse */
		req->data[0] = '\0'; /* nulling this out is NOT a good idea here. */
		return 1;
	}

	req->method = find_sip_method(req->rlPart1);

	if (req->debug)
		ast_verbose("--- (%d headers %d lines)%s ---\n", req->headers, req->lines, (req->headers + req->lines == 0) ? " Nat keepalive" : "");

	if (req->headers < 2)	/* Must have at least two headers */
		return 1;

	/* Process request, with netlock held, and with usual deadlock avoidance */
	for (lockretry = 10; lockretry > 0; lockretry--) {
		ast_mutex_lock(&netlock);

		/* Find the active SIP dialog or create a new one */
		p = find_call(req, sin, req->method);	/* returns p locked */
		if (p == NULL) {
			ast_debug(1, "Invalid SIP message - rejected , no callid, len %d\n", req->len);
			ast_mutex_unlock(&netlock);
			return 1;
		}

		copy_socket_data(&p->socket, &req->socket);

		/* Go ahead and lock the owner if it has one -- we may need it */
		/* becaues this is deadlock-prone, we need to try and unlock if failed */
		if (!p->owner || !ast_channel_trylock(p->owner))
			break;	/* locking succeeded */
		if (lockretry != 1) {
			sip_pvt_unlock(p);
			ast_mutex_unlock(&netlock);
			/* Sleep for a very short amount of time */
			usleep(1);
		}
	}
	p->recv = *sin;

	if (p->do_history) /* This is a request or response, note what it was for */
		append_history(p, "Rx", "%s / %s / %s", req->data, get_header(req, "CSeq"), req->rlPart2);

	if (!lockretry) {
		if (!queue_request(p, req)) {
			/* the request has been queued for later handling */
			sip_pvt_unlock(p);
			ast_mutex_unlock(&netlock);
			return 1;
		}

		/* This is unsafe, since p->owner is not locked. */
		if (p->owner)
			ast_log(LOG_ERROR, "Channel lock for %s could not be obtained, and request was unable to be queued.\n", S_OR(p->owner->name, "- no channel name ??? - "));
		ast_log(LOG_ERROR, "SIP transaction failed: %s \n", p->callid);
		if (req->method != SIP_ACK)
			transmit_response(p, "503 Server error", req);	/* We must respond according to RFC 3261 sec 12.2 */
		/* XXX We could add retry-after to make sure they come back */
		append_history(p, "LockFail", "Owner lock failed, transaction failed.");
		sip_pvt_unlock(p);
		ast_mutex_unlock(&netlock);
		return 1;
	}

	/* if there are queued requests on this sip_pvt, process them first, so that everything is
	   handled in order
	*/
	if (!AST_LIST_EMPTY(&p->request_queue)) {
		AST_SCHED_DEL(sched, p->request_queue_sched_id);
		process_request_queue(p, &recount, &nounlock);
	}

	if (handle_incoming(p, req, sin, &recount, &nounlock) == -1) {
		/* Request failed */
		ast_debug(1, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
	}
		
	if (recount)
		ast_update_use_count();

	if (p->owner && !nounlock)
		ast_channel_unlock(p->owner);
	sip_pvt_unlock(p);
	ast_mutex_unlock(&netlock);

	return 1;
}

/*! \brief Returns the port to use for this socket
 *
 * \param type The type of transport used
 * \param port Port we are checking to see if it's the standard port.
 * \note port is expected in host byte order
 */
static int sip_standard_port(enum sip_transport type, int port)
{
	if (type & SIP_TRANSPORT_TLS)
		return port == STANDARD_TLS_PORT;
	else
		return port == STANDARD_SIP_PORT;
}

/*! 
 * \brief Find thread for TCP/TLS session (based on IP/Port 
 *
 * \note This function returns an astobj2 reference
 */
static struct ast_tcptls_session_instance *sip_tcp_locate(struct sockaddr_in *s)
{
	struct sip_threadinfo *th;
	struct ast_tcptls_session_instance *tcptls_instance = NULL;

	AST_LIST_LOCK(&threadl);
	AST_LIST_TRAVERSE(&threadl, th, list) {
		if ((s->sin_family == th->tcptls_session->requestor.sin_family) &&
			(s->sin_addr.s_addr == th->tcptls_session->requestor.sin_addr.s_addr) &&
			(s->sin_port == th->tcptls_session->requestor.sin_port))  {
				tcptls_instance = (ao2_ref(th->tcptls_session, +1), th->tcptls_session);
				break;
			}
	}
	AST_LIST_UNLOCK(&threadl);

	return tcptls_instance;
}

/*! \todo document this function. */
static int sip_prepare_socket(struct sip_pvt *p) 
{
	struct sip_socket *s = &p->socket;
	static const char name[] = "SIP socket";
	struct ast_tcptls_session_instance *tcptls_session;
	struct server_args ca = {
		.name = name,
		.accept_fd = -1,
	};

	if (s->fd != -1)
		return s->fd;

	if (p->outboundproxy && p->outboundproxy->transport) {
		s->type = p->outboundproxy->transport;
	}

	if (s->type & SIP_TRANSPORT_UDP) {
		s->fd = sipsock;
		return s->fd;
	}

	ca.sin = *(sip_real_dst(p));

	if ((tcptls_session = sip_tcp_locate(&ca.sin))) {
		s->fd = tcptls_session->fd;
		if (s->tcptls_session) {
			ao2_ref(s->tcptls_session, -1);
			s->tcptls_session = NULL;
		}
		s->tcptls_session = tcptls_session;
		return s->fd;
	}

	if (s->tcptls_session && s->tcptls_session->parent->tls_cfg) {
		ca.tls_cfg = s->tcptls_session->parent->tls_cfg;
	} else {
		if (s->type & SIP_TRANSPORT_TLS) {
			ca.tls_cfg = ast_calloc(1, sizeof(*ca.tls_cfg));
			if (!ca.tls_cfg)
				return -1;
			memcpy(ca.tls_cfg, &default_tls_cfg, sizeof(*ca.tls_cfg));
			if (!ast_strlen_zero(p->tohost))
				ast_copy_string(ca.hostname, p->tohost, sizeof(ca.hostname));
		}
	}
	
	if (s->tcptls_session) {
		/* the pvt socket already has a server instance ... */
	} else {
		s->tcptls_session = ast_tcptls_client_start(&ca); /* Start a client connection to this address */
	}

	if (!s->tcptls_session) {
		if (ca.tls_cfg)
			ast_free(ca.tls_cfg);
		return -1;
	}

	s->fd = ca.accept_fd;

	/* Give the new thread a reference */
	ao2_ref(s->tcptls_session, +1);

	if (ast_pthread_create_background(&ca.master, NULL, sip_tcp_worker_fn, s->tcptls_session)) {
		ast_debug(1, "Unable to launch '%s'.", ca.name);
		ao2_ref(s->tcptls_session, -1);
		close(ca.accept_fd);
		s->fd = ca.accept_fd = -1;
	}

	return s->fd;
}

/*!
 * \brief Small function to parse a config line for a host with a transport
 *        i.e. tls://www.google.com:8056
 */
static int sip_parse_host(char *line, int lineno, char **hostname, int *portnum, enum sip_transport *transport)
{
	char *port;

	if ((*hostname = strstr(line, "://"))) {
		*hostname += 3;

		if (!strncasecmp(line, "tcp", 3))
			*transport = SIP_TRANSPORT_TCP;
		else if (!strncasecmp(line, "tls", 3))
			*transport = SIP_TRANSPORT_TLS;
		else if (!strncasecmp(line, "udp", 3))
			*transport = SIP_TRANSPORT_UDP;
		else
			ast_log(LOG_NOTICE, "'%.3s' is not a valid transport type on line %d of sip.conf. defaulting to udp.\n", line, lineno);
	} else {
		*hostname = line;
		*transport = SIP_TRANSPORT_UDP;
	}

	if ((line = strrchr(*hostname, '@')))
		line++;
	else
		line = *hostname;

	if ((port = strrchr(line, ':'))) {
		*port++ = '\0';

		if (!sscanf(port, "%5u", portnum)) {
			ast_log(LOG_NOTICE, "'%s' is not a valid port number on line %d of sip.conf. using default.\n", port, lineno);
			port = NULL;
		}
	}

	if (!port) {
		if (*transport & SIP_TRANSPORT_TLS) {
			*portnum = STANDARD_TLS_PORT;
		} else {
			*portnum = STANDARD_SIP_PORT;
		}
	}

	return 0;
}

/*!
 * \brief Get cached MWI info
 * \retval 0 At least one message is waiting
 * \retval 1 no messages waiting
 */
static int get_cached_mwi(struct sip_peer *peer, int *new, int *old)
{
	struct sip_mailbox *mailbox;

	AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
		struct ast_event *event;
		event = ast_event_get_cached(AST_EVENT_MWI,
			AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
			AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
			AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_EXISTS,
			AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_EXISTS,
			AST_EVENT_IE_END);
		if (!event)
			continue;
		*new += ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
		*old += ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
		ast_event_destroy(event);
	}

	return (*new || *old) ? 0 : 1;
}

/*! \brief Send message waiting indication to alert peer that they've got voicemail */
static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only)
{
	/* Called with peerl lock, but releases it */
	struct sip_pvt *p;
	int newmsgs = 0, oldmsgs = 0;

	if (ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY) && !peer->mwipvt)
		return 0;

	/* Do we have an IP address? If not, skip this peer */
	if (!peer->addr.sin_addr.s_addr && !peer->defaddr.sin_addr.s_addr) 
		return 0;

	if (event) {
		newmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
		oldmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
	} else if (!get_cached_mwi(peer, &newmsgs, &oldmsgs)) {
		/* got it!  Don't keep looking. */
	} else if (cache_only) {
		return 0;
	} else { /* Fall back to manually checking the mailbox */
		struct ast_str *mailbox_str = ast_str_alloca(512);
		peer_mailboxes_to_str(&mailbox_str, peer);
		ast_app_inboxcount(mailbox_str->str, &newmsgs, &oldmsgs);
	}

	if (peer->mwipvt) {
		/* Base message on subscription */
		p = peer->mwipvt;
	} else {
		/* Build temporary dialog for this message */
		if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) 
			return -1;
		if (create_addr_from_peer(p, peer)) {
			/* Maybe they're not registered, etc. */
			dialog_cleanup_and_destroy(p); /*sip_destroy(p);*/
			return 0;
		}
		/* Recalculate our side, and recalculate Call ID */
		ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
		build_via(p);
		build_callid_pvt(p);
		/* Destroy this session after 32 secs */
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
	}

	/* Send MWI */
	ast_set_flag(&p->flags[0], SIP_OUTGOING);
	transmit_notify_with_mwi(p, newmsgs, oldmsgs, peer->vmexten);

	return 0;
}

/*! \brief helper function for the monitoring thread */
static void check_rtp_timeout(struct sip_pvt *dialog, time_t t)
{
	/* If we have no RTP or no active owner, no need to check timers */
	if (!dialog->rtp || !dialog->owner)
		return;
	/* If the call is not in UP state or redirected outside Asterisk, no need to check timers */
	if (dialog->owner->_state != AST_STATE_UP || dialog->redirip.sin_addr.s_addr)
		return;

	/* If the call is involved in a T38 fax session do not check RTP timeout */
	if (dialog->t38.state == T38_ENABLED)
		return;

	/* If we have no timers set, return now */
	if ((ast_rtp_get_rtpkeepalive(dialog->rtp) == 0) && (ast_rtp_get_rtptimeout(dialog->rtp) == 0) && (ast_rtp_get_rtpholdtimeout(dialog->rtp) == 0))
		return;

	/* Check AUDIO RTP keepalives */
	if (dialog->lastrtptx && ast_rtp_get_rtpkeepalive(dialog->rtp) &&
		    (t > dialog->lastrtptx + ast_rtp_get_rtpkeepalive(dialog->rtp))) {
		/* Need to send an empty RTP packet */
		dialog->lastrtptx = time(NULL);
		ast_rtp_sendcng(dialog->rtp, 0);
	}

	/*! \todo Check video RTP keepalives

		Do we need to move the lastrtptx to the RTP structure to have one for audio and one
		for video? It really does belong to the RTP structure.
	*/

	/* Check AUDIO RTP timers */
	if (dialog->lastrtprx && (ast_rtp_get_rtptimeout(dialog->rtp) || ast_rtp_get_rtpholdtimeout(dialog->rtp)) &&
		    (t > dialog->lastrtprx + ast_rtp_get_rtptimeout(dialog->rtp))) {

		/* Might be a timeout now -- see if we're on hold */
		struct sockaddr_in sin;
		ast_rtp_get_peer(dialog->rtp, &sin);
		if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD) || (ast_rtp_get_rtpholdtimeout(dialog->rtp) &&
		     (t > dialog->lastrtprx + ast_rtp_get_rtpholdtimeout(dialog->rtp)))) {
			/* Needs a hangup */
			if (ast_rtp_get_rtptimeout(dialog->rtp)) {
				while (dialog->owner && ast_channel_trylock(dialog->owner)) {
					sip_pvt_unlock(dialog);
					usleep(1);
					sip_pvt_lock(dialog);
				}
				ast_log(LOG_NOTICE, "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
					dialog->owner->name, (long) (t - dialog->lastrtprx));
				/* Issue a softhangup */
				ast_softhangup_nolock(dialog->owner, AST_SOFTHANGUP_DEV);
				ast_channel_unlock(dialog->owner);
				/* forget the timeouts for this call, since a hangup
				   has already been requested and we don't want to
				   repeatedly request hangups
				*/
				ast_rtp_set_rtptimeout(dialog->rtp, 0);
				ast_rtp_set_rtpholdtimeout(dialog->rtp, 0);
				if (dialog->vrtp) {
					ast_rtp_set_rtptimeout(dialog->vrtp, 0);
					ast_rtp_set_rtpholdtimeout(dialog->vrtp, 0);
				}
			}
		}
	}
}

/*! \brief The SIP monitoring thread 
\note	This thread monitors all the SIP sessions and peers that needs notification of mwi
	(and thus do not have a separate thread) indefinitely 
*/
static void *do_monitor(void *data)
{
	int res;
	struct sip_pvt *dialog;
	time_t t;
	int reloading;

	/* Add an I/O event to our SIP UDP socket */
	if (sipsock > -1) 
		sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
	
	/* From here on out, we die whenever asked */
	for(;;) {
		/* Check for a reload request */
		ast_mutex_lock(&sip_reload_lock);
		reloading = sip_reloading;
		sip_reloading = FALSE;
		ast_mutex_unlock(&sip_reload_lock);
		if (reloading) {
			ast_verb(1, "Reloading SIP\n");
			sip_do_reload(sip_reloadreason);

			/* Change the I/O fd of our UDP socket */
			if (sipsock > -1) {
				if (sipsock_read_id)
					sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
				else
					sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
			} else if (sipsock_read_id) {
				ast_io_remove(io, sipsock_read_id);
				sipsock_read_id = NULL;
			}
		}

restartsearch:		
		/* Check for dialogs needing to be killed */
		dialoglist_lock();
		t = time(NULL);
		/* don't scan the dialogs list if it hasn't been a reasonable period
		   of time since the last time we did it (when MWI is being sent, we can
		   get back to this point every millisecond or less)
		*/
		for (dialog = dialoglist; dialog; dialog = dialog->next) {
			if (sip_pvt_trylock(dialog)) {
				dialoglist_unlock();
				usleep(1);
				goto restartsearch;
			}

			/* Check RTP timeouts and kill calls if we have a timeout set and do not get RTP */
			check_rtp_timeout(dialog, t);
			/* If we have sessions that needs to be destroyed, do it now */
			/* Check if we have outstanding requests not responsed to or an active call
				- if that's the case, wait with destruction */
			if (dialog->needdestroy && !dialog->packets && !dialog->owner) {
				sip_pvt_unlock(dialog);
				dialog_cleanup_and_destroy(dialog); /* __sip_destroy(dialog, TRUE, FALSE); */
				dialoglist_unlock();
				usleep(1);
				goto restartsearch;
			}
			sip_pvt_unlock(dialog);
		}
		dialoglist_unlock();

		pthread_testcancel();
		/* Wait for sched or io */
		res = ast_sched_wait(sched);
		if ((res < 0) || (res > 1000))
			res = 1000;
		res = ast_io_wait(io, res);
		if (res > 20)
			ast_debug(1, "chan_sip: ast_io_wait ran %d all at once\n", res);
		ast_mutex_lock(&monlock);
		if (res >= 0)  {
			res = ast_sched_runq(sched);
			if (res >= 20)
				ast_debug(1, "chan_sip: ast_sched_runq ran %d all at once\n", res);
		}
		ast_mutex_unlock(&monlock);
	}

	/* Never reached */
	return NULL;
}

/*! \brief Start the channel monitor thread */
static int restart_monitor(void)
{
	/* If we're supposed to be stopped -- stay stopped */
	if (monitor_thread == AST_PTHREADT_STOP)
		return 0;
	ast_mutex_lock(&monlock);
	if (monitor_thread == pthread_self()) {
		ast_mutex_unlock(&monlock);
		ast_log(LOG_WARNING, "Cannot kill myself\n");
		return -1;
	}
	if (monitor_thread != AST_PTHREADT_NULL) {
		/* Wake up the thread */
		pthread_kill(monitor_thread, SIGURG);
	} else {
		/* Start a new monitor */
		if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
			ast_mutex_unlock(&monlock);
			ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
			return -1;
		}
	}
	ast_mutex_unlock(&monlock);
	return 0;
}


/*! \brief Session-Timers: Restart session timer */
static void restart_session_timer(struct sip_pvt *p)
{
	if (!p->stimer) {
		ast_log(LOG_WARNING, "Null stimer in restart_session_timer - %s\n", p->callid);
		return;
	}

	if (p->stimer->st_active == TRUE) {
		AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid, dialog_unref(p));
		if (p->stimer->st_schedid != -1) {
			ast_log(LOG_WARNING, "ast_sched_del failed: %d - %s\n", p->stimer->st_schedid, p->callid);
		}

		ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
		start_session_timer(p);
	}
}


/*! \brief Session-Timers: Stop session timer */
static void stop_session_timer(struct sip_pvt *p)
{
	if (!p->stimer) {
		ast_log(LOG_WARNING, "Null stimer in stop_session_timer - %s\n", p->callid);
		return;
	}

	if (p->stimer->st_active == TRUE) {
		p->stimer->st_active = FALSE;
		AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid, dialog_unref(p));
		ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
	}
}


/*! \brief Session-Timers: Start session timer */
static void start_session_timer(struct sip_pvt *p)
{
	if (!p->stimer) {
		ast_log(LOG_WARNING, "Null stimer in start_session_timer - %s\n", p->callid);
		return;
	}

	p->stimer->st_schedid = ast_sched_add(sched, p->stimer->st_interval * 1000 / 2, proc_session_timer, dialog_ref(p));
	if (p->stimer->st_schedid < 0) {
		dialog_unref(p); /* removing dialog ref for session timer */
		ast_log(LOG_ERROR, "ast_sched_add failed.\n");
	}

	ast_debug(2, "Session timer started: %d - %s\n", p->stimer->st_schedid, p->callid);
}


/*! \brief Session-Timers: Process session refresh timeout event */
static int proc_session_timer(const void *vp)
{
	struct sip_pvt *p = (struct sip_pvt *) vp;
	int sendreinv = FALSE;
	int res = 0;

	if (!p->stimer) {
		ast_log(LOG_WARNING, "Null stimer in proc_session_timer - %s\n", p->callid);
		goto return_unref;
	}

	ast_debug(2, "Session timer expired: %d - %s\n", p->stimer->st_schedid, p->callid);

	if (!p->owner) {
		goto return_unref;
	}

	if ((p->stimer->st_active != TRUE) || (p->owner->_state != AST_STATE_UP)) {
		goto return_unref;
	}

	switch (p->stimer->st_ref) {
	case SESSION_TIMER_REFRESHER_UAC:
		if (p->outgoing_call == TRUE) {
			sendreinv = TRUE;
		}
		break;
	case SESSION_TIMER_REFRESHER_UAS:
		if (p->outgoing_call != TRUE) {
			sendreinv = TRUE;
		}
		break;
	default:
		ast_log(LOG_ERROR, "Unknown session refresher %d\n", p->stimer->st_ref);
		goto return_unref;
	}

	if (sendreinv == TRUE) {
		res = 1;
		transmit_reinvite_with_sdp(p, FALSE, TRUE);
	} else {
		p->stimer->st_expirys++;
		if (p->stimer->st_expirys >= 2) {
			if (p->stimer->quit_flag) {
				goto return_unref;
			}
			ast_log(LOG_WARNING, "Session-Timer expired - %s\n", p->callid);
			sip_pvt_lock(p);
			while (p->owner && ast_channel_trylock(p->owner)) {
				sip_pvt_unlock(p);
				usleep(1);
				if (p->stimer && p->stimer->quit_flag) {
					goto return_unref;
				}
				sip_pvt_lock(p);
			}

			ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
			ast_channel_unlock(p->owner);
			sip_pvt_unlock(p);
		}
	}
return_unref:
	if (!res) {
		/* An error occurred.  Stop session timer processing */
		if (p->stimer) {
			p->stimer->st_schedid = -1; /* this is the sched, so this is safe */
			stop_session_timer(p); /* will not unref, only mark st_active FALSE */
		}

		/* If we are not asking to be rescheduled, then we need to release our
		 * reference to the dialog. */
		dialog_unref(p);
	}
	return res;
}


/*! \brief Session-Timers: Function for parsing Min-SE header */
int parse_minse (const char *p_hdrval, int *const p_interval)
{
	if (ast_strlen_zero(p_hdrval)) {
		ast_log(LOG_WARNING, "Null Min-SE header\n");
		return -1;
	}

	*p_interval = 0;
	p_hdrval = ast_skip_blanks(p_hdrval);
	if (!sscanf(p_hdrval, "%30d", p_interval)) {
		ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
		return -1;
	}

	ast_debug(2, "Received Min-SE: %d\n", *p_interval);
	return 0;
}


/*! \brief Session-Timers: Function for parsing Session-Expires header */
int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref)
{
	char *p_token;
	int  ref_idx;
	char *p_se_hdr;

	if (ast_strlen_zero(p_hdrval)) {
		ast_log(LOG_WARNING, "Null Session-Expires header\n");
		return -1;
	}

	*p_ref = SESSION_TIMER_REFRESHER_AUTO;
	*p_interval = 0;

	p_se_hdr = ast_strdupa(p_hdrval);
	p_se_hdr = ast_skip_blanks(p_se_hdr);

	while ((p_token = strsep(&p_se_hdr, ";"))) {
		p_token = ast_skip_blanks(p_token);
		if (!sscanf(p_token, "%30d", p_interval)) {
			ast_log(LOG_WARNING, "Parsing of Session-Expires failed\n");
			return -1;
		}

		ast_debug(2, "Session-Expires: %d\n", *p_interval);

		if (!p_se_hdr)
			continue;

		p_se_hdr = ast_skip_blanks(p_se_hdr);
		ref_idx = strlen("refresher=");
		if (!strncasecmp(p_se_hdr, "refresher=", ref_idx)) {
			p_se_hdr += ref_idx;
			p_se_hdr = ast_skip_blanks(p_se_hdr);

			if (!strncasecmp(p_se_hdr, "uac", strlen("uac"))) {
				*p_ref = SESSION_TIMER_REFRESHER_UAC;
				ast_debug(2, "Refresher: UAC\n");
			} else if (!strncasecmp(p_se_hdr, "uas", strlen("uas"))) {
				*p_ref = SESSION_TIMER_REFRESHER_UAS;
				ast_debug(2, "Refresher: UAS\n");
			} else {
				ast_log(LOG_WARNING, "Invalid refresher value %s\n", p_se_hdr);
				return -1;
			}
			break;
		}
	}
	return 0;
}


/*! \brief Handle 422 response to INVITE with session-timer requested

   Session-Timers:   An INVITE originated by Asterisk that asks for session-timers support
   from the UAS can result into a 422 response. This is how a UAS or an intermediary proxy 
   server tells Asterisk that the session refresh interval offered by Asterisk is too low 
   for them.  The proc_422_rsp() function handles a 422 response.  It extracts the Min-SE 
   header that comes back in 422 and sends a new INVITE accordingly. */
static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp)
{
	int rtn;
	const char *p_hdrval;
	int minse;

	p_hdrval = get_header(rsp, "Min-SE");
	if (ast_strlen_zero(p_hdrval)) {
		ast_log(LOG_WARNING, "422 response without a Min-SE header %s\n", p_hdrval);
		return;
	}
	rtn = parse_minse(p_hdrval, &minse);
	if (rtn != 0) {
		ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
		return;
	}
	p->stimer->st_interval = minse;
	transmit_invite(p, SIP_INVITE, 1, 2); 
}


/*! \brief Get Max or Min SE (session timer expiry)
 * \param p pointer to the SIP dialog 
 * \param max if true, get max se, otherwise min se
*/
int st_get_se(struct sip_pvt *p, int max)
{
	if (max == TRUE) {
		if (p->stimer->st_cached_max_se) {
			return p->stimer->st_cached_max_se;
		} else {
			if (p->username) {
				struct sip_user *up = find_user(p->username, 1);
				if (up) {
					p->stimer->st_cached_max_se = up->stimer.st_max_se;
					unref_user(up);
					return (p->stimer->st_cached_max_se);
				}
			} 
			if (p->peername) {
				struct sip_peer *pp = find_peer(p->peername, NULL, 1, 0, 0);
				if (pp) {
					p->stimer->st_cached_max_se = pp->stimer.st_max_se;
					unref_peer(pp);
					return (p->stimer->st_cached_max_se);
				}
			}
		}
		p->stimer->st_cached_max_se = global_max_se;
		return (p->stimer->st_cached_max_se);
	} else {
		if (p->stimer->st_cached_min_se) {
			return p->stimer->st_cached_min_se;
		} else {
			if (p->username) {
				struct sip_user *up = find_user(p->username, 1);
				if (up) {
					p->stimer->st_cached_min_se = up->stimer.st_min_se;
					unref_user(up);
					return (p->stimer->st_cached_min_se);
				}
			} 
			if (p->peername) {
				struct sip_peer *pp = find_peer(p->peername, NULL, 1, 0, 0);
				if (pp) {
					p->stimer->st_cached_min_se = pp->stimer.st_min_se;
					unref_peer(pp);
					return (p->stimer->st_cached_min_se);
				}
			}
		}
		p->stimer->st_cached_min_se = global_min_se;
		return (p->stimer->st_cached_min_se);
	}
}


/*! \brief Get the entity (UAC or UAS) that's acting as the session-timer refresher 
 * \param p pointer to the SIP dialog 
*/
enum st_refresher st_get_refresher(struct sip_pvt *p)
{
	if (p->stimer->st_cached_ref != SESSION_TIMER_REFRESHER_AUTO) 
		return p->stimer->st_cached_ref;

	if (p->username) {
		struct sip_user *up = find_user(p->username, 1);
		if (up) {
			p->stimer->st_cached_ref = up->stimer.st_ref;
			return up->stimer.st_ref;
		}
	} 

	if (p->peername) {
		struct sip_peer *pp = find_peer(p->peername, NULL, 1, 0, 0);
		if (pp) {
			p->stimer->st_cached_ref = pp->stimer.st_ref;
			return pp->stimer.st_ref;
		}
	}
	
	p->stimer->st_cached_ref = global_st_refresher;
	return global_st_refresher;
}


/*! \brief Get the session-timer mode 
 * \param p pointer to the SIP dialog 
*/
enum st_mode st_get_mode(struct sip_pvt *p)
{
	if (!p->stimer) 
		sip_st_alloc(p);

	if (p->stimer->st_cached_mode != SESSION_TIMER_MODE_INVALID) 
		return p->stimer->st_cached_mode;

	if (p->username) {
		struct sip_user *up = find_user(p->username, 1);
		if (up) {
			p->stimer->st_cached_mode = up->stimer.st_mode_oper;
			unref_user(up);
			return p->stimer->st_cached_mode;
		}
	} 
	if (p->peername) {
		struct sip_peer *pp = find_peer(p->peername, NULL, 1, 0, 0);
		if (pp) {
			p->stimer->st_cached_mode = pp->stimer.st_mode_oper;
			unref_peer(pp);
			return p->stimer->st_cached_mode;
		}
	}

	p->stimer->st_cached_mode = global_st_mode;
	return global_st_mode;
}


/*! \brief React to lack of answer to Qualify poke */
static int sip_poke_noanswer(const void *data)
{
	struct sip_peer *peer = (struct sip_peer *)data;
	
	peer->pokeexpire = -1;
	if (peer->lastms > -1) {
		ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE!  Last qualify: %d\n", peer->name, peer->lastms);
		if (sip_cfg.peer_rtupdate) {
			ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", "-1", NULL);
		}
		manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
		if (global_regextenonqualify) {
			register_peer_exten(peer, FALSE);
		}
	}
	if (peer->call) {
		dialog_cleanup_and_destroy(peer->call);
		peer->call = NULL; /*sip_destroy(peer->call);*/
	}
	peer->lastms = -1;
	ast_device_state_changed("SIP/%s", peer->name);
	/* Try again quickly */
	AST_SCHED_REPLACE(peer->pokeexpire, sched, 
		DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer);
	return 0;
}

/*! \brief Check availability of peer, also keep NAT open
\note	This is done with the interval in qualify= configuration option
	Default is 2 seconds */
static int sip_poke_peer(struct sip_peer *peer)
{
	struct sip_pvt *p;
	int xmitres = 0;

	if (!peer->maxms || !peer->addr.sin_addr.s_addr) {
		/* IF we have no IP, or this isn't to be monitored, return
		  immediately after clearing things out */
		AST_SCHED_DEL(sched, peer->pokeexpire);
		peer->lastms = 0;
		peer->call = NULL;
		return 0;
	}
	if (peer->call) {
		if (sipdebug)
			ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
		dialog_cleanup_and_destroy(peer->call);
		peer->call = NULL; /*sip_destroy(peer->call);*/
	}
	if (!(p = peer->call = sip_alloc(NULL, NULL, 0, SIP_OPTIONS, NULL)))
		return -1;
	
	p->sa = peer->addr;
	p->recv = peer->addr;
	copy_socket_data(&p->socket, &peer->socket);
	ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
	ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);

	/* Send OPTIONs to peer's fullcontact */
	if (!ast_strlen_zero(peer->fullcontact))
		ast_string_field_set(p, fullcontact, peer->fullcontact);

	if (!ast_strlen_zero(peer->tohost))
		ast_string_field_set(p, tohost, peer->tohost);
	else
		ast_string_field_set(p, tohost, ast_inet_ntoa(peer->addr.sin_addr));

	/* Recalculate our side, and recalculate Call ID */
	ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
	build_via(p);
	build_callid_pvt(p);

	AST_SCHED_DEL(sched, peer->pokeexpire);
	p->relatedpeer = peer;
	ast_set_flag(&p->flags[0], SIP_OUTGOING);
#ifdef VOCAL_DATA_HACK
	ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
	xmitres = transmit_invite(p, SIP_INVITE, 0, 2);
#else
	xmitres = transmit_invite(p, SIP_OPTIONS, 0, 2);
#endif
	peer->ps = ast_tvnow();
	if (xmitres == XMIT_ERROR)
		sip_poke_noanswer(peer);	/* Immediately unreachable, network problems */
	else {
		AST_SCHED_REPLACE(peer->pokeexpire, sched, 
			peer->maxms * 2, sip_poke_noanswer, peer);
	}

	return 0;
}

/*! \brief Part of PBX channel interface
\note
\par	Return values:---

	If we have qualify on and the device is not reachable, regardless of registration
	state we return AST_DEVICE_UNAVAILABLE

	For peers with call limit:
		- not registered			AST_DEVICE_UNAVAILABLE
		- registered, no call			AST_DEVICE_NOT_INUSE
		- registered, active calls		AST_DEVICE_INUSE
		- registered, call limit reached	AST_DEVICE_BUSY
		- registered, onhold			AST_DEVICE_ONHOLD
		- registered, ringing			AST_DEVICE_RINGING

	For peers without call limit:
		- not registered			AST_DEVICE_UNAVAILABLE
		- registered				AST_DEVICE_NOT_INUSE
		- fixed IP (!dynamic)			AST_DEVICE_NOT_INUSE
	
	Peers that does not have a known call and can't be reached by OPTIONS
		- unreachable				AST_DEVICE_UNAVAILABLE

	If we return AST_DEVICE_UNKNOWN, the device state engine will try to find
	out a state by walking the channel list.

	The queue system (\ref app_queue.c) treats a member as "active"
	if devicestate is != AST_DEVICE_UNAVAILBALE && != AST_DEVICE_INVALID

	When placing a call to the queue member, queue system sets a member to busy if
	!= AST_DEVICE_NOT_INUSE and != AST_DEVICE_UNKNOWN

*/
static int sip_devicestate(void *data)
{
	char *host;
	char *tmp;
	struct sip_peer *p;

	int res = AST_DEVICE_INVALID;

	/* make sure data is not null. Maybe unnecessary, but better be safe */
	host = ast_strdupa(data ? data : "");
	if ((tmp = strchr(host, '@')))
		host = tmp + 1;

	ast_debug(3, "Checking device state for peer %s\n", host);

	/* If find_peer asks for a realtime peer, then this breaks rtautoclear.  This
	 * is because when a peer tries to autoexpire, the last thing it does is to
	 * queue up an event telling the system that the devicestate has changed
	 * (presumably to unavailable).  If we ask for a realtime peer here, this would
	 * load it BACK into memory, thus defeating the point of trying to clear dead
	 * hosts out of memory.
	 */
	if ((p = find_peer(host, NULL, 0, 1, 0))) {
		if (p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) {
			/* we have an address for the peer */
		
			/* Check status in this order
				- Hold
				- Ringing
				- Busy (enforced only by call limit)
				- Inuse (we have a call)
				- Unreachable (qualify)
			   If we don't find any of these state, report AST_DEVICE_NOT_INUSE
			   for registered devices */

			if (p->onHold)
				/* First check for hold or ring states */
				res = AST_DEVICE_ONHOLD;
			else if (p->inRinging) {
				if (p->inRinging == p->inUse)
					res = AST_DEVICE_RINGING;
				else
					res = AST_DEVICE_RINGINUSE;
			} else if (p->call_limit && (p->inUse == p->call_limit))
				/* check call limit */
				res = AST_DEVICE_BUSY;
			else if (p->call_limit && p->busy_level && p->inUse >= p->busy_level)
				/* We're forcing busy before we've reached the call limit */
				res = AST_DEVICE_BUSY;
			else if (p->call_limit && p->inUse)
				/* Not busy, but we do have a call */
				res = AST_DEVICE_INUSE;
			else if (p->maxms && ((p->lastms > p->maxms) || (p->lastms < 0))) 
				/* We don't have a call. Are we reachable at all? Requires qualify= */
				res = AST_DEVICE_UNAVAILABLE;
			else	/* Default reply if we're registered and have no other data */
				res = AST_DEVICE_NOT_INUSE;
		} else {
			/* there is no address, it's unavailable */
			res = AST_DEVICE_UNAVAILABLE;
		}
		unref_peer(p);
	} else {
		res = AST_DEVICE_UNKNOWN;
	}

	return res;
}

/*! \brief PBX interface function -build SIP pvt structure 
 *	SIP calls initiated by the PBX arrive here. 
 *
 * \verbatim	
 * 	SIP Dial string syntax
 *		SIP/exten@host!dnid
 *	or	SIP/host/exten!dnid
 *	or	SIP/host!dnid
 * \endverbatim
*/
static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause)
{
	struct sip_pvt *p;
	struct ast_channel *tmpc = NULL;
	char *ext = NULL, *host;
	char tmp[256];
	char *dest = data;
	char *dnid;
 	char *secret = NULL;
 	char *md5secret = NULL;
 	char *authname = NULL;
	char *trans = NULL;
	enum sip_transport transport = 0;
	int oldformat = format;

	/* mask request with some set of allowed formats.
	 * XXX this needs to be fixed.
	 * The original code uses AST_FORMAT_AUDIO_MASK, but it is
	 * unclear what to use here. We have global_capabilities, which is
	 * configured from sip.conf, and sip_tech.capabilities, which is
	 * hardwired to all audio formats.
	 */
	format &= AST_FORMAT_AUDIO_MASK;
	if (!format) {
		ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format %s while capability is %s\n", ast_getformatname(oldformat), ast_getformatname(global_capability));
		*cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;	/* Can't find codec to connect to host */
		return NULL;
	}
	ast_debug(1, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), oldformat));

	if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE, NULL))) {
		ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", dest);
		*cause = AST_CAUSE_SWITCH_CONGESTION;
		return NULL;
	}

	p->outgoing_call = TRUE;

	if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
		dialog_cleanup_and_destroy(p); /*sip_destroy(p);*/
		ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
		*cause = AST_CAUSE_SWITCH_CONGESTION;
		return NULL;
	}

	/* Save the destination, the SIP dial string */
	ast_copy_string(tmp, dest, sizeof(tmp));


	/* Find DNID and take it away */
	dnid = strchr(tmp, '!');
	if (dnid != NULL) {
		*dnid++ = '\0';
		ast_string_field_set(p, todnid, dnid);
	}

	/* Find at sign - @ */
	host = strchr(tmp, '@');
	if (host) {
		*host++ = '\0';
		ext = tmp;
		secret = strchr(ext, ':');
	}
	if (secret) {
		*secret++ = '\0';
		md5secret = strchr(secret, ':');
	}
	if (md5secret) {
		*md5secret++ = '\0';
		authname = strchr(md5secret, ':');
	}
	if (authname) {
		*authname++ = '\0';
		trans = strchr(authname, ':');
	}
	if (trans) {
		*trans++ = '\0';
		if (!strcasecmp(trans, "tcp"))
			transport = SIP_TRANSPORT_TCP;
		else if (!strcasecmp(trans, "tls"))
			transport = SIP_TRANSPORT_TLS;
		else {
			if (strcasecmp(trans, "udp"))
				ast_log(LOG_WARNING, "'%s' is not a valid transport option to Dial() for SIP calls, using udp by default.\n", trans);
			transport = SIP_TRANSPORT_UDP;
		}
	} else { /* use default */
		transport = SIP_TRANSPORT_UDP;
	}

	if (!host) {
		ext = strchr(tmp, '/');
		if (ext) 
			*ext++ = '\0';
		host = tmp;
	}

	set_socket_transport(&p->socket, transport);

	/* We now have 
		host = peer name, DNS host name or DNS domain (for SRV) 
		ext = extension (user part of URI)
		dnid = destination of the call (applies to the To: header)
	*/
	if (create_addr(p, host, 1)) {
		*cause = AST_CAUSE_UNREGISTERED;
		ast_debug(3, "Cant create SIP call - target device not registered\n");
		dialog_cleanup_and_destroy(p); /*sip_destroy(p);*/
		return NULL;
	}
	if (ast_strlen_zero(p->peername) && ext)
		ast_string_field_set(p, peername, ext);
	/* Recalculate our side, and recalculate Call ID */
	ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
	build_via(p);
	build_callid_pvt(p);

	/* We have an extension to call, don't use the full contact here */
	/* This to enable dialing registered peers with extension dialling,
	   like SIP/peername/extension 	
	   SIP/peername will still use the full contact 
	 */
	if (ext) {
		ast_string_field_set(p, username, ext);
		ast_string_field_set(p, fullcontact, NULL);
	}
	if (secret && !ast_strlen_zero(secret))
		ast_string_field_set(p, peersecret, secret);

	if (md5secret && !ast_strlen_zero(md5secret))
		ast_string_field_set(p, peermd5secret, md5secret);

	if (authname && !ast_strlen_zero(authname))
		ast_string_field_set(p, authname, authname);
#if 0
	printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
#endif
	p->prefcodec = oldformat;				/* Format for this call */
	p->jointcapability = oldformat;
	sip_pvt_lock(p);
	tmpc = sip_new(p, AST_STATE_DOWN, host);	/* Place the call */
	if (global_callevents)
		manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
			"Channel: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
			p->owner? p->owner->name : "", "SIP", p->callid, p->fullcontact, p->peername);
	sip_pvt_unlock(p);
	if (!tmpc) {
		dialog_cleanup_and_destroy(p); /* sip_destroy(p); */
	}
	ast_update_use_count();
	restart_monitor();
	return tmpc;
}

/*! \brief Parse insecure= setting in sip.conf and set flags according to setting */
static void set_insecure_flags (struct ast_flags *flags, const char *value, int lineno)
{
	if (ast_strlen_zero(value))
		return;

	if (!ast_false(value)) {
		char buf[64];
		char *word, *next;

		ast_copy_string(buf, value, sizeof(buf));
		next = buf;
		while ((word = strsep(&next, ","))) {
			if (!strcasecmp(word, "port"))
				ast_set_flag(&flags[0], SIP_INSECURE_PORT);
			else if (!strcasecmp(word, "invite"))
				ast_set_flag(&flags[0], SIP_INSECURE_INVITE);
			else
				ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", value, lineno);
		}
	}
}

/*!
  \brief Handle T.38 configuration options common to users and peers
  \returns non-zero if any config options were handled, zero otherwise
*/
static int handle_t38_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v,
			      int *maxdatagram)
{
	int res = 1;

	if (!strcasecmp(v->name, "t38pt_udptl")) {
		char *buf = ast_strdupa(v->value);
		char *word, *next = buf;

		ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT);

		while ((word = strsep(&next, ","))) {
			if (ast_true(word) || !strcasecmp(word, "fec")) {
				ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
				ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_FEC);
			} else if (!strcasecmp(word, "redundancy")) {
				ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
				ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY);
			} else if (!strcasecmp(word, "none")) {
				ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
				ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
			} else if (!strncasecmp(word, "maxdatagram=", 12)) {
				if (sscanf(&word[12], "%30u", maxdatagram) != 1) {
					ast_log(LOG_WARNING, "Invalid maxdatagram '%s' at line %d of %s\n", v->value, v->lineno, config);
					*maxdatagram = global_t38_maxdatagram;
				}
			}
		}
	} else {
		res = 0;
	}

	return res;
}

/*!
  \brief Handle flag-type options common to configuration of devices - users and peers
  \param flags array of two struct ast_flags
  \param mask array of two struct ast_flags
  \param v linked list of config variables to process
  \returns non-zero if any config options were handled, zero otherwise
*/
static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
{
	int res = 1;

	if (!strcasecmp(v->name, "trustrpid")) {
		ast_set_flag(&mask[0], SIP_TRUSTRPID);
		ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
	} else if (!strcasecmp(v->name, "sendrpid")) {
		ast_set_flag(&mask[0], SIP_SENDRPID);
		ast_set2_flag(&flags[0], ast_true(v->value), SIP_SENDRPID);
	} else if (!strcasecmp(v->name, "g726nonstandard")) {
		ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
		ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
	} else if (!strcasecmp(v->name, "useclientcode")) {
		ast_set_flag(&mask[0], SIP_USECLIENTCODE);
		ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
	} else if (!strcasecmp(v->name, "dtmfmode")) {
		ast_set_flag(&mask[0], SIP_DTMF);
		ast_clear_flag(&flags[0], SIP_DTMF);
		if (!strcasecmp(v->value, "inband"))
			ast_set_flag(&flags[0], SIP_DTMF_INBAND);
		else if (!strcasecmp(v->value, "rfc2833"))
			ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
		else if (!strcasecmp(v->value, "info"))
			ast_set_flag(&flags[0], SIP_DTMF_INFO);
		else if (!strcasecmp(v->value, "shortinfo"))
			ast_set_flag(&flags[0], SIP_DTMF_SHORTINFO);
		else if (!strcasecmp(v->value, "auto"))
			ast_set_flag(&flags[0], SIP_DTMF_AUTO);
		else {
			ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
			ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
		}
	} else if (!strcasecmp(v->name, "nat")) {
		ast_set_flag(&mask[0], SIP_NAT);
		ast_clear_flag(&flags[0], SIP_NAT);
		if (!strcasecmp(v->value, "never"))
			ast_set_flag(&flags[0], SIP_NAT_NEVER);
		else if (!strcasecmp(v->value, "route"))
			ast_set_flag(&flags[0], SIP_NAT_ROUTE);
		else if (ast_true(v->value))
			ast_set_flag(&flags[0], SIP_NAT_ALWAYS);
		else
			ast_set_flag(&flags[0], SIP_NAT_RFC3581);
	} else if (!strcasecmp(v->name, "canreinvite")) {
		ast_set_flag(&mask[0], SIP_REINVITE);
		ast_clear_flag(&flags[0], SIP_REINVITE);
		if (ast_true(v->value)) {
			ast_set_flag(&flags[0], SIP_CAN_REINVITE | SIP_CAN_REINVITE_NAT);
		} else if (!ast_false(v->value)) {
			char buf[64];
			char *word, *next = buf;

			ast_copy_string(buf, v->value, sizeof(buf));
			while ((word = strsep(&next, ","))) {
				if (!strcasecmp(word, "update")) {
					ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_CAN_REINVITE);
				} else if (!strcasecmp(word, "nonat")) {
					ast_set_flag(&flags[0], SIP_CAN_REINVITE);
					ast_clear_flag(&flags[0], SIP_CAN_REINVITE_NAT);
				} else {
					ast_log(LOG_WARNING, "Unknown canreinvite mode '%s' on line %d\n", v->value, v->lineno);
				}
			}
		}
	} else if (!strcasecmp(v->name, "insecure")) {
		ast_set_flag(&mask[0], SIP_INSECURE);
		ast_clear_flag(&flags[0], SIP_INSECURE);
		set_insecure_flags(&flags[0], v->value, v->lineno);	
	} else if (!strcasecmp(v->name, "progressinband")) {
		ast_set_flag(&mask[0], SIP_PROG_INBAND);
		ast_clear_flag(&flags[0], SIP_PROG_INBAND);
		if (ast_true(v->value))
			ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
		else if (strcasecmp(v->value, "never"))
			ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
	} else if (!strcasecmp(v->name, "promiscredir")) {
		ast_set_flag(&mask[0], SIP_PROMISCREDIR);
		ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
	} else if (!strcasecmp(v->name, "videosupport")) {
		ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
		ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
	} else if (!strcasecmp(v->name, "textsupport")) {
		ast_set_flag(&mask[1], SIP_PAGE2_TEXTSUPPORT);
		ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_TEXTSUPPORT);
		res = 1;
	} else if (!strcasecmp(v->name, "allowoverlap")) {
		ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
		ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWOVERLAP);
	} else if (!strcasecmp(v->name, "allowsubscribe")) {
		ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
		ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
	} else if (!strcasecmp(v->name, "ignoresdpversion")) {
		ast_set_flag(&mask[1], SIP_PAGE2_IGNORESDPVERSION);
		ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_IGNORESDPVERSION);
	} else if (!strcasecmp(v->name, "rfc2833compensate")) {
		ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
		ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
	} else if (!strcasecmp(v->name, "buggymwi")) {
		ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
		ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
	} else if (!strcasecmp(v->name, "t38pt_usertpsource")) {
		ast_set_flag(&mask[1], SIP_PAGE2_UDPTL_DESTINATION);
		ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_UDPTL_DESTINATION);
	} else if (!strcasecmp(v->name, "faxdetect")) {
                ast_set_flag(&mask[1], SIP_PAGE2_FAX_DETECT);
                ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_FAX_DETECT);
	} else
		res = 0;

	return res;
}

/*! \brief Add SIP domain to list of domains we are responsible for */
static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
{
	struct domain *d;

	if (ast_strlen_zero(domain)) {
		ast_log(LOG_WARNING, "Zero length domain.\n");
		return 1;
	}

	if (!(d = ast_calloc(1, sizeof(*d))))
		return 0;

	ast_copy_string(d->domain, domain, sizeof(d->domain));

	if (!ast_strlen_zero(context))
		ast_copy_string(d->context, context, sizeof(d->context));

	d->mode = mode;

	AST_LIST_LOCK(&domain_list);
	AST_LIST_INSERT_TAIL(&domain_list, d, list);
	AST_LIST_UNLOCK(&domain_list);

 	if (sipdebug)	
		ast_debug(1, "Added local SIP domain '%s'\n", domain);

	return 1;
}

/*! \brief  check_sip_domain: Check if domain part of uri is local to our server */
static int check_sip_domain(const char *domain, char *context, size_t len)
{
	struct domain *d;
	int result = 0;

	AST_LIST_LOCK(&domain_list);
	AST_LIST_TRAVERSE(&domain_list, d, list) {
		if (strcasecmp(d->domain, domain))
			continue;

		if (len && !ast_strlen_zero(d->context))
			ast_copy_string(context, d->context, len);
		
		result = 1;
		break;
	}
	AST_LIST_UNLOCK(&domain_list);

	return result;
}

/*! \brief Clear our domain list (at reload) */
static void clear_sip_domains(void)
{
	struct domain *d;

	AST_LIST_LOCK(&domain_list);
	while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
		ast_free(d);
	AST_LIST_UNLOCK(&domain_list);
}


/*! \brief Add realm authentication in list */
static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno)
{
	char authcopy[256];
	char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
	struct sip_auth *a, *b, *auth;

	if (ast_strlen_zero(configuration))
		return authlist;

	ast_debug(1, "Auth config ::  %s\n", configuration);

	ast_copy_string(authcopy, configuration, sizeof(authcopy));
	username = authcopy;

	/* split user[:secret] and relm */
	realm = strrchr(username, '@');
	if (realm)
		*realm++ = '\0';
	if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
		ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
		return authlist;
	}

	/* parse username at ':' for secret, or '#" for md5secret */
	if ((secret = strchr(username, ':'))) {
		*secret++ = '\0';
	} else if ((md5secret = strchr(username, '#'))) {
		*md5secret++ = '\0';
	}

	if (!(auth = ast_calloc(1, sizeof(*auth))))
		return authlist;

	ast_copy_string(auth->realm, realm, sizeof(auth->realm));
	ast_copy_string(auth->username, username, sizeof(auth->username));
	if (secret)
		ast_copy_string(auth->secret, secret, sizeof(auth->secret));
	if (md5secret)
		ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));

	/* find the end of the list */
	for (b = NULL, a = authlist; a ; b = a, a = a->next)
		;
	if (b)
		b->next = auth;	/* Add structure add end of list */
	else
		authlist = auth;

	ast_verb(3, "Added authentication for realm %s\n", realm);

	return authlist;

}

/*! \brief Clear realm authentication list (at reload) */
static int clear_realm_authentication(struct sip_auth *authlist)
{
	struct sip_auth *a = authlist;
	struct sip_auth *b;

	while (a) {
		b = a;
		a = a->next;
		ast_free(b);
	}

	return 1;
}

/*! \brief Find authentication for a specific realm */
static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm)
{
	struct sip_auth *a;

	for (a = authlist; a; a = a->next) {
		if (!strcasecmp(a->realm, realm))
			break;
	}

	return a;
}

/*! \brief
 * implement the setvar config line
 */
static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
{
	struct ast_variable *tmpvar = NULL;
	char *varname = ast_strdupa(buf), *varval = NULL;
	
	if ((varval = strchr(varname, '='))) {
		*varval++ = '\0';
		if ((tmpvar = ast_variable_new(varname, varval, ""))) {
			tmpvar->next = list;
			list = tmpvar;
		}
	}
	return list;
}

/*! \brief Initiate a SIP user structure from configuration (configuration or realtime) */
static struct sip_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime)
{
	struct sip_user *user;
	int format;
	struct ast_ha *oldha = NULL;
	struct ast_flags userflags[2] = {{(0)}};
	struct ast_flags mask[2] = {{(0)}};


	if (!(user = ast_calloc(1, sizeof(*user))))
		return NULL;
		
	suserobjs++;
	ASTOBJ_INIT(user);
	ast_copy_string(user->name, name, sizeof(user->name));
	oldha = user->ha;
	user->ha = NULL;
	ast_copy_flags(&user->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
	ast_copy_flags(&user->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
	user->capability = global_capability;
	user->allowtransfer = global_allowtransfer;
	user->maxcallbitrate = default_maxcallbitrate;
	user->autoframing = global_autoframing;
	user->t38_maxdatagram = global_t38_maxdatagram;
	if (global_callcounter)
		user->call_limit=999;
	user->prefs = default_prefs;
	user->stimer.st_mode_oper = global_st_mode;	/* Session-Timers */
	user->stimer.st_ref = global_st_refresher;
	user->stimer.st_min_se = global_min_se;
	user->stimer.st_max_se = global_max_se;

	/* set default context */
	strcpy(user->context, default_context);
	strcpy(user->language, default_language);
	strcpy(user->mohinterpret, default_mohinterpret);
	strcpy(user->mohsuggest, default_mohsuggest);
	/* First we walk through the v parameters list and then the alt parameters list */
	for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
		if (handle_common_options(&userflags[0], &mask[0], v))
			continue;
		if (handle_t38_options(&userflags[0], &mask[0], v, &user->t38_maxdatagram)) {
			continue;
		}
		if (!strcasecmp(v->name, "context")) {
			ast_copy_string(user->context, v->value, sizeof(user->context));
		} else if (!strcasecmp(v->name, "subscribecontext")) {
			ast_copy_string(user->subscribecontext, v->value, sizeof(user->subscribecontext));
		} else if (!strcasecmp(v->name, "setvar")) {
			user->chanvars = add_var(v->value, user->chanvars);
		} else if (!strcasecmp(v->name, "permit") ||
				   !strcasecmp(v->name, "deny")) {
			int ha_error = 0;

			user->ha = ast_append_ha(v->name, v->value, user->ha, &ha_error);
			if (ha_error)
				ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
		} else if (!strcasecmp(v->name, "allowtransfer")) {
			user->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
		} else if (!strcasecmp(v->name, "secret")) {
			ast_copy_string(user->secret, v->value, sizeof(user->secret)); 
		} else if (!strcasecmp(v->name, "md5secret")) {
			ast_copy_string(user->md5secret, v->value, sizeof(user->md5secret));
		} else if (!strcasecmp(v->name, "callerid")) {
			ast_callerid_split(v->value, user->cid_name, sizeof(user->cid_name), user->cid_num, sizeof(user->cid_num));
		} else if (!strcasecmp(v->name, "fullname")) {
			ast_copy_string(user->cid_name, v->value, sizeof(user->cid_name));
		} else if (!strcasecmp(v->name, "trunkname")) {
			/* This is actually for a trunk, so we don't want to override callerid */
			ast_copy_string(user->cid_name, "", sizeof(user->cid_name));
		} else if (!strcasecmp(v->name, "cid_number")) {
			ast_copy_string(user->cid_num, v->value, sizeof(user->cid_num));
		} else if (!strcasecmp(v->name, "callgroup")) {
			user->callgroup = ast_get_group(v->value);
		} else if (!strcasecmp(v->name, "pickupgroup")) {
			user->pickupgroup = ast_get_group(v->value);
		} else if (!strcasecmp(v->name, "language")) {
			ast_copy_string(user->language, v->value, sizeof(user->language));
		} else if (!strcasecmp(v->name, "mohinterpret")) {
			ast_copy_string(user->mohinterpret, v->value, sizeof(user->mohinterpret));
		} else if (!strcasecmp(v->name, "mohsuggest")) {
			ast_copy_string(user->mohsuggest, v->value, sizeof(user->mohsuggest));
		} else if (!strcasecmp(v->name, "accountcode")) {
			ast_copy_string(user->accountcode, v->value, sizeof(user->accountcode));
		} else if (!strcasecmp(v->name, "callcounter")) {
			user->call_limit = ast_true(v->value) ? 999 : 0;
		} else if (!strcasecmp(v->name, "call-limit")) {
			user->call_limit = atoi(v->value);
			if (user->call_limit < 0)
				user->call_limit = 0;
		} else if (!strcasecmp(v->name, "amaflags")) {
			format = ast_cdr_amaflags2int(v->value);
			if (format < 0) {
				ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
			} else {
				user->amaflags = format;
			}
		} else if (!strcasecmp(v->name, "allow")) {
			int error =  ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, TRUE);
			if (error)
				ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
		} else if (!strcasecmp(v->name, "disallow")) {
			int error =  ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, FALSE);
			if (error)
				ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
		} else if (!strcasecmp(v->name, "autoframing")) {
			user->autoframing = ast_true(v->value);
		} else if (!strcasecmp(v->name, "callingpres")) {
			user->callingpres = ast_parse_caller_presentation(v->value);
			if (user->callingpres == -1)
				user->callingpres = atoi(v->value);
		} else if (!strcasecmp(v->name, "maxcallbitrate")) {
			user->maxcallbitrate = atoi(v->value);
			if (user->maxcallbitrate < 0)
				user->maxcallbitrate = default_maxcallbitrate;
		} else if (!strcasecmp(v->name, "session-timers")) {
			int i = (int) str2stmode(v->value); 
			if (i < 0) {
				ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
				user->stimer.st_mode_oper = global_st_mode;
			} else {
				user->stimer.st_mode_oper = i;
			}
		} else if (!strcasecmp(v->name, "session-expires")) {
			if (sscanf(v->value, "%30d", &user->stimer.st_max_se) != 1) {
				ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
				user->stimer.st_max_se = global_max_se;
			}
		} else if (!strcasecmp(v->name, "session-minse")) {
			if (sscanf(v->value, "%30d", &user->stimer.st_min_se) != 1) {
				ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
				user->stimer.st_min_se = global_min_se;
			}
			if (user->stimer.st_min_se < 90) {
				ast_log(LOG_WARNING, "session-minse '%s' at line %d of %s is not allowed to be < 90 secs\n", v->value, v->lineno, config);
				user->stimer.st_min_se = global_min_se;
			}
		} else if (!strcasecmp(v->name, "session-refresher")) {
			int i = (int) str2strefresher(v->value); 
			if (i < 0) {
				ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
				user->stimer.st_ref = global_st_refresher;
			} else {
				user->stimer.st_ref = i;
			}
		}

		/* We can't just report unknown options here because this may be a
		 * type=friend entry.  All user options are valid for a peer, but not
		 * the other way around.  */
	}
	ast_copy_flags(&user->flags[0], &userflags[0], mask[0].flags);
	ast_copy_flags(&user->flags[1], &userflags[1], mask[1].flags);
	if (ast_test_flag(&user->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE))
		global_allowsubscribe = TRUE;	/* No global ban any more */
	ast_free_ha(oldha);
	return user;
}

/*! \brief Set peer defaults before configuring specific configurations */
static void set_peer_defaults(struct sip_peer *peer)
{
	if (peer->expire == 0) {
		/* Don't reset expire or port time during reload 
		   if we have an active registration 
		*/
		peer->expire = -1;
		peer->pokeexpire = -1;
		peer->addr.sin_port = htons(STANDARD_SIP_PORT);
		set_socket_transport(&peer->socket, SIP_TRANSPORT_UDP);
	}
	ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
	ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
	strcpy(peer->context, default_context);
	strcpy(peer->subscribecontext, default_subscribecontext);
	strcpy(peer->language, default_language);
	strcpy(peer->mohinterpret, default_mohinterpret);
	strcpy(peer->mohsuggest, default_mohsuggest);
	peer->addr.sin_family = AF_INET;
	peer->defaddr.sin_family = AF_INET;
	peer->capability = global_capability;
	peer->maxcallbitrate = default_maxcallbitrate;
	peer->rtptimeout = global_rtptimeout;
	peer->rtpholdtimeout = global_rtpholdtimeout;
	peer->rtpkeepalive = global_rtpkeepalive;
	peer->allowtransfer = global_allowtransfer;
	peer->autoframing = global_autoframing;
	peer->qualifyfreq = global_qualifyfreq;
	if (global_callcounter)
		peer->call_limit=999;
	strcpy(peer->vmexten, default_vmexten);
	peer->secret[0] = '\0';
	peer->md5secret[0] = '\0';
	peer->cid_num[0] = '\0';
	peer->cid_name[0] = '\0';
	peer->fromdomain[0] = '\0';
	peer->fromuser[0] = '\0';
	peer->regexten[0] = '\0';
	peer->callgroup = 0;
	peer->pickupgroup = 0;
	peer->maxms = default_qualify;
	peer->prefs = default_prefs;
	peer->stimer.st_mode_oper = global_st_mode;	/* Session-Timers */
	peer->stimer.st_ref = global_st_refresher;
	peer->stimer.st_min_se = global_min_se;
	peer->stimer.st_max_se = global_max_se;
	peer->timer_t1 = global_t1;
	peer->timer_b = global_timer_b;
	peer->t38_maxdatagram = global_t38_maxdatagram;
	clear_peer_mailboxes(peer);
}

/*! \brief Create temporary peer (used in autocreatepeer mode) */
static struct sip_peer *temp_peer(const char *name)
{
	struct sip_peer *peer;

	if (!(peer = ast_calloc(1, sizeof(*peer))))
		return NULL;

	apeerobjs++;
	ASTOBJ_INIT(peer);
	set_peer_defaults(peer);

	ast_copy_string(peer->name, name, sizeof(peer->name));

	peer->selfdestruct = TRUE;
	peer->host_dynamic = TRUE;
	peer->prefs = default_prefs;
	reg_source_db(peer);

	return peer;
}

/*! \todo document this function */
static void add_peer_mailboxes(struct sip_peer *peer, const char *value)
{
	char *next, *mbox, *context;

	next = ast_strdupa(value);

	while ((mbox = context = strsep(&next, ","))) {
		struct sip_mailbox *mailbox;

		if (!(mailbox = ast_calloc(1, sizeof(*mailbox))))
			continue;

		strsep(&context, "@");
		if (ast_strlen_zero(mbox)) {
			ast_free(mailbox);
			continue;
		}
		mailbox->mailbox = ast_strdup(mbox);
		mailbox->context = ast_strdup(context);

		AST_LIST_INSERT_TAIL(&peer->mailboxes, mailbox, entry);
	}
}

/*! \brief Build peer from configuration (file or realtime static/dynamic) */
static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only)
{
	struct sip_peer *peer = NULL;
	struct ast_ha *oldha = NULL;
	int found = 0;
	int firstpass = 1;
	uint16_t port = 0;
	int format = 0;		/* Ama flags */
	time_t regseconds = 0;
	struct ast_flags peerflags[2] = {{(0)}};
	struct ast_flags mask[2] = {{(0)}};
	char callback[256] = "";
	const char *srvlookup = NULL;
	static int deprecation_warning = 1;
	int alt_fullcontact = alt ? 1 : 0;
	struct ast_str *fullcontact = ast_str_alloca(512);

	if (!realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
		/* Note we do NOT use find_peer here, to avoid realtime recursion */
		/* We also use a case-sensitive comparison (unlike find_peer) so
		   that case changes made to the peer name will be properly handled
		   during reload
		*/
		peer = ASTOBJ_CONTAINER_FIND_UNLINK_FULL(&peerl, name, name, 0, 0, strcmp);
	}

	if (peer) {
		/* Already in the list, remove it and it will be added back (or FREE'd)  */
		found++;
		if (!(peer->objflags & ASTOBJ_FLAG_MARKED))
			firstpass = 0;
 	} else {
		if (!(peer = ast_calloc(1, sizeof(*peer))))
			return NULL;

		if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
			rpeerobjs++;
			ast_debug(3, "-REALTIME- peer built. Name: %s. Peer objects: %d\n", name, rpeerobjs);
		} else
			speerobjs++;
		ASTOBJ_INIT(peer);
	}
	/* Note that our peer HAS had its reference count incrased */
	if (firstpass) {
		peer->lastmsgssent = -1;
		oldha = peer->ha;
		peer->ha = NULL;
		set_peer_defaults(peer);	/* Set peer defaults */
	}
	if (!found && name)
			ast_copy_string(peer->name, name, sizeof(peer->name));

	/* If we have channel variables, remove them (reload) */
	if (peer->chanvars) {
		ast_variables_destroy(peer->chanvars);
		peer->chanvars = NULL;
		/* XXX should unregister ? */
	}

	if (found)
		peer->portinuri = 0;

	/* If we have realm authentication information, remove them (reload) */
	clear_realm_authentication(peer->auth);
	peer->auth = NULL;
	peer->default_outbound_transport = 0;
	peer->transports = 0;

	for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
		if (!devstate_only) {
			if (handle_common_options(&peerflags[0], &mask[0], v)) {
				continue;
			}
			if (handle_t38_options(&peerflags[0], &mask[0], v, &peer->t38_maxdatagram)) {
				continue;
			}
			if (!strcasecmp(v->name, "transport") && !ast_strlen_zero(v->value)) {
				char *val = ast_strdupa(v->value);
				char *trans;

				while ((trans = strsep(&val, ","))) {
					trans = ast_skip_blanks(trans);

					if (!strncasecmp(trans, "udp", 3)) {
						peer->transports |= SIP_TRANSPORT_UDP;
					} else if (!strncasecmp(trans, "tcp", 3)) {
						peer->transports |= SIP_TRANSPORT_TCP;
					} else if (!strncasecmp(trans, "tls", 3)) {
						peer->transports |= SIP_TRANSPORT_TLS;
					} else {
						ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
					}

					if (!peer->default_outbound_transport) { /*!< The first transport listed should be default outbound */
						peer->default_outbound_transport = peer->transports;
					}
				}
			} else if (realtime && !strcasecmp(v->name, "regseconds")) {
				ast_get_time_t(v->value, &regseconds, 0, NULL);
			} else if (realtime && !strcasecmp(v->name, "name")) {
				ast_copy_string(peer->name, v->value, sizeof(peer->name));
			} else if (!strcasecmp(v->name, "secret")) {
				ast_copy_string(peer->secret, v->value, sizeof(peer->secret));
			} else if (!strcasecmp(v->name, "md5secret")) {
				ast_copy_string(peer->md5secret, v->value, sizeof(peer->md5secret));
			} else if (!strcasecmp(v->name, "auth")) {
				peer->auth = add_realm_authentication(peer->auth, v->value, v->lineno);
			} else if (!strcasecmp(v->name, "callerid")) {
				ast_callerid_split(v->value, peer->cid_name, sizeof(peer->cid_name), peer->cid_num, sizeof(peer->cid_num));
			} else if (!strcasecmp(v->name, "fullname")) {
				ast_copy_string(peer->cid_name, v->value, sizeof(peer->cid_name));
			} else if (!strcasecmp(v->name, "trunkname")) {
				/* This is actually for a trunk, so we don't want to override callerid */
				ast_copy_string(peer->cid_name, "", sizeof(peer->cid_name));
			} else if (!strcasecmp(v->name, "cid_number")) {
				ast_copy_string(peer->cid_num, v->value, sizeof(peer->cid_num));
			} else if (!strcasecmp(v->name, "context")) {
				ast_copy_string(peer->context, v->value, sizeof(peer->context));
				ast_set_flag(&peer->flags[1], SIP_PAGE2_HAVEPEERCONTEXT);
			} else if (!strcasecmp(v->name, "subscribecontext")) {
				ast_copy_string(peer->subscribecontext, v->value, sizeof(peer->subscribecontext));
			} else if (!strcasecmp(v->name, "fromdomain")) {
				ast_copy_string(peer->fromdomain, v->value, sizeof(peer->fromdomain));
			} else if (!strcasecmp(v->name, "usereqphone")) {
				ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
			} else if (!strcasecmp(v->name, "fromuser")) {
				ast_copy_string(peer->fromuser, v->value, sizeof(peer->fromuser));
			} else if (!strcasecmp(v->name, "outboundproxy")) {
				char *port, *next, *force, *proxyname;
				int forceopt = FALSE;
				/* Set peer channel variable */
				next = proxyname = ast_strdupa(v->value);
				if ((port = strchr(proxyname, ':'))) {
					*port++ = '\0';
					next = port;
				}
				if ((force = strchr(next, ','))) {
					*force++ = '\0';
					forceopt = strcmp(force, "force");
				}
				/* Allocate proxy object */
				peer->outboundproxy = proxy_allocate(proxyname, port, forceopt);
			} else if (!strcasecmp(v->name, "host")) {
				if (!strcasecmp(v->value, "dynamic")) {
					/* They'll register with us */
					if (!found || !peer->host_dynamic) {
						/* Initialize stuff if this is a new peer, or if it used to
						 * not be dynamic before the reload. */
						memset(&peer->addr.sin_addr, 0, 4);
						peer->addr.sin_port = 0;
					}
					peer->host_dynamic = TRUE;
				} else {
					/* Non-dynamic.  Make sure we become that way if we're not */
					AST_SCHED_DEL(sched, peer->expire);
					/* the port will either be set to a default value or a config specified value once all option parsing is complete */
					peer->addr.sin_port = 0;
					peer->host_dynamic = FALSE;
					srvlookup = v->value;
					if (global_dynamic_exclude_static) {
						int err = 0;
						global_contact_ha = ast_append_ha("deny", (char *)ast_inet_ntoa(peer->addr.sin_addr), global_contact_ha, &err);
						if (err) {
							ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
						}
					}
				}
			} else if (!strcasecmp(v->name, "defaultip")) {
				if (!ast_strlen_zero(v->value) && ast_get_ip(&peer->defaddr, v->value)) {
					unref_peer(peer);
					return NULL;
				}
			} else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
				int ha_error = 0;
				if (!ast_strlen_zero(v->value)) {
					peer->ha = ast_append_ha(v->name, v->value, peer->ha, &ha_error);
				}
				if (ha_error) {
					ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
				}
			} else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
				int ha_error = 0;
				if (!ast_strlen_zero(v->value)) {
					peer->contactha = ast_append_ha(v->name + 7, v->value, peer->contactha, &ha_error);
				}
				if (ha_error) {
					ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
				}
			} else if (!strcasecmp(v->name, "port")) {
				peer->portinuri = 1;
				if (!(port = port_str2int(v->value, 0))) {
					if (realtime) {
						/* If stored as integer, could be 0 for some DBs (notably MySQL) */
						peer->portinuri = 0;
					} else {
						ast_log(LOG_WARNING, "Invalid peer port configuration at line %d : %s\n", v->lineno, v->value);
					}
				}
			} else if (!strcasecmp(v->name, "callingpres")) {
				peer->callingpres = ast_parse_caller_presentation(v->value);
				if (peer->callingpres == -1) {
					peer->callingpres = atoi(v->value);
				}
			} else if (!strcasecmp(v->name, "username") || !strcmp(v->name, "defaultuser")) {	/* "username" is deprecated */
				ast_copy_string(peer->username, v->value, sizeof(peer->username));
				if (!strcasecmp(v->name, "username")) {
					if (deprecation_warning) {
						ast_log(LOG_NOTICE, "The 'username' field for sip peers has been deprecated in favor of the term 'defaultuser'\n");
						deprecation_warning = 0;
					}
					peer->deprecated_username = 1;
				}
			} else if (!strcasecmp(v->name, "language")) {
				ast_copy_string(peer->language, v->value, sizeof(peer->language));
			} else if (!strcasecmp(v->name, "regexten")) {
				ast_copy_string(peer->regexten, v->value, sizeof(peer->regexten));
			} else if (!strcasecmp(v->name, "callbackextension")) {
				ast_copy_string(callback, v->value, sizeof(callback));
			} else if (!strcasecmp(v->name, "callcounter")) {
				peer->call_limit = ast_true(v->value) ? 999 : 0;
			} else if (!strcasecmp(v->name, "call-limit")) {
				peer->call_limit = atoi(v->value);
				if (peer->call_limit < 0) {
					peer->call_limit = 0;
				}
			} else if (!strcasecmp(v->name, "busylevel")) {
				peer->busy_level = atoi(v->value);
				if (peer->busy_level < 0) {
					peer->busy_level = 0;
				}
			} else if (!strcasecmp(v->name, "amaflags")) {
				format = ast_cdr_amaflags2int(v->value);
				if (format < 0) {
					ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
				} else {
					peer->amaflags = format;
				}
			} else if (!strcasecmp(v->name, "accountcode")) {
				ast_copy_string(peer->accountcode, v->value, sizeof(peer->accountcode));
			} else if (!strcasecmp(v->name, "mohinterpret")) {
				ast_copy_string(peer->mohinterpret, v->value, sizeof(peer->mohinterpret));
			} else if (!strcasecmp(v->name, "mohsuggest")) {
				ast_copy_string(peer->mohsuggest, v->value, sizeof(peer->mohsuggest));
			} else if (!strcasecmp(v->name, "mailbox")) {
				add_peer_mailboxes(peer, v->value);
			} else if (!strcasecmp(v->name, "hasvoicemail")) {
				/* People expect that if 'hasvoicemail' is set, that the mailbox will
				 * be also set, even if not explicitly specified. */
				if (ast_true(v->value) && AST_LIST_EMPTY(&peer->mailboxes)) {
					add_peer_mailboxes(peer, name);
				}
			} else if (!strcasecmp(v->name, "subscribemwi")) {
				ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
			} else if (!strcasecmp(v->name, "vmexten")) {
				ast_copy_string(peer->vmexten, v->value, sizeof(peer->vmexten));
			} else if (!strcasecmp(v->name, "callgroup")) {
				peer->callgroup = ast_get_group(v->value);
			} else if (!strcasecmp(v->name, "allowtransfer")) {
				peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
			} else if (!strcasecmp(v->name, "pickupgroup")) {
				peer->pickupgroup = ast_get_group(v->value);
			} else if (!strcasecmp(v->name, "allow")) {
				int error = ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, TRUE);
				if (error) {
					ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
				}
			} else if (!strcasecmp(v->name, "disallow")) {
				int error = ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, FALSE);
				if (error) {
					ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
				}
			} else if (!strcasecmp(v->name, "registertrying")) {
				ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_REGISTERTRYING);
			} else if (!strcasecmp(v->name, "autoframing")) {
				peer->autoframing = ast_true(v->value);
			} else if (!strcasecmp(v->name, "rtptimeout")) {
				if ((sscanf(v->value, "%30d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
					ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
					peer->rtptimeout = global_rtptimeout;
				}
			} else if (!strcasecmp(v->name, "rtpholdtimeout")) {
				if ((sscanf(v->value, "%30d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
					ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
					peer->rtpholdtimeout = global_rtpholdtimeout;
				}
			} else if (!strcasecmp(v->name, "rtpkeepalive")) {
				if ((sscanf(v->value, "%30d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
					ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d.  Using default.\n", v->value, v->lineno);
					peer->rtpkeepalive = global_rtpkeepalive;
				}
			} else if (!strcasecmp(v->name, "timert1")) {
				if ((sscanf(v->value, "%30d", &peer->timer_t1) != 1) || (peer->timer_t1 < 0)) {
					ast_log(LOG_WARNING, "'%s' is not a valid T1 time at line %d.  Using default.\n", v->value, v->lineno);
					peer->timer_t1 = global_t1;
				}
				/* Note that Timer B is dependent upon T1 and MUST NOT be lower
				 * than T1 * 64, according to RFC 3261, Section 17.1.1.2 */
				if (peer->timer_b < peer->timer_t1 * 64) {
					peer->timer_b = peer->timer_t1 * 64;
				}
			} else if (!strcasecmp(v->name, "timerb")) {
				if ((sscanf(v->value, "%30d", &peer->timer_b) != 1) || (peer->timer_b < 0)) {
					ast_log(LOG_WARNING, "'%s' is not a valid Timer B time at line %d.  Using default.\n", v->value, v->lineno);
					peer->timer_b = global_timer_b;
				}
				if (peer->timer_b < peer->timer_t1 * 64) {
					static int warning = 0;
					if (warning++ % 20 == 0) {
						ast_log(LOG_WARNING, "Timer B has been set lower than recommended. (RFC 3261, 17.1.1.2)\n");
					}
				}
			} else if (!strcasecmp(v->name, "setvar")) {
				peer->chanvars = add_var(v->value, peer->chanvars);
			} else if (!strcasecmp(v->name, "qualifyfreq")) {
				int i;
				if (sscanf(v->value, "%30d", &i) == 1) {
					peer->qualifyfreq = i * 1000;
				} else {
					ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
					peer->qualifyfreq = global_qualifyfreq;
				}
			} else if (!strcasecmp(v->name, "maxcallbitrate")) {
				peer->maxcallbitrate = atoi(v->value);
				if (peer->maxcallbitrate < 0) {
					peer->maxcallbitrate = default_maxcallbitrate;
				}
			} else if (!strcasecmp(v->name, "session-timers")) {
				int i = (int) str2stmode(v->value);
				if (i < 0) {
					ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
					peer->stimer.st_mode_oper = global_st_mode;
				} else {
					peer->stimer.st_mode_oper = i;
				}
			} else if (!strcasecmp(v->name, "session-expires")) {
				if (sscanf(v->value, "%30d", &peer->stimer.st_max_se) != 1) {
					ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
					peer->stimer.st_max_se = global_max_se;
					}
			} else if (!strcasecmp(v->name, "session-minse")) {
				if (sscanf(v->value, "%30d", &peer->stimer.st_min_se) != 1) {
					ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
					peer->stimer.st_min_se = global_min_se;
				}
				if (peer->stimer.st_min_se < 90) {
					ast_log(LOG_WARNING, "session-minse '%s' at line %d of %s is not allowed to be < 90 secs\n", v->value, v->lineno, config);
					peer->stimer.st_min_se = global_min_se;
				}
			} else if (!strcasecmp(v->name, "session-refresher")) {
				int i = (int) str2strefresher(v->value);
				if (i < 0) {
					ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
					peer->stimer.st_ref = global_st_refresher;
				} else {
					peer->stimer.st_ref = i;
				}
			}
		}

		/* These apply to devstate lookups */
		if (realtime && !strcasecmp(v->name, "lastms")) {
			sscanf(v->value, "%30d", &peer->lastms);
		} else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
			inet_aton(v->value, &(peer->addr.sin_addr));
		} else if (realtime && !strcasecmp(v->name, "fullcontact")) {
			if (alt_fullcontact && !alt) {
				/* Reset, because the alternate also has a fullcontact and we
				 * do NOT want the field value to be doubled. It might be
				 * tempting to skip this, but the first table might not have
				 * fullcontact and since we're here, we know that the alternate
				 * absolutely does. */
				alt_fullcontact = 0;
				ast_str_reset(fullcontact);
			}
			/* Reconstruct field, because realtime separates our value at the ';' */
			if (fullcontact->used > 0) {
				ast_str_append(&fullcontact, 0, ";%s", v->value);
			} else {
				ast_str_set(&fullcontact, 0, "%s", v->value);
			}
		} else if (!strcasecmp(v->name, "qualify")) {
			if (!strcasecmp(v->value, "no")) {
				peer->maxms = 0;
			} else if (!strcasecmp(v->value, "yes")) {
				peer->maxms = default_qualify ? default_qualify : DEFAULT_MAXMS;
			} else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
				ast_log(LOG_WARNING, "Qualification of peer '%s' should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", peer->name, v->lineno);
				peer->maxms = 0;
			}
			if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->maxms > 0) {
				/* This would otherwise cause a network storm, where the
				 * qualify response refreshes the peer from the database,
				 * which in turn causes another qualify to be sent, ad
				 * infinitum. */
				ast_log(LOG_WARNING, "Qualify is incompatible with dynamic uncached realtime.  Please either turn rtcachefriends on or turn qualify off on peer '%s'\n", peer->name);
				peer->maxms = 0;
			}
		} else if (!strcasecmp(v->name, "callcounter")) {
			peer->call_limit = ast_true(v->value) ? INT_MAX : 0;
		} else if (!strcasecmp(v->name, "call-limit")) {
			peer->call_limit = atoi(v->value);
			if (peer->call_limit < 0) {
				peer->call_limit = 0;
			}
		} else if (!strcasecmp(v->name, "busylevel")) {
			peer->busy_level = atoi(v->value);
			if (peer->busy_level < 0) {
				peer->busy_level = 0;
			}
		}
	}

	if (!peer->default_outbound_transport) {
		peer->transports  = SIP_TRANSPORT_UDP;
		peer->default_outbound_transport = SIP_TRANSPORT_UDP;
	}

	/* The default transport type set during build_peer should only replace the socket.type when...
	 * 1. Registration is not present and the socket.type and default transport types are different.
	 * 2. The socket.type is not an acceptable transport type after rebuilding peer.
	 * 3. The socket.type is not set yet. */
	if (((peer->socket.type != peer->default_outbound_transport) && (peer->expire == -1)) ||
		!(peer->socket.type & peer->transports) || !(peer->socket.type)) {

		set_socket_transport(&peer->socket, peer->default_outbound_transport);
	}

	if (port && !realtime && peer->host_dynamic) {
		peer->defaddr.sin_port = htons(port);
	} else if (port) {
		peer->addr.sin_port = htons(port);
	}

	if (ast_str_strlen(fullcontact)) {
		ast_copy_string(peer->fullcontact, fullcontact->str, sizeof(peer->fullcontact));
		peer->rt_fromcontact = TRUE;
		/* We have a hostname in the fullcontact, but if we don't have an
		 * address listed on the entry (or if it's 'dynamic'), then we need to
		 * parse the entry to obtain the IP address, so a dynamic host can be
		 * contacted immediately after reload (as opposed to waiting for it to
		 * register once again). But if we have an address for this peer and NAT was
		 * specified, use that address instead. */
		/* XXX May need to revisit the final argument; does the realtime DB store whether
		 * the original contact was over TLS or not? XXX */
		if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) || !peer->addr.sin_addr.s_addr) {
			__set_address_from_contact(fullcontact->str, &peer->addr, 0);
		}
	}

	if (srvlookup) {
		if (ast_get_ip_or_srv(&peer->addr, srvlookup, 
							global_srvlookup && !peer->portinuri ?
								((peer->socket.type & SIP_TRANSPORT_UDP) ? "_sip._udp" :
								 (peer->socket.type & SIP_TRANSPORT_TCP) ? "_sip._tcp" :
								 "_sip._tls")
								: NULL)) {
			ast_log(LOG_ERROR, "srvlookup failed for host: %s, on peer %s, removing peer\n", srvlookup, peer->name);
			unref_peer(peer);
			return NULL;
		}

		ast_copy_string(peer->tohost, srvlookup, sizeof(peer->tohost));
	}

	if (!peer->addr.sin_port) {
		peer->addr.sin_port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
	}
	if (!peer->defaddr.sin_port) {
		peer->defaddr.sin_port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
	}
	if (!peer->socket.port) {
		peer->socket.port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
	}

	if (!sip_cfg.ignore_regexpire && peer->host_dynamic && realtime) {
		time_t nowtime = time(NULL);

		if ((nowtime - regseconds) > 0) {
			destroy_association(peer);
			memset(&peer->addr, 0, sizeof(peer->addr));
			peer->lastms = -1;
			ast_debug(1, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
		}
	}

	/* Startup regular pokes */
	if (!devstate_only && realtime && peer->lastms > 0) {
		ASTOBJ_REF(peer);
		sip_poke_peer(peer);
	}

	ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
	ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
	if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
		global_allowsubscribe = TRUE;	/* No global ban any more */
	}
	if (!found && peer->host_dynamic && !peer->is_realtime) {
		reg_source_db(peer);
	}

	/* If they didn't request that MWI is sent *only* on subscribe, go ahead and
	 * subscribe to it now. */
	if (!devstate_only && !ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
		!AST_LIST_EMPTY(&peer->mailboxes)) {
		add_peer_mwi_subs(peer);
		/* Send MWI from the event cache only.  This is so we can send initial
		 * MWI if app_voicemail got loaded before chan_sip.  If it is the other
		 * way, then we will get events when app_voicemail gets loaded. */
		sip_send_mwi_to_peer(peer, NULL, 1);
	}

	ASTOBJ_UNMARK(peer);

	ast_free_ha(oldha);
	if (!ast_strlen_zero(callback)) { /* build string from peer info */
		char *reg_string;

		if (asprintf(&reg_string, "%s?%s:%s@%s/%s", peer->name, peer->username, peer->secret, peer->tohost, callback) < 0) {
			ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
		} else if (reg_string) {
			sip_register(reg_string, 0); /* XXX TODO: count in registry_count */
			ast_free(reg_string);
		}
	}
	return peer;
}

/*! \brief Re-read SIP.conf config file
\note	This function reloads all config data, except for
	active peers (with registrations). They will only
	change configuration data at restart, not at reload.
	SIP debug and recordhistory state will not change
 */
static int reload_config(enum channelreloadreason reason)
{
	struct ast_config *cfg, *ucfg;
	struct ast_variable *v;
	struct sip_peer *peer;
	struct sip_user *user;
	char *cat, *stringp, *context, *oldregcontext;
	char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
	struct ast_flags dummy[2];
	struct ast_flags config_flags = { reason == CHANNEL_MODULE_LOAD ? 0 : ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) ? 0 : CONFIG_FLAG_FILEUNCHANGED };
	int auto_sip_domains = FALSE;
	struct sockaddr_in old_bindaddr = bindaddr;
	int registry_count = 0, peer_count = 0, user_count = 0;

	cfg = ast_config_load(config, config_flags);

	/* We *must* have a config file otherwise stop immediately */
	if (!cfg) {
		ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
		return -1;
	} else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
		ucfg = ast_config_load("users.conf", config_flags);
		if (ucfg == CONFIG_STATUS_FILEUNCHANGED)
			return 1;
		/* Must reread both files, because one changed */
		ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
		cfg = ast_config_load(config, config_flags);
	} else {
		ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
		ucfg = ast_config_load("users.conf", config_flags);
	}

	/* Initialize tcp sockets */
	memset(&sip_tcp_desc.sin, 0, sizeof(sip_tcp_desc.sin));
	memset(&sip_tls_desc.sin, 0, sizeof(sip_tls_desc.sin));

	ast_free_ha(global_contact_ha);
	global_contact_ha = NULL;

	default_tls_cfg.enabled = FALSE;		/* Default: Disable TLS */

	sip_tcp_desc.sin.sin_port = htons(STANDARD_SIP_PORT);
	sip_tls_desc.sin.sin_port = htons(STANDARD_TLS_PORT);

	if (reason != CHANNEL_MODULE_LOAD) {
		ast_debug(4, "--------------- SIP reload started\n");

		clear_realm_authentication(authl);
		clear_sip_domains();
		authl = NULL;

		/* First, destroy all outstanding registry calls */
		/* This is needed, since otherwise active registry entries will not be destroyed */
		ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
			ASTOBJ_RDLOCK(iterator);
			if (iterator->call) {
				ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
				/* This will also remove references to the registry */
				dialog_cleanup_and_destroy(iterator->call);
				iterator->call = NULL; /* sip_destroy(iterator->call);*/
			}
			ASTOBJ_UNLOCK(iterator);

		} while(0));

		/* Then, actually destroy users and registry */
		ASTOBJ_CONTAINER_DESTROYALL(&userl, sip_destroy_user);
		ast_debug(4, "--------------- Done destroying user list\n");
		ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
		ast_debug(4, "--------------- Done destroying registry list\n");
		ASTOBJ_CONTAINER_MARKALL(&peerl);
	}

	/* Reset certificate handling for TLS sessions */
	default_tls_cfg.certfile = ast_strdup(AST_CERTFILE); /*XXX Not sure if this is useful */
	default_tls_cfg.cipher = ast_strdup("");
	default_tls_cfg.cafile = ast_strdup("");
	default_tls_cfg.capath = ast_strdup("");
	
	/* Initialize copy of current global_regcontext for later use in removing stale contexts */
	ast_copy_string(oldcontexts, global_regcontext, sizeof(oldcontexts));
	oldregcontext = oldcontexts;

	/* Clear all flags before setting default values */
	/* Preserve debugging settings for console */
	sipdebug &= sip_debug_console;
	ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
	ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);

	/* Reset IP addresses  */
	memset(&bindaddr, 0, sizeof(bindaddr));
	memset(&stunaddr, 0, sizeof(stunaddr));
	memset(&internip, 0, sizeof(internip));

	/* Free memory for local network address mask */
	ast_free_ha(localaddr);
	memset(&localaddr, 0, sizeof(localaddr));
	memset(&externip, 0, sizeof(externip));
	memset(&default_prefs, 0 , sizeof(default_prefs));
	memset(&global_outboundproxy, 0, sizeof(struct sip_proxy));
	global_outboundproxy.ip.sin_port = htons(STANDARD_SIP_PORT);
	global_outboundproxy.ip.sin_family = AF_INET;	/*!< Type of address: IPv4 */
	global_outboundproxy.force = FALSE;		/*!< Don't force proxy usage, use route: headers */
	ourport_tcp = STANDARD_SIP_PORT;
	ourport_tls = STANDARD_TLS_PORT;
	bindaddr.sin_port = htons(STANDARD_SIP_PORT);
	global_srvlookup = DEFAULT_SRVLOOKUP;
	global_tos_sip = DEFAULT_TOS_SIP;
	global_tos_audio = DEFAULT_TOS_AUDIO;
	global_tos_video = DEFAULT_TOS_VIDEO;
	global_tos_text = DEFAULT_TOS_TEXT;
	global_cos_sip = DEFAULT_COS_SIP;
	global_cos_audio = DEFAULT_COS_AUDIO;
	global_cos_video = DEFAULT_COS_VIDEO;
	global_cos_text = DEFAULT_COS_TEXT;

	externhost[0] = '\0';			/* External host name (for behind NAT DynDNS support) */
	externexpire = 0;			/* Expiration for DNS re-issuing */
	externrefresh = 10;

	/* Reset channel settings to default before re-configuring */
	allow_external_domains = DEFAULT_ALLOW_EXT_DOM;				/* Allow external invites */
	global_regcontext[0] = '\0';
	global_regextenonqualify = DEFAULT_REGEXTENONQUALIFY;
	global_notifyringing = DEFAULT_NOTIFYRINGING;
	global_limitonpeers = FALSE;		/*!< Match call limit on peers only */
	global_notifyhold = FALSE;		/*!< Keep track of hold status for a peer */
	global_directrtpsetup = FALSE;		/* Experimental feature, disabled by default */
	global_alwaysauthreject = 0;
	global_allowsubscribe = FALSE;
	snprintf(global_useragent, sizeof(global_useragent), "%s %s", DEFAULT_USERAGENT, ast_get_version());
	snprintf(global_sdpsession, sizeof(global_sdpsession), "%s %s", DEFAULT_SDPSESSION, ast_get_version());
	snprintf(global_sdpowner, sizeof(global_sdpowner), "%s", DEFAULT_SDPOWNER);
	global_prematuremediafilter = FALSE;
	ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
	ast_copy_string(global_realm, S_OR(ast_config_AST_SYSTEM_NAME, DEFAULT_REALM), sizeof(global_realm));
	ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
	compactheaders = DEFAULT_COMPACTHEADERS;
	global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
	global_regattempts_max = 0;
	pedanticsipchecking = DEFAULT_PEDANTIC;
	autocreatepeer = DEFAULT_AUTOCREATEPEER;
	global_autoframing = 0;
	global_allowguest = DEFAULT_ALLOWGUEST;
	global_callcounter = DEFAULT_CALLCOUNTER;
	global_match_auth_username = FALSE;		/*!< Match auth username if available instead of From: Default off. */
	global_rtptimeout = 0;
	global_rtpholdtimeout = 0;
	global_rtpkeepalive = 0;
	global_allowtransfer = TRANSFER_OPENFORALL;	/* Merrily accept all transfers by default */
	global_rtautoclear = 120;
	ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE);	/* Default for peers, users: TRUE */
	ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP);		/* Default for peers, users: TRUE */
	sip_cfg.peer_rtupdate = TRUE;
	global_dynamic_exclude_static = 0;	/* Exclude static peers */

	/* Session-Timers */
	global_st_mode = SESSION_TIMER_MODE_ACCEPT;    
	global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
	global_min_se  = DEFAULT_MIN_SE;
	global_max_se  = DEFAULT_MAX_SE;

	/* Initialize some reasonable defaults at SIP reload (used both for channel and as default for peers and users */
	ast_copy_string(default_context, DEFAULT_CONTEXT, sizeof(default_context));
	default_subscribecontext[0] = '\0';
	default_language[0] = '\0';
	default_fromdomain[0] = '\0';
	default_qualify = DEFAULT_QUALIFY;
	default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
	ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
	ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
	ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
	ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833);			/*!< Default DTMF setting: RFC2833 */
	ast_set_flag(&global_flags[0], SIP_NAT_RFC3581);			/*!< NAT support if requested by device with rport */
	ast_set_flag(&global_flags[0], SIP_CAN_REINVITE);			/*!< Allow re-invites */

	/* Debugging settings, always default to off */
	dumphistory = FALSE;
	recordhistory = FALSE;
	sipdebug &= ~sip_debug_config;

	/* Misc settings for the channel */
	global_relaxdtmf = FALSE;
	global_callevents = FALSE;
	global_t1 = SIP_TIMER_T1;
	global_timer_b = 64 * SIP_TIMER_T1;
	global_t1min = DEFAULT_T1MIN;
	global_qualifyfreq = DEFAULT_QUALIFYFREQ;
	global_t38_maxdatagram = -1;
	global_shrinkcallerid = 1;

	global_matchexterniplocally = FALSE;

	/* Copy the default jb config over global_jbconf */
	memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));

	ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT);
	ast_clear_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT);
	ast_clear_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION);
	ast_clear_flag(&global_flags[1], SIP_PAGE2_FAX_DETECT);

	/* Read the [general] config section of sip.conf (or from realtime config) */
	for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
		if (handle_common_options(&global_flags[0], &dummy[0], v))
			continue;
		if (handle_t38_options(&global_flags[0], &dummy[0], v, &global_t38_maxdatagram)) {
			continue;
		}
		/* handle jb conf */
		if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
			continue;

		if (!strcasecmp(v->name, "context")) {
			ast_copy_string(default_context, v->value, sizeof(default_context));
		} else if (!strcasecmp(v->name, "subscribecontext")) {
			ast_copy_string(default_subscribecontext, v->value, sizeof(default_subscribecontext));
  		} else if (!strcasecmp(v->name, "callcounter")) {
			global_callcounter = ast_true(v->value) ? 1 : 0;
  		} else if (!strcasecmp(v->name, "allowguest")) {
			global_allowguest = ast_true(v->value) ? 1 : 0;
		} else if (!strcasecmp(v->name, "realm")) {
			ast_copy_string(global_realm, v->value, sizeof(global_realm));
		} else if (!strcasecmp(v->name, "useragent")) {
			ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
			ast_debug(1, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
		} else if (!strcasecmp(v->name, "sdpsession")) {
			ast_copy_string(global_sdpsession, v->value, sizeof(global_sdpsession));
		} else if (!strcasecmp(v->name, "sdpowner")) {
			/* Field cannot contain spaces */
			if (!strstr(v->value, " "))
				ast_copy_string(global_sdpowner, v->value, sizeof(global_sdpowner));
			else
				ast_log(LOG_WARNING, "'%s' must not contain spaces at line %d.  Using default.\n", v->value, v->lineno);
		} else if (!strcasecmp(v->name, "allowtransfer")) {
			global_allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
		} else if (!strcasecmp(v->name, "rtcachefriends")) {
			ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);	
		} else if (!strcasecmp(v->name, "rtsavesysname")) {
			sip_cfg.rtsave_sysname = ast_true(v->value);
		} else if (!strcasecmp(v->name, "rtupdate")) {
			sip_cfg.peer_rtupdate = ast_true(v->value);
		} else if (!strcasecmp(v->name, "ignoreregexpire")) {
			sip_cfg.ignore_regexpire = ast_true(v->value);
		} else if (!strcasecmp(v->name, "timert1")) {
			/* Defaults to 500ms, but RFC 3261 states that it is recommended
			 * for the value to be set higher, though a lower value is only
			 * allowed on private networks unconnected to the Internet. */
			global_t1 = atoi(v->value);
			/* Note that timer B is dependent on the value of T1 */
			global_timer_b = global_t1 * 64;
		} else if (!strcasecmp(v->name, "t1min")) {
			global_t1min = atoi(v->value);
		} else if (!strcasecmp(v->name, "tcpenable")) {
			sip_tcp_desc.sin.sin_family = ast_false(v->value) ? 0 : AF_INET;
			ast_debug(2, "Enabling TCP socket for listening\n");
		} else if (!strcasecmp(v->name, "tcpbindaddr")) {
			int family = sip_tcp_desc.sin.sin_family;
			if (ast_parse_arg(v->value, PARSE_INADDR, &sip_tcp_desc.sin))
				ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n", v->name, v->value, v->lineno, config);
			sip_tcp_desc.sin.sin_family = family;
			ast_debug(2, "Setting TCP socket address to %s\n", v->value);
		} else if (!strcasecmp(v->name, "tlsenable")) {
			default_tls_cfg.enabled = ast_true(v->value) ? TRUE : FALSE;
			sip_tls_desc.sin.sin_family = AF_INET;
		} else if (!strcasecmp(v->name, "tlscertfile")) {
			ast_free(default_tls_cfg.certfile);
			default_tls_cfg.certfile = ast_strdup(v->value);
		} else if (!strcasecmp(v->name, "tlscipher")) {
			ast_free(default_tls_cfg.cipher);
			default_tls_cfg.cipher = ast_strdup(v->value);
		} else if (!strcasecmp(v->name, "tlscafile")) {
			ast_free(default_tls_cfg.cafile);
			default_tls_cfg.cafile = ast_strdup(v->value);
		} else if (!strcasecmp(v->name, "tlscapath")) {
			ast_free(default_tls_cfg.capath);
			default_tls_cfg.capath = ast_strdup(v->value);
		} else if (!strcasecmp(v->name, "tlsverifyclient")) {
			ast_set2_flag(&default_tls_cfg.flags, ast_true(v->value), AST_SSL_VERIFY_CLIENT);	
		} else if (!strcasecmp(v->name, "tlsdontverifyserver")) {
			ast_set2_flag(&default_tls_cfg.flags, ast_true(v->value), AST_SSL_DONT_VERIFY_SERVER);	
		} else if (!strcasecmp(v->name, "tlsbindaddr")) {
			if (ast_parse_arg(v->value, PARSE_INADDR, &sip_tls_desc.sin))
				ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n", v->name, v->value, v->lineno, config);
		} else if (!strcasecmp(v->name, "dynamic_exclude_static") || !strcasecmp(v->name, "dynamic_excludes_static")) {
			global_dynamic_exclude_static = ast_true(v->value);
		} else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
			int ha_error = 0;
			global_contact_ha = ast_append_ha(v->name + 7, v->value, global_contact_ha, &ha_error);
			if (ha_error) {
				ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
			}
		} else if (!strcasecmp(v->name, "rtautoclear")) {
			int i = atoi(v->value);
			if (i > 0)
				global_rtautoclear = i;
			else
				i = 0;
			ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
		} else if (!strcasecmp(v->name, "usereqphone")) {
			ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);	
		} else if (!strcasecmp(v->name, "prematuremedia")) {
			global_prematuremediafilter = ast_true(v->value);
		} else if (!strcasecmp(v->name, "relaxdtmf")) {
			global_relaxdtmf = ast_true(v->value);
		} else if (!strcasecmp(v->name, "vmexten")) {
			ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
		} else if (!strcasecmp(v->name, "rtptimeout")) {
			if ((sscanf(v->value, "%30d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
				ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
				global_rtptimeout = 0;
			}
		} else if (!strcasecmp(v->name, "rtpholdtimeout")) {
			if ((sscanf(v->value, "%30d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
				ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
				global_rtpholdtimeout = 0;
			}
		} else if (!strcasecmp(v->name, "rtpkeepalive")) {
			if ((sscanf(v->value, "%30d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
				ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d.  Using default.\n", v->value, v->lineno);
				global_rtpkeepalive = 0;
			}
		} else if (!strcasecmp(v->name, "compactheaders")) {
			compactheaders = ast_true(v->value);
		} else if (!strcasecmp(v->name, "notifymimetype")) {
			ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
		} else if (!strncasecmp(v->name, "limitonpeer", 11) || !strcasecmp(v->name, "counteronpeer")) {
			global_limitonpeers = ast_true(v->value);
		} else if (!strcasecmp(v->name, "directrtpsetup")) {
			global_directrtpsetup = ast_true(v->value);
		} else if (!strcasecmp(v->name, "notifyringing")) {
			global_notifyringing = ast_true(v->value);
		} else if (!strcasecmp(v->name, "notifyhold")) {
			global_notifyhold = ast_true(v->value);
		} else if (!strcasecmp(v->name, "alwaysauthreject")) {
			global_alwaysauthreject = ast_true(v->value);
		} else if (!strcasecmp(v->name, "mohinterpret")) {
			ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
		} else if (!strcasecmp(v->name, "mohsuggest")) {
			ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
		} else if (!strcasecmp(v->name, "language")) {
			ast_copy_string(default_language, v->value, sizeof(default_language));
		} else if (!strcasecmp(v->name, "regcontext")) {
			ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
			stringp = newcontexts;
			/* Let's remove any contexts that are no longer defined in regcontext */
			cleanup_stale_contexts(stringp, oldregcontext);
			/* Create contexts if they don't exist already */
			while ((context = strsep(&stringp, "&"))) {
				ast_copy_string(used_context, context, sizeof(used_context));
				ast_context_find_or_create(NULL, NULL, context, "SIP");
			}
			ast_copy_string(global_regcontext, v->value, sizeof(global_regcontext));
		} else if (!strcasecmp(v->name, "regextenonqualify")) {
			global_regextenonqualify = ast_true(v->value);
		} else if (!strcasecmp(v->name, "callerid")) {
			ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
		} else if (!strcasecmp(v->name, "fromdomain")) {
			ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
		} else if (!strcasecmp(v->name, "outboundproxy")) {
			int portnum;
			char *tok, *proxyname;

			if (ast_strlen_zero(v->value)) {
				ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf.", v->lineno);
				continue;
			}

			tok = ast_skip_blanks(strtok(ast_strdupa(v->value), ","));

			sip_parse_host(tok, v->lineno, &proxyname, &portnum, &global_outboundproxy.transport);

			global_outboundproxy.ip.sin_port = htons(portnum);
	
			if ((tok = strtok(NULL, ","))) {
				global_outboundproxy.force = !strncasecmp(ast_skip_blanks(tok), "force", 5);
			} else {
				global_outboundproxy.force = FALSE;
			}

			if (ast_strlen_zero(proxyname)) {
				ast_log(LOG_WARNING, "you must specify a name for the outboundproxy on line %d of sip.conf.", v->lineno);
				global_outboundproxy.name[0] = '\0';
				continue;
			}

			ast_copy_string(global_outboundproxy.name, proxyname, sizeof(global_outboundproxy.name));

			proxy_update(&global_outboundproxy);
		} else if (!strcasecmp(v->name, "autocreatepeer")) {
			autocreatepeer = ast_true(v->value);
		} else if (!strcasecmp(v->name, "match_auth_username")) {
			global_match_auth_username = ast_true(v->value);
		} else if (!strcasecmp(v->name, "srvlookup")) {
			global_srvlookup = ast_true(v->value);
		} else if (!strcasecmp(v->name, "pedantic")) {
			pedanticsipchecking = ast_true(v->value);
		} else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
			max_expiry = atoi(v->value);
			if (max_expiry < 1)
				max_expiry = DEFAULT_MAX_EXPIRY;
		} else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
			min_expiry = atoi(v->value);
			if (min_expiry < 1)
				min_expiry = DEFAULT_MIN_EXPIRY;
		} else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
			default_expiry = atoi(v->value);
			if (default_expiry < 1)
				default_expiry = DEFAULT_DEFAULT_EXPIRY;
		} else if (!strcasecmp(v->name, "sipdebug")) {
			if (ast_true(v->value))
				sipdebug |= sip_debug_config;
		} else if (!strcasecmp(v->name, "dumphistory")) {
			dumphistory = ast_true(v->value);
		} else if (!strcasecmp(v->name, "recordhistory")) {
			recordhistory = ast_true(v->value);
		} else if (!strcasecmp(v->name, "registertimeout")) {
			global_reg_timeout = atoi(v->value);
			if (global_reg_timeout < 1)
				global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
		} else if (!strcasecmp(v->name, "registerattempts")) {
			global_regattempts_max = atoi(v->value);
		} else if (!strcasecmp(v->name, "stunaddr")) {
			stunaddr.sin_port = htons(3478);
			if (ast_parse_arg(v->value, PARSE_INADDR, &stunaddr))
				ast_log(LOG_WARNING, "Invalid STUN server address: %s\n", v->value);
			externexpire = time(NULL);
		} else if (!strcasecmp(v->name, "bindaddr")) {
			if (ast_parse_arg(v->value, PARSE_INADDR, &bindaddr))
				ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
		} else if (!strcasecmp(v->name, "localnet")) {
			struct ast_ha *na;
			int ha_error = 0;

			if (!(na = ast_append_ha("d", v->value, localaddr, &ha_error)))
				ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
			else
				localaddr = na;
			if (ha_error)
				ast_log(LOG_ERROR, "Bad localnet configuration value line %d : %s\n", v->lineno, v->value);
		} else if (!strcasecmp(v->name, "externip")) {
			if (ast_parse_arg(v->value, PARSE_INADDR, &externip))
				ast_log(LOG_WARNING, "Invalid address for externip keyword: %s\n", v->value);
			externexpire = 0;
			/* If no port was specified use the value of bindport */
			if (!externip.sin_port)
				externip.sin_port = bindaddr.sin_port;
		} else if (!strcasecmp(v->name, "externhost")) {
			ast_copy_string(externhost, v->value, sizeof(externhost));
			if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
				ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
			externexpire = time(NULL);
			/* If no port was specified use the value of bindport */
			if (!externip.sin_port)
				externip.sin_port = bindaddr.sin_port;
		} else if (!strcasecmp(v->name, "externrefresh")) {
			if (sscanf(v->value, "%30d", &externrefresh) != 1) {
				ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
				externrefresh = 10;
			}
		} else if (!strcasecmp(v->name, "allow")) {
			int error =  ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, TRUE);
			if (error)
				ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
		} else if (!strcasecmp(v->name, "disallow")) {
			int error =  ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, FALSE);
			if (error)
				ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
		} else if (!strcasecmp(v->name, "autoframing")) {
			global_autoframing = ast_true(v->value);
		} else if (!strcasecmp(v->name, "allowexternaldomains")) {
			allow_external_domains = ast_true(v->value);
		} else if (!strcasecmp(v->name, "autodomain")) {
			auto_sip_domains = ast_true(v->value);
		} else if (!strcasecmp(v->name, "domain")) {
			char *domain = ast_strdupa(v->value);
			char *context = strchr(domain, ',');

			if (context)
				*context++ = '\0';

			if (ast_strlen_zero(context))
				ast_debug(1, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
			if (ast_strlen_zero(domain))
				ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
			else
				add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, context ? ast_strip(context) : "");
		} else if (!strcasecmp(v->name, "register")) {
			if (sip_register(v->value, v->lineno) == 0)
				registry_count++;
		} else if (!strcasecmp(v->name, "tos_sip")) {
			if (ast_str2tos(v->value, &global_tos_sip))
				ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, refer to QoS documentation\n", v->lineno);
		} else if (!strcasecmp(v->name, "tos_audio")) {
			if (ast_str2tos(v->value, &global_tos_audio))
				ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, refer to QoS documentation\n", v->lineno);
		} else if (!strcasecmp(v->name, "tos_video")) {
			if (ast_str2tos(v->value, &global_tos_video))
				ast_log(LOG_WARNING, "Invalid tos_video value at line %d, refer to QoS documentation\n", v->lineno);
		} else if (!strcasecmp(v->name, "tos_text")) {
			if (ast_str2tos(v->value, &global_tos_text))
				ast_log(LOG_WARNING, "Invalid tos_text value at line %d, refer to QoS documentation\n", v->lineno);
		} else if (!strcasecmp(v->name, "cos_sip")) {
			if (ast_str2cos(v->value, &global_cos_sip))
				ast_log(LOG_WARNING, "Invalid cos_sip value at line %d, refer to QoS documentation\n", v->lineno);
		} else if (!strcasecmp(v->name, "cos_audio")) {
			if (ast_str2cos(v->value, &global_cos_audio))
				ast_log(LOG_WARNING, "Invalid cos_audio value at line %d, refer to QoS documentation\n", v->lineno);
		} else if (!strcasecmp(v->name, "cos_video")) {
			if (ast_str2cos(v->value, &global_cos_video))
				ast_log(LOG_WARNING, "Invalid cos_video value at line %d, refer to QoS documentation\n", v->lineno);
		} else if (!strcasecmp(v->name, "cos_text")) {
			if (ast_str2cos(v->value, &global_cos_text))
				ast_log(LOG_WARNING, "Invalid cos_text value at line %d, refer to QoS documentation\n", v->lineno);
		} else if (!strcasecmp(v->name, "bindport")) {
			int i;
			if (sscanf(v->value, "%5d", &i) == 1) {
				bindaddr.sin_port = htons(i);
			} else {
				ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
			}
		} else if (!strcasecmp(v->name, "qualify")) {
			if (!strcasecmp(v->value, "no")) {
				default_qualify = 0;
			} else if (!strcasecmp(v->value, "yes")) {
				default_qualify = DEFAULT_MAXMS;
			} else if (sscanf(v->value, "%30d", &default_qualify) != 1) {
				ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
				default_qualify = 0;
			}
		} else if (!strcasecmp(v->name, "qualifyfreq")) {
			int i;
			if (sscanf(v->value, "%30d", &i) == 1)
				global_qualifyfreq = i * 1000;
			else {
				ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
				global_qualifyfreq = DEFAULT_QUALIFYFREQ;
			}
		} else if (!strcasecmp(v->name, "callevents")) {
			global_callevents = ast_true(v->value);
		} else if (!strcasecmp(v->name, "maxcallbitrate")) {
			default_maxcallbitrate = atoi(v->value);
			if (default_maxcallbitrate < 0)
				default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
		} else if (!strcasecmp(v->name, "matchexterniplocally")) {
			global_matchexterniplocally = ast_true(v->value);
		} else if (!strcasecmp(v->name, "session-timers")) {
			int i = (int) str2stmode(v->value); 
			if (i < 0) {
				ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
				global_st_mode = SESSION_TIMER_MODE_ACCEPT;
			} else {
				global_st_mode = i;
			}
		} else if (!strcasecmp(v->name, "session-expires")) {
			if (sscanf(v->value, "%30d", &global_max_se) != 1) {
				ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
				global_max_se = DEFAULT_MAX_SE;
			} 
		} else if (!strcasecmp(v->name, "session-minse")) {
			if (sscanf(v->value, "%30d", &global_min_se) != 1) {
				ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
				global_min_se = DEFAULT_MIN_SE;
			} 
			if (global_min_se < 90) {
				ast_log(LOG_WARNING, "session-minse '%s' at line %d of %s is not allowed to be < 90 secs\n", v->value, v->lineno, config);
				global_min_se = DEFAULT_MIN_SE;
			} 
		} else if (!strcasecmp(v->name, "session-refresher")) {
			int i = (int) str2strefresher(v->value); 
			if (i < 0) {
				ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
				global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
			} else {
				global_st_refresher = i;
			}
		} else if (!strcasecmp(v->name, "shrinkcallerid")) {
			if (ast_true(v->value)) {
				global_shrinkcallerid = 1;
			} else if (ast_false(v->value)) {
				global_shrinkcallerid = 0;
			} else {
				ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
			}
		}
	}

	if (!allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
		ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
		allow_external_domains = 1;
	}
	
	/* Build list of authentication to various SIP realms, i.e. service providers */
 	for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
 		/* Format for authentication is auth = username:password@realm */
 		if (!strcasecmp(v->name, "auth"))
 			authl = add_realm_authentication(authl, v->value, v->lineno);
 	}
	
	if (ucfg) {
		struct ast_variable *gen;
		int genhassip, genregistersip;
		const char *hassip, *registersip;
		
		genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
		genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
		gen = ast_variable_browse(ucfg, "general");
		cat = ast_category_browse(ucfg, NULL);
		while (cat) {
			if (strcasecmp(cat, "general")) {
				hassip = ast_variable_retrieve(ucfg, cat, "hassip");
				registersip = ast_variable_retrieve(ucfg, cat, "registersip");
				if (ast_true(hassip) || (!hassip && genhassip)) {
					user = build_user(cat, gen, ast_variable_browse(ucfg, cat), 0);
					if (user) {
						ASTOBJ_CONTAINER_LINK(&userl,user);
						ASTOBJ_UNREF(user, sip_destroy_user);
						user_count++;
					}
					peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0, 0);
					if (peer) {
						ASTOBJ_CONTAINER_LINK(&peerl, peer);
						unref_peer(peer);
						peer_count++;
					}
				}
				if (ast_true(registersip) || (!registersip && genregistersip)) {
					char tmp[256];
					const char *host = ast_variable_retrieve(ucfg, cat, "host");
					const char *username = ast_variable_retrieve(ucfg, cat, "username");
					const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
					const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
					const char *authuser = ast_variable_retrieve(ucfg, cat, "authuser");
					if (!host)
						host = ast_variable_retrieve(ucfg, "general", "host");
					if (!username)
						username = ast_variable_retrieve(ucfg, "general", "username");
					if (!secret)
						secret = ast_variable_retrieve(ucfg, "general", "secret");
					if (!contact)
						contact = "s";
					if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
						if (!ast_strlen_zero(secret)) {
							if (!ast_strlen_zero(authuser)) {
								snprintf(tmp, sizeof(tmp), "%s:%s:%s@%s/%s", username, secret, authuser, host, contact);
							} else {
								snprintf(tmp, sizeof(tmp), "%s:%s@%s/%s", username, secret, host, contact);
							}
						} else if (!ast_strlen_zero(authuser)) {
							snprintf(tmp, sizeof(tmp), "%s::%s@%s/%s", username, authuser, host, contact);
						} else {
							snprintf(tmp, sizeof(tmp), "%s@%s/%s", username, host, contact);
						}
						if (sip_register(tmp, 0) == 0)
							registry_count++;
					}
				}
			}
			cat = ast_category_browse(ucfg, cat);
		}
		ast_config_destroy(ucfg);
	}
	

	/* Load peers, users and friends */
	cat = NULL;
	while ( (cat = ast_category_browse(cfg, cat)) ) {
		const char *utype;
		if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
			continue;
		utype = ast_variable_retrieve(cfg, cat, "type");
		if (!utype) {
			ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
			continue;
		} else {
			int is_user = 0, is_peer = 0;
			if (!strcasecmp(utype, "user"))
				is_user = 1;
			else if (!strcasecmp(utype, "friend"))
				is_user = is_peer = 1;
			else if (!strcasecmp(utype, "peer"))
				is_peer = 1;
			else {
				ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
				continue;
			}
			if (is_user) {
				user = build_user(cat, ast_variable_browse(cfg, cat), NULL, 0);
				if (user) {
					ASTOBJ_CONTAINER_LINK(&userl, user);
					unref_user(user);
					user_count++;
				}
			}
			if (is_peer) {
				peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0, 0);
				if (peer) {
					ASTOBJ_CONTAINER_LINK(&peerl, peer);
					unref_peer(peer);
					peer_count++;
				}
			}
		}
	}
	/* Set UDP address and open socket */
	bindaddr.sin_family = AF_INET;
	internip = bindaddr;
	if (ast_find_ourip(&internip.sin_addr, bindaddr)) {
		ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
		ast_config_destroy(cfg);
		return 0;
	}
	ast_mutex_lock(&netlock);
	if ((sipsock > -1) && (memcmp(&old_bindaddr, &bindaddr, sizeof(struct sockaddr_in)))) {
		close(sipsock);
		sipsock = -1;
	}
	if (sipsock < 0) {
		sipsock = socket(AF_INET, SOCK_DGRAM, 0);
		if (sipsock < 0) {
			ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
			ast_config_destroy(cfg);
			return -1;
		} else {
			/* Allow SIP clients on the same host to access us: */
			const int reuseFlag = 1;

			setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
				   (const char*)&reuseFlag,
				   sizeof reuseFlag);

			ast_enable_packet_fragmentation(sipsock);

			if (bind(sipsock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
				ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
				ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
				strerror(errno));
				close(sipsock);
				sipsock = -1;
			} else {
				ast_verb(2, "SIP Listening on %s:%d\n",
						ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port));
				ast_netsock_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
			}
		}
	}
	if (stunaddr.sin_addr.s_addr != 0) {
		ast_debug(1, "stun to %s:%d\n",
			ast_inet_ntoa(stunaddr.sin_addr) , ntohs(stunaddr.sin_port));
		ast_stun_request(sipsock, &stunaddr,
			NULL, &externip);
		ast_debug(1, "STUN sees us at %s:%d\n", 
			ast_inet_ntoa(externip.sin_addr) , ntohs(externip.sin_port));
	}
	ast_mutex_unlock(&netlock);

	/* Start TCP server */
	ast_tcptls_server_start(&sip_tcp_desc);

	/* Start TLS server if needed */
	memcpy(sip_tls_desc.tls_cfg, &default_tls_cfg, sizeof(default_tls_cfg));

	if (ast_ssl_setup(sip_tls_desc.tls_cfg))
		ast_tcptls_server_start(&sip_tls_desc);
	else if (sip_tls_desc.tls_cfg->enabled) {
		sip_tls_desc.tls_cfg = NULL;
		ast_log(LOG_WARNING, "SIP TLS server did not load because of errors.\n");
	}


	/* Add default domains - host name, IP address and IP:port
	 * Only do this if user added any sip domain with "localdomains" 
	 * In order to *not* break backwards compatibility 
	 * 	Some phones address us at IP only, some with additional port number 
	 */
	if (auto_sip_domains) {
		char temp[MAXHOSTNAMELEN];

		/* First our default IP address */
		if (bindaddr.sin_addr.s_addr)
			add_sip_domain(ast_inet_ntoa(bindaddr.sin_addr), SIP_DOMAIN_AUTO, NULL);
		else
			ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");

		/* If TCP is running on a different IP than UDP, then add it too */
		if (sip_tcp_desc.sin.sin_addr.s_addr && !inaddrcmp(&bindaddr, &sip_tcp_desc.sin))
			add_sip_domain(ast_inet_ntoa(sip_tcp_desc.sin.sin_addr), SIP_DOMAIN_AUTO, NULL);

		/* If TLS is running on a differen IP than UDP and TCP, then add that too */
		if (sip_tls_desc.sin.sin_addr.s_addr && !inaddrcmp(&bindaddr, &sip_tls_desc.sin) && inaddrcmp(&sip_tcp_desc.sin, &sip_tls_desc.sin))
			add_sip_domain(ast_inet_ntoa(sip_tls_desc.sin.sin_addr), SIP_DOMAIN_AUTO, NULL);

		/* Our extern IP address, if configured */
		if (externip.sin_addr.s_addr)
			add_sip_domain(ast_inet_ntoa(externip.sin_addr), SIP_DOMAIN_AUTO, NULL);

		/* Extern host name (NAT traversal support) */
		if (!ast_strlen_zero(externhost))
			add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
		
		/* Our host name */
		if (!gethostname(temp, sizeof(temp)))
			add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
	}

	/* Release configuration from memory */
	ast_config_destroy(cfg);

	/* Load the list of manual NOTIFY types to support */
	if (notify_types)
		ast_config_destroy(notify_types);
	notify_types = ast_config_load(notify_config, config_flags);

	/* Done, tell the manager */
	manager_event(EVENT_FLAG_SYSTEM, "ChannelReload", "ChannelType: SIP\r\nReloadReason: %s\r\nRegistry_Count: %d\r\nPeer_Count: %d\r\nUser_Count: %d\r\n", channelreloadreason2txt(reason), registry_count, peer_count, user_count);

	return 0;
}

static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
{
	struct sip_pvt *p;
	struct ast_udptl *udptl = NULL;
	
	p = chan->tech_pvt;
	if (!p)
		return NULL;
	
	sip_pvt_lock(p);
	if (p->udptl && ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
		udptl = p->udptl;
	sip_pvt_unlock(p);
	return udptl;
}

static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
{
	struct sip_pvt *p;
	
	p = chan->tech_pvt;
	if (!p)
		return -1;
	sip_pvt_lock(p);
	if (udptl)
		ast_udptl_get_peer(udptl, &p->udptlredirip);
	else
		memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
	if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
		if (!p->pendinginvite) {
			ast_debug(3, "Sending reinvite on SIP '%s' - It's UDPTL soon redirected to IP %s:%d\n", p->callid, ast_inet_ntoa(udptl ? p->udptlredirip.sin_addr : p->ourip.sin_addr), udptl ? ntohs(p->udptlredirip.sin_port) : 0);
			transmit_reinvite_with_sdp(p, TRUE, FALSE);
		} else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
			ast_debug(3, "Deferring reinvite on SIP '%s' - It's UDPTL will be redirected to IP %s:%d\n", p->callid, ast_inet_ntoa(udptl ? p->udptlredirip.sin_addr : p->ourip.sin_addr), udptl ? ntohs(p->udptlredirip.sin_port) : 0);
			ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
		}
	}
	/* Reset lastrtprx timer */
	p->lastrtprx = p->lastrtptx = time(NULL);
	sip_pvt_unlock(p);
	return 0;
}

/*! \brief Returns null if we can't reinvite audio (part of RTP interface) */
static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
{
	struct sip_pvt *p = NULL;
	enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;

	if (!(p = chan->tech_pvt))
		return AST_RTP_GET_FAILED;

	sip_pvt_lock(p);
	if (!(p->rtp)) {
		sip_pvt_unlock(p);
		return AST_RTP_GET_FAILED;
	}

	*rtp = p->rtp;

	if (ast_rtp_getnat(*rtp) && !ast_test_flag(&p->flags[0], SIP_CAN_REINVITE_NAT))
		res = AST_RTP_TRY_PARTIAL;
	else if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
		res = AST_RTP_TRY_NATIVE;
	else if (ast_test_flag(&global_jbconf, AST_JB_FORCED))
		res = AST_RTP_GET_FAILED;

	sip_pvt_unlock(p);

	return res;
}

/*! \brief Returns null if we can't reinvite video (part of RTP interface) */
static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
{
	struct sip_pvt *p = NULL;
	enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
	
	if (!(p = chan->tech_pvt))
		return AST_RTP_GET_FAILED;

	sip_pvt_lock(p);
	if (!(p->vrtp)) {
		sip_pvt_unlock(p);
		return AST_RTP_GET_FAILED;
	}

	*rtp = p->vrtp;

	if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
		res = AST_RTP_TRY_NATIVE;

	sip_pvt_unlock(p);

	return res;
}

/*! \brief Returns null if we can't reinvite text (part of RTP interface) */
static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
{
	struct sip_pvt *p = NULL;
	enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
	
	if (!(p = chan->tech_pvt))
		return AST_RTP_GET_FAILED;

	sip_pvt_lock(p);
	if (!(p->trtp)) {
		sip_pvt_unlock(p);
		return AST_RTP_GET_FAILED;
	}

	*rtp = p->trtp;

	if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
		res = AST_RTP_TRY_NATIVE;

	sip_pvt_unlock(p);

	return res;
}

/*! \brief Set the RTP peer for this call */
static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, struct ast_rtp *trtp, int codecs, int nat_active)
{
	struct sip_pvt *p;
	int changed = 0;

	p = chan->tech_pvt;
	if (!p) 
		return -1;

	/* Disable early RTP bridge  */
	if (!ast_bridged_channel(chan) && !global_directrtpsetup) 	/* We are in early state */
		return 0;

	sip_pvt_lock(p);
	if (p->alreadygone) {
		/* If we're destroyed, don't bother */
		sip_pvt_unlock(p);
		return 0;
	}

	/* if this peer cannot handle reinvites of the media stream to devices
	   that are known to be behind a NAT, then stop the process now
	*/
	if (nat_active && !ast_test_flag(&p->flags[0], SIP_CAN_REINVITE_NAT)) {
		sip_pvt_unlock(p);
		return 0;
	}

	if (rtp) {
		changed |= ast_rtp_get_peer(rtp, &p->redirip);
	} else if (p->redirip.sin_addr.s_addr || ntohs(p->redirip.sin_port) != 0) {
		memset(&p->redirip, 0, sizeof(p->redirip));
		changed = 1;
	}
	if (vrtp) {
		changed |= ast_rtp_get_peer(vrtp, &p->vredirip);
	} else if (p->vredirip.sin_addr.s_addr || ntohs(p->vredirip.sin_port) != 0) {
		memset(&p->vredirip, 0, sizeof(p->vredirip));
		changed = 1;
	}
	if (trtp) {
		changed |= ast_rtp_get_peer(trtp, &p->tredirip);
	} else if (p->tredirip.sin_addr.s_addr || ntohs(p->tredirip.sin_port) != 0) {
		memset(&p->tredirip, 0, sizeof(p->tredirip));
		changed = 1;
	}
	if (codecs && (p->redircodecs != codecs)) {
		p->redircodecs = codecs;
		changed = 1;
	}
	if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER) && !ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
		if (chan->_state != AST_STATE_UP) {	/* We are in early state */
			if (p->do_history)
				append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
			ast_debug(1, "Early remote bridge setting SIP '%s' - Sending media to %s\n", p->callid, ast_inet_ntoa(rtp ? p->redirip.sin_addr : p->ourip.sin_addr));
		} else if (!p->pendinginvite) {		/* We are up, and have no outstanding invite */
			ast_debug(3, "Sending reinvite on SIP '%s' - It's audio soon redirected to IP %s\n", p->callid, ast_inet_ntoa(rtp ? p->redirip.sin_addr : p->ourip.sin_addr));
			transmit_reinvite_with_sdp(p, FALSE, FALSE);
		} else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
			ast_debug(3, "Deferring reinvite on SIP '%s' - It's audio will be redirected to IP %s\n", p->callid, ast_inet_ntoa(rtp ? p->redirip.sin_addr : p->ourip.sin_addr));
			/* We have a pending Invite. Send re-invite when we're done with the invite */
			ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);	
		}
	}
	/* Reset lastrtprx timer */
	p->lastrtprx = p->lastrtptx = time(NULL);
	sip_pvt_unlock(p);
	return 0;
}

static char *synopsis_dtmfmode = "Change the dtmfmode for a SIP call";
static char *descrip_dtmfmode = "  SIPDtmfMode(inband|info|rfc2833): Changes the dtmfmode for a SIP call\n";
static char *app_dtmfmode = "SIPDtmfMode";

static char *app_sipaddheader = "SIPAddHeader";
static char *synopsis_sipaddheader = "Add a SIP header to the outbound call";

static char *descrip_sipaddheader = ""
"  SIPAddHeader(Header: Content):\n"
"Adds a header to a SIP call placed with DIAL.\n"
"Remember to user the X-header if you are adding non-standard SIP\n"
"headers, like \"X-Asterisk-Accountcode:\". Use this with care.\n"
"Adding the wrong headers may jeopardize the SIP dialog.\n"
"Always returns 0\n";


/*! \brief Set the DTMFmode for an outbound SIP call (application) */
static int sip_dtmfmode(struct ast_channel *chan, void *data)
{
	struct sip_pvt *p;
	char *mode = data;

	if (!data) {
		ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
		return 0;
	}
	ast_channel_lock(chan);
	if (!IS_SIP_TECH(chan->tech)) {
		ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
		ast_channel_unlock(chan);
		return 0;
	}
	p = chan->tech_pvt;
	if (!p) {
		ast_channel_unlock(chan);
		return 0;
	}
	sip_pvt_lock(p);
	if (!strcasecmp(mode, "info")) {
		ast_clear_flag(&p->flags[0], SIP_DTMF);
		ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
		p->jointnoncodeccapability &= ~AST_RTP_DTMF;
	} else if (!strcasecmp(mode, "shortinfo")) {
		ast_clear_flag(&p->flags[0], SIP_DTMF);
		ast_set_flag(&p->flags[0], SIP_DTMF_SHORTINFO);
		p->jointnoncodeccapability &= ~AST_RTP_DTMF;
	} else if (!strcasecmp(mode, "rfc2833")) {
		ast_clear_flag(&p->flags[0], SIP_DTMF);
		ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
		p->jointnoncodeccapability |= AST_RTP_DTMF;
	} else if (!strcasecmp(mode, "inband")) { 
		ast_clear_flag(&p->flags[0], SIP_DTMF);
		ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
		p->jointnoncodeccapability &= ~AST_RTP_DTMF;
	} else
		ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n", mode);
	if (p->rtp)
		ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
	if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
		if (!p->dsp) {
			p->dsp = ast_dsp_new();
			ast_dsp_set_features(p->dsp, DSP_FEATURE_DTMF_DETECT);
		}
	} else {
		if (p->dsp) {
			ast_dsp_free(p->dsp);
			p->dsp = NULL;
		}
	}
	sip_pvt_unlock(p);
	ast_channel_unlock(chan);
	return 0;
}

/*! \brief Add a SIP header to an outbound INVITE */
static int sip_addheader(struct ast_channel *chan, void *data)
{
	int no = 0;
	int ok = FALSE;
	char varbuf[30];
	char *inbuf = data, *subbuf;
	
	if (ast_strlen_zero(inbuf)) {
		ast_log(LOG_WARNING, "This application requires the argument: Header\n");
		return 0;
	}
	ast_channel_lock(chan);

	/* Check for headers */
	while (!ok && no <= 50) {
		no++;
		snprintf(varbuf, sizeof(varbuf), "__SIPADDHEADER%.2d", no);

		/* Compare without the leading underscores */
		if ((pbx_builtin_getvar_helper(chan, (const char *) varbuf + 2) == (const char *) NULL)) {
			ok = TRUE;
		}
	}
	if (ok) {
		size_t len = strlen(inbuf);
		subbuf = alloca(len + 1);
		ast_get_encoded_str(inbuf, subbuf, len + 1);
		pbx_builtin_setvar_helper(chan, varbuf, subbuf);
		if (sipdebug) {
			ast_debug(1, "SIP Header added \"%s\" as %s\n", inbuf, varbuf);
		}
	} else {
		ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
	}
	ast_channel_unlock(chan);
	return 0;
}

/*! \brief Transfer call before connect with a 302 redirect
\note	Called by the transfer() dialplan application through the sip_transfer()
	pbx interface function if the call is in ringing state 
\todo	Fix this function so that we wait for reply to the REFER and
	react to errors, denials or other issues the other end might have.
 */
static int sip_sipredirect(struct sip_pvt *p, const char *dest)
{
	char *cdest;
	char *extension, *host, *port;
	char tmp[80];

	cdest = ast_strdupa(dest);
	
	extension = strsep(&cdest, "@");
	host = strsep(&cdest, ":");
	port = strsep(&cdest, ":");
	if (ast_strlen_zero(extension)) {
		ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
		return 0;
	}

	/* we'll issue the redirect message here */
	if (!host) {
		char *localtmp;

		ast_copy_string(tmp, get_header(&p->initreq, "To"), sizeof(tmp));
		if (ast_strlen_zero(tmp)) {
			ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
			return 0;
		}
		if ( ( (localtmp = strcasestr(tmp, "sip:")) || (localtmp = strcasestr(tmp, "sips:")) ) 
			&& (localtmp = strchr(localtmp, '@'))) {
			char lhost[80], lport[80];

			memset(lhost, 0, sizeof(lhost));
			memset(lport, 0, sizeof(lport));
			localtmp++;
			/* This is okey because lhost and lport are as big as tmp */
			sscanf(localtmp, "%80[^<>:; ]:%80[^<>:; ]", lhost, lport);
			if (ast_strlen_zero(lhost)) {
				ast_log(LOG_ERROR, "Can't find the host address\n");
				return 0;
			}
			host = ast_strdupa(lhost);
			if (!ast_strlen_zero(lport)) {
				port = ast_strdupa(lport);
			}
		}
	}

	ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s%s%s>", extension, host, port ? ":" : "", port ? port : "");
	transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);

	sip_scheddestroy(p, SIP_TRANS_TIMEOUT);	/* Make sure we stop send this reply. */
	sip_alreadygone(p);
	/* hangup here */
	return 0;
}

/*! \brief Return SIP UA's codec (part of the RTP interface) */
static int sip_get_codec(struct ast_channel *chan)
{
	struct sip_pvt *p = chan->tech_pvt;
	return p->peercapability ? p->peercapability : p->capability;	
}

/*! \brief Send a poke to all known peers 
	Space them out 100 ms apart
	XXX We might have a cool algorithm for this or use random - any suggestions?
*/
static void sip_poke_all_peers(void)
{
	int ms = 0;
	
	if (!speerobjs)	/* No peers, just give up */
		return;

	ASTOBJ_CONTAINER_TRAVERSE(&peerl, 1, do {
		ASTOBJ_WRLOCK(iterator);
		ms += 100;
		AST_SCHED_REPLACE(iterator->pokeexpire, sched, ms, sip_poke_peer_s, iterator);
		ASTOBJ_UNLOCK(iterator);
	} while (0)
	);
}

/*! \brief Send all known registrations */
static void sip_send_all_registers(void)
{
	int ms;
	int regspacing;
	if (!regobjs)
		return;
	regspacing = default_expiry * 1000/regobjs;
	if (regspacing > 100)
		regspacing = 100;
	ms = regspacing;
	ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
		ASTOBJ_WRLOCK(iterator);
		ms += regspacing;
		AST_SCHED_REPLACE(iterator->expire, 
			sched, ms, sip_reregister, iterator);
		ASTOBJ_UNLOCK(iterator);
	} while (0)
	);
}

/*! \brief Reload module */
static int sip_do_reload(enum channelreloadreason reason)
{
	reload_config(reason);

	/* Prune peers who still are supposed to be deleted */
	ASTOBJ_CONTAINER_PRUNE_MARKED(&peerl, sip_destroy_peer);
	ast_debug(4, "--------------- Done destroying pruned peers\n");

	/* Send qualify (OPTIONS) to all peers */
	sip_poke_all_peers();

	/* Register with all services */
	sip_send_all_registers();

	ast_debug(4, "--------------- SIP reload done\n");

	return 0;
}

/*! \brief Force reload of module from cli */
static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
	
	switch (cmd) {
	case CLI_INIT:
		e->command = "sip reload";
		e->usage =
			"Usage: sip reload\n"
			"       Reloads SIP configuration from sip.conf\n";
		return NULL;
	case CLI_GENERATE:
		return NULL;
	}

	ast_mutex_lock(&sip_reload_lock);
	if (sip_reloading) 
		ast_verbose("Previous SIP reload not yet done\n");
	else {
		sip_reloading = TRUE;
		sip_reloadreason = (a && a->fd) ? CHANNEL_CLI_RELOAD : CHANNEL_MODULE_RELOAD;
	}
	ast_mutex_unlock(&sip_reload_lock);
	restart_monitor();

	return CLI_SUCCESS;
}

/*! \brief  Part of Asterisk module interface */
static int reload(void)
{
	if (sip_reload(0, 0, NULL))
		return 0;
	return 1;
}

static struct ast_cli_entry cli_sip_do_history_deprecated = AST_CLI_DEFINE(sip_do_history_deprecated, "Enable/Disable SIP history");
/*! \brief SIP Cli commands definition */
static struct ast_cli_entry cli_sip[] = {
	AST_CLI_DEFINE(sip_show_channels, "List active SIP channels/subscriptions"),
	AST_CLI_DEFINE(sip_show_domains, "List our local SIP domains"),
	AST_CLI_DEFINE(sip_show_inuse, "List all inuse/limits"),
	AST_CLI_DEFINE(sip_show_objects, "List all SIP object allocations"),
	AST_CLI_DEFINE(sip_show_peers, "List defined SIP peers"),
	AST_CLI_DEFINE(sip_show_registry, "List SIP registration status"),
	AST_CLI_DEFINE(sip_unregister, "Unregister (force expiration) a SIP peer from the registry"),
	AST_CLI_DEFINE(sip_show_settings, "Show SIP global settings"),
	AST_CLI_DEFINE(sip_notify, "Send a notify packet to a SIP peer"),
	AST_CLI_DEFINE(sip_show_channel, "Show detailed SIP channel info"),
	AST_CLI_DEFINE(sip_show_history, "Show SIP dialog history"),
	AST_CLI_DEFINE(sip_show_peer, "Show details on specific SIP peer"),
	AST_CLI_DEFINE(sip_show_users, "List defined SIP users"),
	AST_CLI_DEFINE(sip_show_user, "Show details on specific SIP user"),
	AST_CLI_DEFINE(sip_prune_realtime, "Prune cached Realtime users/peers"),
	AST_CLI_DEFINE(sip_do_debug, "Enable/Disable SIP debugging"),
	AST_CLI_DEFINE(sip_set_history, "Enable/Disable SIP history", .deprecate_cmd = &cli_sip_do_history_deprecated),
	AST_CLI_DEFINE(sip_reload, "Reload SIP configuration"),
	AST_CLI_DEFINE(sip_show_tcp, "List TCP Connections")
};

/*! \brief PBX load module - initialization */
static int load_module(void)
{
	ast_verbose("SIP channel loading...\n");
	ASTOBJ_CONTAINER_INIT(&userl);	/* User object list */
	ASTOBJ_CONTAINER_INIT(&peerl);	/* Peer object list */
	ASTOBJ_CONTAINER_INIT(&regl);	/* Registry object list */

	if (!(sched = sched_context_create())) {
		ast_log(LOG_ERROR, "Unable to create scheduler context\n");
		return AST_MODULE_LOAD_FAILURE;
	}

	if (!(io = io_context_create())) {
		ast_log(LOG_ERROR, "Unable to create I/O context\n");
		sched_context_destroy(sched);
		return AST_MODULE_LOAD_FAILURE;
	}

	sip_reloadreason = CHANNEL_MODULE_LOAD;

	if(reload_config(sip_reloadreason))	/* Load the configuration from sip.conf */
		return AST_MODULE_LOAD_DECLINE;

	/* Prepare the version that does not require DTMF BEGIN frames.
	 * We need to use tricks such as memcpy and casts because the variable
	 * has const fields.
	 */
	memcpy(&sip_tech_info, &sip_tech, sizeof(sip_tech));
	memset((void *) &sip_tech_info.send_digit_begin, 0, sizeof(sip_tech_info.send_digit_begin));

	/* Make sure we can register our sip channel type */
	if (ast_channel_register(&sip_tech)) {
		ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
		io_context_destroy(io);
		sched_context_destroy(sched);
		return AST_MODULE_LOAD_FAILURE;
	}

	/* Register all CLI functions for SIP */
	ast_cli_register_multiple(cli_sip, sizeof(cli_sip)/ sizeof(struct ast_cli_entry));

	/* Tell the RTP subdriver that we're here */
	ast_rtp_proto_register(&sip_rtp);

	/* Tell the UDPTL subdriver that we're here */
	ast_udptl_proto_register(&sip_udptl);

	/* Register dialplan applications */
	ast_register_application(app_dtmfmode, sip_dtmfmode, synopsis_dtmfmode, descrip_dtmfmode);
	ast_register_application(app_sipaddheader, sip_addheader, synopsis_sipaddheader, descrip_sipaddheader);

	/* Register dialplan functions */
	ast_custom_function_register(&sip_header_function);
	ast_custom_function_register(&sippeer_function);
	ast_custom_function_register(&sipchaninfo_function);
	ast_custom_function_register(&checksipdomain_function);

	/* Register manager commands */
	ast_manager_register2("SIPpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peers,
			"List SIP peers (text format)", mandescr_show_peers);
	ast_manager_register2("SIPshowpeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peer,
			"Show SIP peer (text format)", mandescr_show_peer);
	ast_manager_register2("SIPshowregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_show_registry,
			"Show SIP registrations (text format)", mandescr_show_registry);
	sip_poke_all_peers();	
	sip_send_all_registers();
	
	/* And start the monitor for the first time */
	restart_monitor();

	return AST_MODULE_LOAD_SUCCESS;
}

/*! \brief PBX unload module API */
static int unload_module(void)
{
	struct sip_pvt *p, *pl;
	struct sip_threadinfo *th;
	struct ast_context *con;
	
	/* First, take us out of the channel type list */
	ast_channel_unregister(&sip_tech);

	/* Unregister dial plan functions */
	ast_custom_function_unregister(&sipchaninfo_function);
	ast_custom_function_unregister(&sippeer_function);
	ast_custom_function_unregister(&sip_header_function);
	ast_custom_function_unregister(&checksipdomain_function);

	/* Unregister dial plan applications */
	ast_unregister_application(app_dtmfmode);
	ast_unregister_application(app_sipaddheader);

	/* Unregister CLI commands */
	ast_cli_unregister_multiple(cli_sip, sizeof(cli_sip) / sizeof(struct ast_cli_entry));

	/* Disconnect from the RTP subsystem */
	ast_rtp_proto_unregister(&sip_rtp);

	/* Disconnect from UDPTL */
	ast_udptl_proto_unregister(&sip_udptl);

	/* Unregister AMI actions */
	ast_manager_unregister("SIPpeers");
	ast_manager_unregister("SIPshowpeer");
	ast_manager_unregister("SIPshowregistry");

	/* Kill TCP/TLS server threads */
	if (sip_tcp_desc.master)
		ast_tcptls_server_stop(&sip_tcp_desc);
	if (sip_tls_desc.master)
		ast_tcptls_server_stop(&sip_tls_desc);

	/* Kill all existing TCP/TLS threads */
	AST_LIST_LOCK(&threadl);
	AST_LIST_TRAVERSE_SAFE_BEGIN(&threadl, th, list) {
		pthread_t thread = th->threadid;
		th->stop = 1;
		AST_LIST_UNLOCK(&threadl);
		pthread_kill(thread, SIGURG);
		pthread_join(thread, NULL);
		AST_LIST_LOCK(&threadl);
	}
	AST_LIST_TRAVERSE_SAFE_END;
	AST_LIST_UNLOCK(&threadl);

	dialoglist_lock();
	/* Hangup all dialogs if they have an owner */
	for (p = dialoglist; p ; p = p->next) {
		if (p->owner)
			ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
	}
	dialoglist_unlock();

	ast_mutex_lock(&monlock);
	if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
		pthread_cancel(monitor_thread);
		pthread_kill(monitor_thread, SIGURG);
		pthread_join(monitor_thread, NULL);
	}
	monitor_thread = AST_PTHREADT_STOP;
	ast_mutex_unlock(&monlock);

restartdestroy:
	dialoglist_lock();
	/* Destroy all the dialogs and free their memory */
	p = dialoglist;
	while (p) {
		pl = p;
		p = p->next;
		if (dialog_cleanup_and_destroy(pl) < 0) {
			/* Something is still bridged, let it react to getting a hangup */
			dialoglist = p;
			dialoglist_unlock();
			usleep(1);
			goto restartdestroy;
		}
	}
	dialoglist = NULL;
	dialoglist_unlock();

	/* Free memory for local network address mask */
	ast_free_ha(localaddr);

	if (default_tls_cfg.certfile)
		ast_free(default_tls_cfg.certfile);
	if (default_tls_cfg.cipher)
		ast_free(default_tls_cfg.cipher);
	if (default_tls_cfg.cafile)
		ast_free(default_tls_cfg.cafile);
	if (default_tls_cfg.capath)
		ast_free(default_tls_cfg.capath);

	ASTOBJ_CONTAINER_DESTROYALL(&userl, sip_destroy_user);
	ASTOBJ_CONTAINER_DESTROY(&userl);
	ASTOBJ_CONTAINER_DESTROYALL(&peerl, sip_destroy_peer);
	ASTOBJ_CONTAINER_DESTROY(&peerl);
	ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
	ASTOBJ_CONTAINER_DESTROY(&regl);

	clear_realm_authentication(authl);
	clear_sip_domains();
	ast_free_ha(global_contact_ha);
	close(sipsock);
	sched_context_destroy(sched);
	con = ast_context_find(used_context);
	if (con)
		ast_context_destroy(con, "SIP");

	return 0;
}

AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Session Initiation Protocol (SIP)",
		.load = load_module,
		.unload = unload_module,
		.reload = reload,
	       );