File: chan_skinny.c

package info (click to toggle)
asterisk 1:13.14.1~dfsg-2+deb9u4
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 50,572 kB
  • sloc: ansic: 675,986; sh: 11,363; python: 3,925; sql: 3,634; makefile: 3,153; perl: 3,103; yacc: 2,164; cpp: 2,093; xml: 786; tcl: 113; php: 62
file content (8810 lines) | stat: -rw-r--r-- 281,894 bytes parent folder | download
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
/*
 * Asterisk -- An open source telephony toolkit.
 *
 * Copyright (C) 1999 - 2005, Digium, Inc.
 *
 * chan_skinny was developed by Jeremy McNamara & Florian Overkamp
 * chan_skinny was heavily modified/fixed by North Antara
 *
 * 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 the Skinny protocol
 *
 * \author Jeremy McNamara & Florian Overkamp & North Antara
 * \ingroup channel_drivers
 */

/*! \li \ref chan_skinny.c uses the configuration file \ref skinny.conf
 * \addtogroup configuration_file
 */

/*! \page skinny.conf skinny.conf
 * \verbinclude skinny.conf.sample
 */

/*** MODULEINFO
	<support_level>extended</support_level>
 ***/

#include "asterisk.h"

ASTERISK_FILE_VERSION(__FILE__, "$Revision$")

#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <fcntl.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/signal.h>
#include <signal.h>
#include <ctype.h>

#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_engine.h"
#include "asterisk/netsock2.h"
#include "asterisk/acl.h"
#include "asterisk/callerid.h"
#include "asterisk/cli.h"
#include "asterisk/manager.h"
#include "asterisk/say.h"
#include "asterisk/astdb.h"
#include "asterisk/causes.h"
#include "asterisk/pickup.h"
#include "asterisk/app.h"
#include "asterisk/musiconhold.h"
#include "asterisk/utils.h"
#include "asterisk/dsp.h"
#include "asterisk/stringfields.h"
#include "asterisk/abstract_jb.h"
#include "asterisk/threadstorage.h"
#include "asterisk/devicestate.h"
#include "asterisk/indications.h"
#include "asterisk/linkedlists.h"
#include "asterisk/stasis_endpoints.h"
#include "asterisk/bridge.h"
#include "asterisk/parking.h"
#include "asterisk/stasis_channels.h"
#include "asterisk/format_cache.h"

/*** DOCUMENTATION
	<manager name="SKINNYdevices" language="en_US">
		<synopsis>
			List SKINNY devices (text format).
		</synopsis>
		<syntax>
			<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
		</syntax>
		<description>
			<para>Lists Skinny devices in text format with details on current status.
			Devicelist will follow as separate events, followed by a final event called
			DevicelistComplete.</para>
		</description>
	</manager>
	<manager name="SKINNYshowdevice" language="en_US">
		<synopsis>
			Show SKINNY device (text format).
		</synopsis>
		<syntax>
			<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
			<parameter name="Device" required="true">
				<para>The device name you want to check.</para>
			</parameter>
		</syntax>
		<description>
			<para>Show one SKINNY device with details on current status.</para>
		</description>
	</manager>
	<manager name="SKINNYlines" language="en_US">
		<synopsis>
			List SKINNY lines (text format).
		</synopsis>
		<syntax>
			<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
		</syntax>
		<description>
			<para>Lists Skinny lines in text format with details on current status.
			Linelist will follow as separate events, followed by a final event called
			LinelistComplete.</para>
		</description>
	</manager>
	<manager name="SKINNYshowline" language="en_US">
		<synopsis>
			Show SKINNY line (text format).
		</synopsis>
		<syntax>
			<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
			<parameter name="Line" required="true">
				<para>The line name you want to check.</para>
			</parameter>
		</syntax>
		<description>
			<para>Show one SKINNY line with details on current status.</para>
		</description>
	</manager>
 ***/

/* Skinny debugging only available if asterisk configured with --enable-dev-mode */
#ifdef AST_DEVMODE
static int skinnydebug = 0;
char dbgcli_buf[256];
#define DEBUG_GENERAL	(1 << 1)
#define DEBUG_SUB	(1 << 2)
#define DEBUG_PACKET	(1 << 3)
#define DEBUG_AUDIO	(1 << 4)
#define DEBUG_LOCK	(1 << 5)
#define DEBUG_TEMPLATE	(1 << 6)
#define DEBUG_THREAD	(1 << 7)
#define DEBUG_HINT	(1 << 8)
#define DEBUG_KEEPALIVE (1 << 9)
#define SKINNY_DEBUG(type, verb_level, text, ...)						\
	do{											\
		if (skinnydebug & (type)) {							\
			ast_verb(verb_level, "[%d] " text, ast_get_tid(), ##__VA_ARGS__);	\
		}										\
	}while(0)
#else
#define SKINNY_DEBUG(type, verb_level, text, ...)
#endif

/*************************************
 * Skinny/Asterisk Protocol Settings *
 *************************************/
static const char tdesc[] = "Skinny Client Control Protocol (Skinny)";
static const char config[] = "skinny.conf";

static struct ast_format_cap *default_cap;

enum skinny_codecs {
	SKINNY_CODEC_ALAW = 2,
	SKINNY_CODEC_ULAW = 4,
	SKINNY_CODEC_G722 = 6,
	SKINNY_CODEC_G723_1 = 9,
	SKINNY_CODEC_G729A = 12,
	SKINNY_CODEC_G726_32 = 82, /* XXX Which packing order does this translate to? */
	SKINNY_CODEC_H261 = 100,
	SKINNY_CODEC_H263 = 101
};

#define DEFAULT_SKINNY_PORT 2000
#define DEFAULT_SKINNY_BACKLOG 2
#define SKINNY_MAX_PACKET 2000
#define DEFAULT_AUTH_TIMEOUT 30
#define DEFAULT_AUTH_LIMIT 50

static struct {
	unsigned int tos;
	unsigned int tos_audio;
	unsigned int tos_video;
	unsigned int cos;
	unsigned int cos_audio;
	unsigned int cos_video;
} qos = { 0, 0, 0, 0, 0, 0 };

static int keep_alive = 120;
static int auth_timeout = DEFAULT_AUTH_TIMEOUT;
static int auth_limit = DEFAULT_AUTH_LIMIT;
static int unauth_sessions = 0;
static char immed_dialchar;
static char vmexten[AST_MAX_EXTENSION];      /* Voicemail pilot number */
static char used_context[AST_MAX_EXTENSION]; /* placeholder to check if context are already used in regcontext */
static char regcontext[AST_MAX_CONTEXT];     /* Context for auto-extension */
static char date_format[6] = "D-M-Y";
static char version_id[16] = "P002F202";

#if __BYTE_ORDER == __LITTLE_ENDIAN
#define letohl(x) (x)
#define letohs(x) (x)
#define htolel(x) (x)
#define htoles(x) (x)
#else
#if defined(HAVE_BYTESWAP_H)
#include <byteswap.h>
#define letohl(x) bswap_32(x)
#define letohs(x) bswap_16(x)
#define htolel(x) bswap_32(x)
#define htoles(x) bswap_16(x)
#elif defined(HAVE_SYS_ENDIAN_SWAP16)
#include <sys/endian.h>
#define letohl(x) __swap32(x)
#define letohs(x) __swap16(x)
#define htolel(x) __swap32(x)
#define htoles(x) __swap16(x)
#elif defined(HAVE_SYS_ENDIAN_BSWAP16)
#include <sys/endian.h>
#define letohl(x) bswap32(x)
#define letohs(x) bswap16(x)
#define htolel(x) bswap32(x)
#define htoles(x) bswap16(x)
#else
#define __bswap_16(x) \
	((((x) & 0xff00) >> 8) | \
	 (((x) & 0x00ff) << 8))
#define __bswap_32(x) \
	((((x) & 0xff000000) >> 24) | \
	 (((x) & 0x00ff0000) >>  8) | \
	 (((x) & 0x0000ff00) <<  8) | \
	 (((x) & 0x000000ff) << 24))
#define letohl(x) __bswap_32(x)
#define letohs(x) __bswap_16(x)
#define htolel(x) __bswap_32(x)
#define htoles(x) __bswap_16(x)
#endif
#endif

/*! Global jitterbuffer configuration - by default, jb is disabled
 *  \note Values shown here match the defaults shown in skinny.conf.sample */
static struct ast_jb_conf default_jbconf =
{
	.flags = 0,
	.max_size = 200,
	.resync_threshold = 1000,
	.impl = "fixed",
	.target_extra = 40,
};
static struct ast_jb_conf global_jbconf;

#ifdef AST_DEVMODE
AST_THREADSTORAGE(message2str_threadbuf);
#define MESSAGE2STR_BUFSIZE   35
#endif

AST_THREADSTORAGE(device2str_threadbuf);
#define DEVICE2STR_BUFSIZE   15

AST_THREADSTORAGE(control2str_threadbuf);
#define CONTROL2STR_BUFSIZE   100

AST_THREADSTORAGE(substate2str_threadbuf);
#define SUBSTATE2STR_BUFSIZE   15

AST_THREADSTORAGE(callstate2str_threadbuf);
#define CALLSTATE2STR_BUFSIZE   15

/*********************
 * Protocol Messages *
 *********************/
/* message types */
#define KEEP_ALIVE_MESSAGE 0x0000
/* no additional struct */

#define REGISTER_MESSAGE 0x0001
struct register_message {
	char name[16];
	uint32_t userId;
	uint32_t instance;
	uint32_t ip;
	uint32_t type;
	uint32_t maxStreams;
	uint32_t space;
	uint8_t protocolVersion;
	/*! \brief space2 is used for newer version of skinny */
	char space2[3];
};

#define IP_PORT_MESSAGE 0x0002

#define KEYPAD_BUTTON_MESSAGE 0x0003
struct keypad_button_message {
	uint32_t button;
	uint32_t lineInstance;
	uint32_t callReference;
};


#define ENBLOC_CALL_MESSAGE 0x0004
struct enbloc_call_message {
	char calledParty[24];
};

#define STIMULUS_MESSAGE 0x0005
struct stimulus_message {
	uint32_t stimulus;
	uint32_t stimulusInstance;
	uint32_t callreference;
};

#define OFFHOOK_MESSAGE 0x0006
struct offhook_message {
	uint32_t instance;
	uint32_t reference;
};

#define ONHOOK_MESSAGE 0x0007
struct onhook_message {
	uint32_t instance;
	uint32_t reference;
};

#define CAPABILITIES_RES_MESSAGE 0x0010
struct station_capabilities {
	uint32_t codec; /* skinny codec, not ast codec */
	uint32_t frames;
	union {
		char res[8];
		uint32_t rate;
	} payloads;
};

#define SKINNY_MAX_CAPABILITIES 18

struct capabilities_res_message {
	uint32_t count;
	struct station_capabilities caps[SKINNY_MAX_CAPABILITIES];
};

#define SPEED_DIAL_STAT_REQ_MESSAGE 0x000A
struct speed_dial_stat_req_message {
	uint32_t speedDialNumber;
};

#define LINE_STATE_REQ_MESSAGE 0x000B
struct line_state_req_message {
	uint32_t lineNumber;
};

#define TIME_DATE_REQ_MESSAGE 0x000D
#define BUTTON_TEMPLATE_REQ_MESSAGE 0x000E
#define VERSION_REQ_MESSAGE 0x000F
#define SERVER_REQUEST_MESSAGE 0x0012

#define ALARM_MESSAGE 0x0020
struct alarm_message {
	uint32_t alarmSeverity;
	char displayMessage[80];
	uint32_t alarmParam1;
	uint32_t alarmParam2;
};

#define OPEN_RECEIVE_CHANNEL_ACK_MESSAGE 0x0022
struct open_receive_channel_ack_message_ip4 {
	uint32_t status;
	uint32_t ipAddr;
	uint32_t port;
	uint32_t callReference;
};
struct open_receive_channel_ack_message_ip6 {
	uint32_t status;
	uint32_t space;
	char ipAddr[16];
	uint32_t port;
	uint32_t callReference;
};

#define SOFT_KEY_SET_REQ_MESSAGE 0x0025

#define SOFT_KEY_EVENT_MESSAGE 0x0026
struct soft_key_event_message {
	uint32_t softKeyEvent;
	uint32_t instance;
	uint32_t callreference;
};

#define UNREGISTER_MESSAGE 0x0027
#define SOFT_KEY_TEMPLATE_REQ_MESSAGE 0x0028
#define HEADSET_STATUS_MESSAGE 0x002B
#define REGISTER_AVAILABLE_LINES_MESSAGE 0x002D

#define SERVICEURL_STATREQ_MESSAGE 0x0033
struct serviceurl_statreq_message {
	uint32_t instance;
};

#define REGISTER_ACK_MESSAGE 0x0081
struct register_ack_message {
	uint32_t keepAlive;
	char dateTemplate[6];
	char res[2];
	uint32_t secondaryKeepAlive;
	char res2[4];
};

#define START_TONE_MESSAGE 0x0082
struct start_tone_message {
	uint32_t tone;
	uint32_t space;
	uint32_t instance;
	uint32_t reference;
};

#define STOP_TONE_MESSAGE 0x0083
struct stop_tone_message {
	uint32_t instance;
	uint32_t reference;
	uint32_t space;
};

#define SET_RINGER_MESSAGE 0x0085
struct set_ringer_message {
	uint32_t ringerMode;
	uint32_t unknown1; /* See notes in transmit_ringer_mode */
	uint32_t unknown2;
	uint32_t space[2];
};

#define SET_LAMP_MESSAGE 0x0086
struct set_lamp_message {
	uint32_t stimulus;
	uint32_t stimulusInstance;
	uint32_t deviceStimulus;
};

#define SET_SPEAKER_MESSAGE 0x0088
struct set_speaker_message {
	uint32_t mode;
};

/* XXX When do we need to use this? */
#define SET_MICROPHONE_MESSAGE 0x0089
struct set_microphone_message {
	uint32_t mode;
};

#define START_MEDIA_TRANSMISSION_MESSAGE 0x008A
struct media_qualifier {
	uint32_t precedence;
	uint32_t vad;
	uint32_t packets;
	uint32_t bitRate;
};

struct start_media_transmission_message_ip4 {
	uint32_t conferenceId;
	uint32_t passThruPartyId;
	uint32_t remoteIp;
	uint32_t remotePort;
	uint32_t packetSize;
	uint32_t payloadType;
	struct media_qualifier qualifier;
	uint32_t space[19];
};

struct start_media_transmission_message_ip6 {
	uint32_t conferenceId;
	uint32_t passThruPartyId;
	uint32_t space;
	char remoteIp[16];
	uint32_t remotePort;
	uint32_t packetSize;
	uint32_t payloadType;
	struct media_qualifier qualifier;
	/*! \brief space2 is used for newer version of skinny */
	uint32_t space2[19];
};

#define STOP_MEDIA_TRANSMISSION_MESSAGE 0x008B
struct stop_media_transmission_message {
	uint32_t conferenceId;
	uint32_t passThruPartyId;
	uint32_t space[3];
};

#define CALL_INFO_MESSAGE 0x008F
struct call_info_message {
	char callingPartyName[40];
	char callingParty[24];
	char calledPartyName[40];
	char calledParty[24];
	uint32_t instance;
	uint32_t reference;
	uint32_t type;
	char originalCalledPartyName[40];
	char originalCalledParty[24];
	char lastRedirectingPartyName[40];
	char lastRedirectingParty[24];
	uint32_t originalCalledPartyRedirectReason;
	uint32_t lastRedirectingReason;
	char callingPartyVoiceMailbox[24];
	char calledPartyVoiceMailbox[24];
	char originalCalledPartyVoiceMailbox[24];
	char lastRedirectingVoiceMailbox[24];
	uint32_t space[3];
};

#define FORWARD_STAT_MESSAGE 0x0090
struct forward_stat_message {
	uint32_t activeforward;
	uint32_t lineNumber;
	uint32_t fwdall;
	char fwdallnum[24];
	uint32_t fwdbusy;
	char fwdbusynum[24];
	uint32_t fwdnoanswer;
	char fwdnoanswernum[24];
};

#define SPEED_DIAL_STAT_RES_MESSAGE 0x0091
struct speed_dial_stat_res_message {
	uint32_t speedDialNumber;
	char speedDialDirNumber[24];
	char speedDialDisplayName[40];
};

#define LINE_STAT_RES_MESSAGE 0x0092
struct line_stat_res_message {
	uint32_t lineNumber;
	char lineDirNumber[24];
	char lineDisplayName[24];
	uint32_t space[15];
};

#define DEFINETIMEDATE_MESSAGE 0x0094
struct definetimedate_message {
	uint32_t year; /* since 1900 */
	uint32_t month;
	uint32_t dayofweek; /* monday = 1 */
	uint32_t day;
	uint32_t hour;
	uint32_t minute;
	uint32_t seconds;
	uint32_t milliseconds;
	uint32_t timestamp;
};

#define BUTTON_TEMPLATE_RES_MESSAGE 0x0097
struct button_definition {
	uint8_t instanceNumber;
	uint8_t buttonDefinition;
};

struct button_definition_template {
	uint8_t buttonDefinition;
	/* for now, anything between 0xB0 and 0xCF is custom */
	/*int custom;*/
};

#define STIMULUS_REDIAL 0x01
#define STIMULUS_SPEEDDIAL 0x02
#define STIMULUS_HOLD 0x03
#define STIMULUS_TRANSFER 0x04
#define STIMULUS_FORWARDALL 0x05
#define STIMULUS_FORWARDBUSY 0x06
#define STIMULUS_FORWARDNOANSWER 0x07
#define STIMULUS_DISPLAY 0x08
#define STIMULUS_LINE 0x09
#define STIMULUS_VOICEMAIL 0x0F
#define STIMULUS_AUTOANSWER 0x11
#define STIMULUS_SERVICEURL 0x14
#define STIMULUS_DND 0x3F
#define STIMULUS_CONFERENCE 0x7D
#define STIMULUS_CALLPARK 0x7E
#define STIMULUS_CALLPICKUP 0x7F
#define STIMULUS_NONE 0xFF

/* Button types */
#define BT_REDIAL STIMULUS_REDIAL
#define BT_SPEEDDIAL STIMULUS_SPEEDDIAL
#define BT_HOLD STIMULUS_HOLD
#define BT_TRANSFER STIMULUS_TRANSFER
#define BT_FORWARDALL STIMULUS_FORWARDALL
#define BT_FORWARDBUSY STIMULUS_FORWARDBUSY
#define BT_FORWARDNOANSWER STIMULUS_FORWARDNOANSWER
#define BT_DISPLAY STIMULUS_DISPLAY
#define BT_LINE STIMULUS_LINE
#define BT_VOICEMAIL STIMULUS_VOICEMAIL
#define BT_AUTOANSWER STIMULUS_AUTOANSWER
#define BT_SERVICEURL STIMULUS_SERVICEURL
#define BT_DND STIMULUS_DND
#define BT_CONFERENCE STIMULUS_CONFERENCE
#define BT_CALLPARK STIMULUS_CALLPARK
#define BT_CALLPICKUP STIMULUS_CALLPICKUP
#define BT_NONE 0x00

/* Custom button types - add our own between 0xB0 and 0xCF.
   This may need to be revised in the future,
   if stimuluses are ever added in this range. */
#define BT_CUST_LINESPEEDDIAL 0xB0 /* line or speeddial with/without hint */
#define BT_CUST_LINE 0xB1          /* line or speeddial with hint only */

struct button_template_res_message {
	uint32_t buttonOffset;
	uint32_t buttonCount;
	uint32_t totalButtonCount;
	struct button_definition definition[42];
};

#define VERSION_RES_MESSAGE 0x0098
struct version_res_message {
	char version[16];
};

#define DISPLAYTEXT_MESSAGE 0x0099
struct displaytext_message {
	char text[40];
};

#define CLEAR_NOTIFY_MESSAGE  0x0115
#define CLEAR_DISPLAY_MESSAGE 0x009A
struct clear_display_message {
	uint32_t space;
};

#define CAPABILITIES_REQ_MESSAGE 0x009B

#define REGISTER_REJ_MESSAGE 0x009D
struct register_rej_message {
	char errMsg[33];
};

#define SERVER_RES_MESSAGE 0x009E
struct server_identifier {
	char serverName[48];
};

struct server_res_message {
	struct server_identifier server[5];
	uint32_t serverListenPort[5];
	uint32_t serverIpAddr[5];
};

#define RESET_MESSAGE 0x009F
struct reset_message {
	uint32_t resetType;
};

#define KEEP_ALIVE_ACK_MESSAGE 0x0100

#define OPEN_RECEIVE_CHANNEL_MESSAGE 0x0105
struct open_receive_channel_message {
	uint32_t conferenceId;
	uint32_t partyId;
	uint32_t packets;
	uint32_t capability;
	uint32_t echo;
	uint32_t bitrate;
	uint32_t space[36];
};

#define CLOSE_RECEIVE_CHANNEL_MESSAGE 0x0106
struct close_receive_channel_message {
	uint32_t conferenceId;
	uint32_t partyId;
	uint32_t space[2];
};

#define SOFT_KEY_TEMPLATE_RES_MESSAGE 0x0108
struct soft_key_template_definition {
	char softKeyLabel[16];
	uint32_t softKeyEvent;
};

#define BKSP_REQ_MESSAGE 0x0119
struct bksp_req_message {
	uint32_t instance;
	uint32_t callreference;
};

#define KEYDEF_ONHOOK 0
#define KEYDEF_CONNECTED 1
#define KEYDEF_ONHOLD 2
#define KEYDEF_RINGIN 3
#define KEYDEF_OFFHOOK 4
#define KEYDEF_CONNWITHTRANS 5
#define KEYDEF_DADFD 6 /* Digits After Dialing First Digit */
#define KEYDEF_CONNWITHCONF 7
#define KEYDEF_RINGOUT 8
#define KEYDEF_OFFHOOKWITHFEAT 9
#define KEYDEF_UNKNOWN 10
#define KEYDEF_SLAHOLD 11
#define KEYDEF_SLACONNECTEDNOTACTIVE 12
#define KEYDEF_RINGOUTWITHTRANS 13

#define SOFTKEY_NONE 0x00
#define SOFTKEY_REDIAL 0x01
#define SOFTKEY_NEWCALL 0x02
#define SOFTKEY_HOLD 0x03
#define SOFTKEY_TRNSFER 0x04
#define SOFTKEY_CFWDALL 0x05
#define SOFTKEY_CFWDBUSY 0x06
#define SOFTKEY_CFWDNOANSWER 0x07
#define SOFTKEY_BKSPC 0x08
#define SOFTKEY_ENDCALL 0x09
#define SOFTKEY_RESUME 0x0A
#define SOFTKEY_ANSWER 0x0B
#define SOFTKEY_INFO 0x0C
#define SOFTKEY_CONFRN 0x0D
#define SOFTKEY_PARK 0x0E
#define SOFTKEY_JOIN 0x0F
#define SOFTKEY_MEETME 0x10
#define SOFTKEY_PICKUP 0x11
#define SOFTKEY_GPICKUP 0x12
#define SOFTKEY_DND 0x13
#define SOFTKEY_IDIVERT 0x14
#define SOFTKEY_FORCEDIAL 0x15

#define KEYMASK_ALL            0xFFFFFFFF
#define KEYMASK_NONE           (1 << 0)
#define KEYMASK_REDIAL         (1 << 1)
#define KEYMASK_NEWCALL        (1 << 2)
#define KEYMASK_HOLD           (1 << 3)
#define KEYMASK_TRNSFER        (1 << 4)
#define KEYMASK_CFWDALL        (1 << 5)
#define KEYMASK_CFWDBUSY       (1 << 6)
#define KEYMASK_CFWDNOANSWER   (1 << 7)
#define KEYMASK_BKSPC          (1 << 8)
#define KEYMASK_ENDCALL        (1 << 9)
#define KEYMASK_RESUME         (1 << 10)
#define KEYMASK_ANSWER         (1 << 11)
#define KEYMASK_INFO           (1 << 12)
#define KEYMASK_CONFRN         (1 << 13)
#define KEYMASK_PARK           (1 << 14)
#define KEYMASK_JOIN           (1 << 15)
#define KEYMASK_MEETME         (1 << 16)
#define KEYMASK_PICKUP         (1 << 17)
#define KEYMASK_GPICKUP        (1 << 18)
#define KEYMASK_DND            (1 << 29)
#define KEYMASK_IDIVERT        (1 << 20)
#define KEYMASK_FORCEDIAL      (1 << 21)

/* Localized message "codes" (in octal)
   Below is en_US (taken from a 7970) */

/*                            "\200\000"        ??? */
#define OCTAL_REDIAL          "\200\001"     /* Redial */
#define OCTAL_NEWCALL         "\200\002"     /* New Call */
#define OCTAL_HOLD            "\200\003"     /* Hold */
#define OCTAL_TRANSFER        "\200\004"     /* Transfer */
#define OCTAL_CFWDALL         "\200\005"     /* CFwdALL */
#define OCTAL_CFWDBUSY        "\200\006"     /* CFwdBusy */
#define OCTAL_CFWDNOAN        "\200\007"     /* CFwdNoAnswer */
#define OCTAL_BKSPC           "\200\010"     /* << */
#define OCTAL_ENDCALL         "\200\011"     /* EndCall */
#define OCTAL_RESUME          "\200\012"     /* Resume */
#define OCTAL_ANSWER          "\200\013"     /* Answer */
#define OCTAL_INFO            "\200\014"     /* Info */
#define OCTAL_CONFRN          "\200\015"     /* Confrn */
#define OCTAL_PARK            "\200\016"     /* Park */
#define OCTAL_JOIN            "\200\017"     /* Join */
#define OCTAL_MEETME          "\200\020"     /* MeetMe */
#define OCTAL_PICKUP          "\200\021"     /* PickUp */
#define OCTAL_GPICKUP         "\200\022"     /* GPickUp */
#define OCTAL_CUROPTS         "\200\023"     /* Your current options */
#define OCTAL_OFFHOOK         "\200\024"     /* Off Hook */
#define OCTAL_ONHOOK          "\200\025"     /* On Hook */
#define OCTAL_RINGOUT         "\200\026"     /* Ring out */
#define OCTAL_FROM            "\200\027"     /* From */
#define OCTAL_CONNECTED       "\200\030"     /* Connected */
#define OCTAL_BUSY            "\200\031"     /* Busy */
#define OCTAL_LINEINUSE       "\200\032"     /* Line In Use */
#define OCTAL_CALLWAITING     "\200\033"     /* Call Waiting */
#define OCTAL_CALLXFER        "\200\034"     /* Call Transfer */
#define OCTAL_CALLPARK        "\200\035"     /* Call Park */
#define OCTAL_CALLPROCEED     "\200\036"     /* Call Proceed */
#define OCTAL_INUSEREMOTE     "\200\037"     /* In Use Remote */
#define OCTAL_ENTRNUM         "\200\040"     /* Enter number */
#define OCTAL_PARKAT          "\200\041"     /* Call park At */
#define OCTAL_PRIMONLY        "\200\042"     /* Primary Only */
#define OCTAL_TMPFAIL         "\200\043"     /* Temp Fail */
#define OCTAL_HAVEVMAIL       "\200\044"     /* You Have VoiceMail */
#define OCTAL_FWDEDTO         "\200\045"     /* Forwarded to */
#define OCTAL_CANTCOMPCNF     "\200\046"     /* Can Not Complete Conference */
#define OCTAL_NOCONFBRDG      "\200\047"     /* No Conference Bridge */
#define OCTAL_NOPRIMARYCTL    "\200\050"     /* Can Not Hold Primary Control */
#define OCTAL_INVALCONFPART   "\200\051"     /* Invalid Conference Participant */
#define OCTAL_INCONFALREADY   "\200\052"     /* In Conference Already */
#define OCTAL_NOPARTINFO      "\200\053"     /* No Participant Info */
#define OCTAL_MAXPARTEXCEED   "\200\054"     /* Exceed Maximum Parties */
#define OCTAL_KEYNOTACTIVE    "\200\055"     /* Key Is Not Active */
#define OCTAL_ERRNOLIC        "\200\056"     /* Error No License */
#define OCTAL_ERRDBCFG        "\200\057"     /* Error DBConfig */
#define OCTAL_ERRDB           "\200\060"     /* Error Database */
#define OCTAL_ERRPASSLMT      "\200\061"     /* Error Pass Limit */
#define OCTAL_ERRUNK          "\200\062"     /* Error Unknown */
#define OCTAL_ERRMISMATCH     "\200\063"     /* Error Mismatch */
#define OCTAL_CONFERENCE      "\200\064"     /* Conference */
#define OCTAL_PARKNO          "\200\065"     /* Park Number */
#define OCTAL_PRIVATE         "\200\066"     /* Private */
#define OCTAL_INSUFBANDW      "\200\067"     /* Not Enough Bandwidth */
#define OCTAL_UNKNUM          "\200\070"     /* Unknown Number */
#define OCTAL_RMLSTC          "\200\071"     /* RmLstC */
#define OCTAL_VOICEMAIL       "\200\072"     /* Voicemail */
#define OCTAL_IMMDIV          "\200\073"     /* ImmDiv */
#define OCTAL_INTRCPT         "\200\074"     /* Intrcpt */
#define OCTAL_SETWTCH         "\200\075"     /* SetWtch */
#define OCTAL_TRNSFVM         "\200\076"     /* TrnsfVM */
#define OCTAL_DND             "\200\077"     /* DND */
#define OCTAL_DIVALL          "\200\100"     /* DivAll */
#define OCTAL_CALLBACK        "\200\101"     /* CallBack */
#define OCTAL_NETCNGREROUT    "\200\102"     /* Network congestion,rerouting */
#define OCTAL_BARGE           "\200\103"     /* Barge */
#define OCTAL_BARGEFAIL       "\200\104"     /* Failed to setup Barge */
#define OCTAL_BARGEEXIST      "\200\105"     /* Another Barge exists */
#define OCTAL_INCOMPATDEV     "\200\106"     /* Incompatible device type */
#define OCTAL_PARKNONUM       "\200\107"     /* No Park Number Available */
#define OCTAL_PARKREVERSION   "\200\110"     /* CallPark Reversion */
#define OCTAL_SRVNOTACTIVE    "\200\111"     /* Service is not Active */
#define OCTAL_HITRAFFIC       "\200\112"     /* High Traffic Try Again Later */
#define OCTAL_QRT             "\200\113"     /* QRT */
#define OCTAL_MCID            "\200\114"     /* MCID */
#define OCTAL_DIRTRFR         "\200\115"     /* DirTrfr */
#define OCTAL_SELECT          "\200\116"     /* Select */
#define OCTAL_CONFLIST        "\200\117"     /* ConfList */
#define OCTAL_IDIVERT         "\200\120"     /* iDivert */
#define OCTAL_CBARGE          "\200\121"     /* cBarge */
#define OCTAL_CANTCOMPLXFER   "\200\122"     /* Can Not Complete Transfer */
#define OCTAL_CANTJOINCALLS   "\200\123"     /* Can Not Join Calls */
#define OCTAL_MCIDSUCCESS     "\200\124"     /* Mcid Successful */
#define OCTAL_NUMNOTCFG       "\200\125"     /* Number Not Configured */
#define OCTAL_SECERROR        "\200\126"     /* Security Error */
#define OCTAL_VIDBANDWNA      "\200\127"     /* Video Bandwidth Unavailable */
#define OCTAL_VIDMODE         "\200\130"     /* VidMode */
#define OCTAL_CALLDURTIMEOUT  "\200\131"     /* Max Call Duration Timeout */
#define OCTAL_HOLDDURTIMEOUT  "\200\132"     /* Max Hold Duration Timeout */
#define OCTAL_OPICKUP         "\200\133"     /* OPickUp */
/*                            "\200\134"        ??? */
/*                            "\200\135"        ??? */
/*                            "\200\136"        ??? */
/*                            "\200\137"        ??? */
/*                            "\200\140"        ??? */
#define OCTAL_EXTXFERRESTRICT "\200\141"     /* External Transfer Restricted */
/*                            "\200\142"        ??? */
/*                            "\200\143"        ??? */
/*                            "\200\144"        ??? */
#define OCTAL_MACADD          "\200\145"     /* Mac Address */
#define OCTAL_HOST            "\200\146"     /* Host Name */
#define OCTAL_DOMAIN          "\200\147"     /* Domain Name */
#define OCTAL_IPADD           "\200\150"     /* IP Address */
#define OCTAL_SUBMASK         "\200\151"     /* Subnet Mask */
#define OCTAL_TFTP1           "\200\152"     /* TFTP Server 1 */
#define OCTAL_ROUTER1         "\200\153"     /* Default Router 1 */
#define OCTAL_ROUTER2         "\200\154"     /* Default Router 2 */
#define OCTAL_ROUTER3         "\200\155"     /* Default Router 3 */
#define OCTAL_ROUTER4         "\200\156"     /* Default Router 4 */
#define OCTAL_ROUTER5         "\200\157"     /* Default Router 5 */
#define OCTAL_DNS1            "\200\160"     /* DNS Server 1 */
#define OCTAL_DNS2            "\200\161"     /* DNS Server 2 */
#define OCTAL_DNS3            "\200\162"     /* DNS Server 3 */
#define OCTAL_DNS4            "\200\163"     /* DNS Server 4 */
#define OCTAL_DNS5            "\200\164"     /* DNS Server 5 */
#define OCTAL_VLANOPID        "\200\165"     /* Operational VLAN Id */
#define OCTAL_VLANADID        "\200\166"     /* Admin. VLAN Id */
#define OCTAL_CM1             "\200\167"     /* CallManager 1 */
#define OCTAL_CM2             "\200\170"     /* CallManager 2 */
#define OCTAL_CM3             "\200\171"     /* CallManager 3 */
#define OCTAL_CM4             "\200\172"     /* CallManager 4 */
#define OCTAL_CM5             "\200\173"     /* CallManager 5 */
#define OCTAL_URLINFO         "\200\174"     /* Information URL */
#define OCTAL_URLDIRS         "\200\175"     /* Directories URL */
#define OCTAL_URLMSGS         "\200\176"     /* Messages URL */
#define OCTAL_URLSRVS         "\200\177"     /* Services URL */

static struct soft_key_template_definition soft_key_template_default[] = {
	{ OCTAL_REDIAL, SOFTKEY_REDIAL },
	{ OCTAL_NEWCALL, SOFTKEY_NEWCALL },
	{ OCTAL_HOLD, SOFTKEY_HOLD },
	{ OCTAL_TRANSFER, SOFTKEY_TRNSFER },
	{ OCTAL_CFWDALL, SOFTKEY_CFWDALL },
	{ OCTAL_CFWDBUSY, SOFTKEY_CFWDBUSY },
	{ OCTAL_CFWDNOAN, SOFTKEY_CFWDNOANSWER },
	{ OCTAL_BKSPC, SOFTKEY_BKSPC },
	{ OCTAL_ENDCALL, SOFTKEY_ENDCALL },
	{ OCTAL_RESUME, SOFTKEY_RESUME },
	{ OCTAL_ANSWER, SOFTKEY_ANSWER },
	{ OCTAL_INFO, SOFTKEY_INFO },
	{ OCTAL_CONFRN, SOFTKEY_CONFRN },
	{ OCTAL_PARK, SOFTKEY_PARK },
	{ OCTAL_JOIN, SOFTKEY_JOIN },
	{ OCTAL_MEETME, SOFTKEY_MEETME },
	{ OCTAL_PICKUP, SOFTKEY_PICKUP },
	{ OCTAL_GPICKUP, SOFTKEY_GPICKUP },
	{ OCTAL_DND, SOFTKEY_DND },
	{ OCTAL_IDIVERT, SOFTKEY_IDIVERT },
	{ "Dial", SOFTKEY_FORCEDIAL},
};

struct soft_key_definitions {
	const uint8_t mode;
	const uint8_t *defaults;
	const int count;
};

static const uint8_t soft_key_default_onhook[] = {
	SOFTKEY_REDIAL,
	SOFTKEY_NEWCALL,
	SOFTKEY_CFWDALL,
	SOFTKEY_CFWDBUSY,
	SOFTKEY_CFWDNOANSWER,
	SOFTKEY_DND,
	SOFTKEY_GPICKUP,
	/*SOFTKEY_CONFRN,*/
};

static const uint8_t soft_key_default_connected[] = {
	SOFTKEY_HOLD,
	SOFTKEY_ENDCALL,
	SOFTKEY_TRNSFER,
	SOFTKEY_PARK,
	SOFTKEY_CFWDALL,
	SOFTKEY_CFWDBUSY,
	SOFTKEY_CFWDNOANSWER,
};

static const uint8_t soft_key_default_onhold[] = {
	SOFTKEY_RESUME,
	SOFTKEY_NEWCALL,
	SOFTKEY_ENDCALL,
	SOFTKEY_TRNSFER,
};

static const uint8_t soft_key_default_ringin[] = {
	SOFTKEY_ANSWER,
	SOFTKEY_ENDCALL,
	SOFTKEY_TRNSFER,
};

static const uint8_t soft_key_default_offhook[] = {
	SOFTKEY_REDIAL,
	SOFTKEY_ENDCALL,
	SOFTKEY_TRNSFER,
	SOFTKEY_CFWDALL,
	SOFTKEY_CFWDBUSY,
	SOFTKEY_CFWDNOANSWER,
	SOFTKEY_GPICKUP,
};

static const uint8_t soft_key_default_connwithtrans[] = {
	SOFTKEY_HOLD,
	SOFTKEY_ENDCALL,
	SOFTKEY_TRNSFER,
	SOFTKEY_PARK,
	SOFTKEY_CFWDALL,
	SOFTKEY_CFWDBUSY,
	SOFTKEY_CFWDNOANSWER,
};

static const uint8_t soft_key_default_dadfd[] = {
	SOFTKEY_BKSPC,
	SOFTKEY_ENDCALL,
	SOFTKEY_TRNSFER,
	SOFTKEY_FORCEDIAL,
};

static const uint8_t soft_key_default_connwithconf[] = {
	SOFTKEY_NONE,
};

static const uint8_t soft_key_default_ringout[] = {
	SOFTKEY_NONE,
	SOFTKEY_ENDCALL,
};

static const uint8_t soft_key_default_ringoutwithtransfer[] = {
	SOFTKEY_NONE,
	SOFTKEY_ENDCALL,
	SOFTKEY_TRNSFER,
};

static const uint8_t soft_key_default_offhookwithfeat[] = {
	SOFTKEY_REDIAL,
	SOFTKEY_ENDCALL,
	SOFTKEY_TRNSFER,
};

static const uint8_t soft_key_default_unknown[] = {
	SOFTKEY_NONE,
};

static const uint8_t soft_key_default_SLAhold[] = {
	SOFTKEY_REDIAL,
	SOFTKEY_NEWCALL,
	SOFTKEY_RESUME,
};

static const uint8_t soft_key_default_SLAconnectednotactive[] = {
	SOFTKEY_REDIAL,
	SOFTKEY_NEWCALL,
	SOFTKEY_JOIN,
};

static const struct soft_key_definitions soft_key_default_definitions[] = {
	{KEYDEF_ONHOOK, soft_key_default_onhook, sizeof(soft_key_default_onhook) / sizeof(uint8_t)},
	{KEYDEF_CONNECTED, soft_key_default_connected, sizeof(soft_key_default_connected) / sizeof(uint8_t)},
	{KEYDEF_ONHOLD, soft_key_default_onhold, sizeof(soft_key_default_onhold) / sizeof(uint8_t)},
	{KEYDEF_RINGIN, soft_key_default_ringin, sizeof(soft_key_default_ringin) / sizeof(uint8_t)},
	{KEYDEF_OFFHOOK, soft_key_default_offhook, sizeof(soft_key_default_offhook) / sizeof(uint8_t)},
	{KEYDEF_CONNWITHTRANS, soft_key_default_connwithtrans, sizeof(soft_key_default_connwithtrans) / sizeof(uint8_t)},
	{KEYDEF_DADFD, soft_key_default_dadfd, sizeof(soft_key_default_dadfd) / sizeof(uint8_t)},
	{KEYDEF_CONNWITHCONF, soft_key_default_connwithconf, sizeof(soft_key_default_connwithconf) / sizeof(uint8_t)},
	{KEYDEF_RINGOUT, soft_key_default_ringout, sizeof(soft_key_default_ringout) / sizeof(uint8_t)},
	{KEYDEF_RINGOUTWITHTRANS, soft_key_default_ringoutwithtransfer, sizeof(soft_key_default_ringoutwithtransfer) / sizeof(uint8_t)},
	{KEYDEF_OFFHOOKWITHFEAT, soft_key_default_offhookwithfeat, sizeof(soft_key_default_offhookwithfeat) / sizeof(uint8_t)},
	{KEYDEF_UNKNOWN, soft_key_default_unknown, sizeof(soft_key_default_unknown) / sizeof(uint8_t)},
	{KEYDEF_SLAHOLD, soft_key_default_SLAhold, sizeof(soft_key_default_SLAhold) / sizeof(uint8_t)},
	{KEYDEF_SLACONNECTEDNOTACTIVE, soft_key_default_SLAconnectednotactive, sizeof(soft_key_default_SLAconnectednotactive) / sizeof(uint8_t)}
};

struct soft_key_template_res_message {
	uint32_t softKeyOffset;
	uint32_t softKeyCount;
	uint32_t totalSoftKeyCount;
	struct soft_key_template_definition softKeyTemplateDefinition[32];
};

#define SOFT_KEY_SET_RES_MESSAGE 0x0109

struct soft_key_set_definition {
	uint8_t softKeyTemplateIndex[16];
	uint16_t softKeyInfoIndex[16];
};

struct soft_key_set_res_message {
	uint32_t softKeySetOffset;
	uint32_t softKeySetCount;
	uint32_t totalSoftKeySetCount;
	struct soft_key_set_definition softKeySetDefinition[16];
	uint32_t res;
};

#define SELECT_SOFT_KEYS_MESSAGE 0x0110
struct select_soft_keys_message {
	uint32_t instance;
	uint32_t reference;
	uint32_t softKeySetIndex;
	uint32_t validKeyMask;
};

#define CALL_STATE_MESSAGE 0x0111
struct call_state_message {
	uint32_t callState;
	uint32_t lineInstance;
	uint32_t callReference;
	uint32_t space[3];
};

#define DISPLAY_PROMPT_STATUS_MESSAGE 0x0112
struct display_prompt_status_message {
	uint32_t messageTimeout;
	char promptMessage[32];
	uint32_t lineInstance;
	uint32_t callReference;
	uint32_t space[3];
};

#define CLEAR_PROMPT_MESSAGE  0x0113
struct clear_prompt_message {
	uint32_t lineInstance;
	uint32_t callReference;
};

#define DISPLAY_NOTIFY_MESSAGE 0x0114
struct display_notify_message {
	uint32_t displayTimeout;
	char displayMessage[100];
};

#define ACTIVATE_CALL_PLANE_MESSAGE 0x0116
struct activate_call_plane_message {
	uint32_t lineInstance;
};

#define DIALED_NUMBER_MESSAGE 0x011D
struct dialed_number_message {
	char dialedNumber[24];
	uint32_t lineInstance;
	uint32_t callReference;
};

#define MAX_SERVICEURL 256
#define SERVICEURL_STAT_MESSAGE 0x012F
struct serviceurl_stat_message {
	uint32_t instance;
	char url[MAX_SERVICEURL];
	char displayName[40];
};

#define MAXCALLINFOSTR 256
#define MAXDISPLAYNOTIFYSTR 32

#define DISPLAY_PRINOTIFY_MESSAGE 0x0120
struct display_prinotify_message {
	uint32_t timeout;
	uint32_t priority;
	char text[MAXDISPLAYNOTIFYSTR];
};

#define CLEAR_PRINOTIFY_MESSAGE 0x0121
struct clear_prinotify_message {
	uint32_t priority;
};

#define CALL_INFO_MESSAGE_VARIABLE 0x014A
struct call_info_message_variable {
	uint32_t instance;
	uint32_t callreference;
	uint32_t calldirection;
	uint32_t unknown1;
	uint32_t unknown2;
	uint32_t unknown3;
	uint32_t unknown4;
	uint32_t unknown5;
	char calldetails[MAXCALLINFOSTR];
};

#define DISPLAY_PRINOTIFY_MESSAGE_VARIABLE 0x0144
struct display_prinotify_message_variable {
	uint32_t timeout;
	uint32_t priority;
	char text[MAXDISPLAYNOTIFYSTR];
};

#define DISPLAY_PROMPT_STATUS_MESSAGE_VARIABLE 0x0145
struct display_prompt_status_message_variable {
	uint32_t unknown;
	uint32_t lineInstance;
	uint32_t callReference;
	char promptMessage[MAXCALLINFOSTR];
};

union skinny_data {
	struct alarm_message alarm;
	struct speed_dial_stat_req_message speeddialreq;
	struct register_message reg;
	struct register_ack_message regack;
	struct register_rej_message regrej;
	struct capabilities_res_message caps;
	struct version_res_message version;
	struct button_template_res_message buttontemplate;
	struct displaytext_message displaytext;
	struct clear_display_message cleardisplay;
	struct display_prompt_status_message displaypromptstatus;
	struct clear_prompt_message clearpromptstatus;
	struct definetimedate_message definetimedate;
	struct start_tone_message starttone;
	struct stop_tone_message stoptone;
	struct speed_dial_stat_res_message speeddial;
	struct line_state_req_message line;
	struct line_stat_res_message linestat;
	struct soft_key_set_res_message softkeysets;
	struct soft_key_template_res_message softkeytemplate;
	struct server_res_message serverres;
	struct reset_message reset;
	struct set_lamp_message setlamp;
	struct set_ringer_message setringer;
	struct call_state_message callstate;
	struct keypad_button_message keypad;
	struct select_soft_keys_message selectsoftkey;
	struct activate_call_plane_message activatecallplane;
	struct stimulus_message stimulus;
	struct offhook_message offhook;
	struct onhook_message onhook;
	struct set_speaker_message setspeaker;
	struct set_microphone_message setmicrophone;
	struct call_info_message callinfo;
	struct start_media_transmission_message_ip4 startmedia_ip4;
	struct start_media_transmission_message_ip6 startmedia_ip6;
	struct stop_media_transmission_message stopmedia;
	struct open_receive_channel_message openreceivechannel;
	struct open_receive_channel_ack_message_ip4 openreceivechannelack_ip4;
	struct open_receive_channel_ack_message_ip6 openreceivechannelack_ip6;
	struct close_receive_channel_message closereceivechannel;
	struct display_notify_message displaynotify;
	struct dialed_number_message dialednumber;
	struct soft_key_event_message softkeyeventmessage;
	struct enbloc_call_message enbloccallmessage;
	struct forward_stat_message forwardstat;
	struct bksp_req_message bkspmessage;
	struct call_info_message_variable callinfomessagevariable;
	struct display_prompt_status_message_variable displaypromptstatusvar;
	struct serviceurl_stat_message serviceurlmessage;
	struct clear_prinotify_message clearprinotify;
	struct display_prinotify_message displayprinotify;
	struct display_prinotify_message_variable displayprinotifyvar;
};

/* packet composition */
struct skinny_req {
	uint32_t len;
	uint32_t res;
	uint32_t e;
	union skinny_data data;
};

/* XXX This is the combined size of the variables above.  (len, res, e)
   If more are added, this MUST change.
   (sizeof(skinny_req) - sizeof(skinny_data)) DOES NOT WORK on all systems (amd64?). */
static int skinny_header_size = 12;

/*****************************
 * Asterisk specific globals *
 *****************************/

static int skinnyreload = 0;

/* a hostname, portnumber, socket and such is usefull for VoIP protocols */
static struct sockaddr_in bindaddr;
static char ourhost[256];
static int ourport;
static struct in_addr __ourip;
static struct ast_hostent ahp;
static struct hostent *hp;
static int skinnysock = -1;
static pthread_t accept_t;
static int callnums = 1;

#define SKINNY_DEVICE_UNKNOWN -1
#define SKINNY_DEVICE_NONE 0
#define SKINNY_DEVICE_30SPPLUS 1
#define SKINNY_DEVICE_12SPPLUS 2
#define SKINNY_DEVICE_12SP 3
#define SKINNY_DEVICE_12 4
#define SKINNY_DEVICE_30VIP 5
#define SKINNY_DEVICE_7910 6
#define SKINNY_DEVICE_7960 7
#define SKINNY_DEVICE_7940 8
#define SKINNY_DEVICE_7935 9
#define SKINNY_DEVICE_ATA186 12 /* Cisco ATA-186 */
#define SKINNY_DEVICE_7941 115
#define SKINNY_DEVICE_7971 119
#define SKINNY_DEVICE_7914 124 /* Expansion module */
#define SKINNY_DEVICE_7985 302
#define SKINNY_DEVICE_7911 307
#define SKINNY_DEVICE_7961GE 308
#define SKINNY_DEVICE_7941GE 309
#define SKINNY_DEVICE_7931 348
#define SKINNY_DEVICE_7921 365
#define SKINNY_DEVICE_7906 369
#define SKINNY_DEVICE_7962 404 /* Not found */
#define SKINNY_DEVICE_7937 431
#define SKINNY_DEVICE_7942 434
#define SKINNY_DEVICE_7945 435
#define SKINNY_DEVICE_7965 436
#define SKINNY_DEVICE_7975 437
#define SKINNY_DEVICE_7905 20000
#define SKINNY_DEVICE_7920 30002
#define SKINNY_DEVICE_7970 30006
#define SKINNY_DEVICE_7912 30007
#define SKINNY_DEVICE_7902 30008
#define SKINNY_DEVICE_CIPC 30016 /* Cisco IP Communicator */
#define SKINNY_DEVICE_7961 30018
#define SKINNY_DEVICE_7936 30019
#define SKINNY_DEVICE_SCCPGATEWAY_AN 30027 /* Analog gateway */
#define SKINNY_DEVICE_SCCPGATEWAY_BRI 30028 /* BRI gateway */

#define SKINNY_SPEAKERON 1
#define SKINNY_SPEAKEROFF 2

#define SKINNY_MICON 1
#define SKINNY_MICOFF 2

#define SKINNY_OFFHOOK 1
#define SKINNY_ONHOOK 2
#define SKINNY_RINGOUT 3
#define SKINNY_RINGIN 4
#define SKINNY_CONNECTED 5
#define SKINNY_BUSY 6
#define SKINNY_CONGESTION 7
#define SKINNY_HOLD 8
#define SKINNY_CALLWAIT 9
#define SKINNY_TRANSFER 10
#define SKINNY_PARK 11
#define SKINNY_PROGRESS 12
#define SKINNY_CALLREMOTEMULTILINE 13
#define SKINNY_INVALID 14

#define SKINNY_INCOMING 1
#define SKINNY_OUTGOING 2

#define SKINNY_SILENCE 0x00		/* Note sure this is part of the protocol, remove? */
#define SKINNY_DIALTONE 0x21
#define SKINNY_BUSYTONE 0x23
#define SKINNY_ALERT 0x24
#define SKINNY_REORDER 0x25
#define SKINNY_CALLWAITTONE 0x2D
#define SKINNY_ZIPZIP 0x31
#define SKINNY_ZIP 0x32
#define SKINNY_BEEPBONK 0x33
#define SKINNY_BARGIN 0x43
#define SKINNY_NOTONE 0x7F

#define SKINNY_LAMP_OFF 1
#define SKINNY_LAMP_ON 2
#define SKINNY_LAMP_WINK 3
#define SKINNY_LAMP_FLASH 4
#define SKINNY_LAMP_BLINK 5

#define SKINNY_RING_OFF 1
#define SKINNY_RING_INSIDE 2
#define SKINNY_RING_OUTSIDE 3
#define SKINNY_RING_FEATURE 4

#define SKINNY_CFWD_ALL       (1 << 0)
#define SKINNY_CFWD_BUSY      (1 << 1)
#define SKINNY_CFWD_NOANSWER  (1 << 2)

/* Skinny rtp stream modes. Do we really need this? */
#define SKINNY_CX_SENDONLY 0
#define SKINNY_CX_RECVONLY 1
#define SKINNY_CX_SENDRECV 2
#define SKINNY_CX_CONF 3
#define SKINNY_CX_CONFERENCE 3
#define SKINNY_CX_MUTE 4
#define SKINNY_CX_INACTIVE 4

#if 0
static const char * const skinny_cxmodes[] = {
	"sendonly",
	"recvonly",
	"sendrecv",
	"confrnce",
	"inactive"
};
#endif

/* driver scheduler */
static struct ast_sched_context *sched = NULL;

/* Protect the network socket */
AST_MUTEX_DEFINE_STATIC(netlock);

/* Wait up to 16 seconds for first digit */
static int firstdigittimeout = 16000;

/* How long to wait for following digits */
static int gendigittimeout = 8000;

/* How long to wait for an extra digit, if there is an ambiguous match */
static int matchdigittimeout = 3000;

/*!
 * To apease the stupid compiler option on ast_sched_del()
 * since we don't care about the return value.
 */
static int not_used;

#define SUBSTATE_UNSET 0
#define SUBSTATE_OFFHOOK 1
#define SUBSTATE_ONHOOK 2
#define SUBSTATE_RINGOUT 3
#define SUBSTATE_RINGIN 4
#define SUBSTATE_CONNECTED 5
#define SUBSTATE_BUSY 6
#define SUBSTATE_CONGESTION 7
#define SUBSTATE_HOLD 8
#define SUBSTATE_CALLWAIT 9
#define SUBSTATE_PROGRESS 12
#define SUBSTATE_DIALING 101

#define DIALTYPE_NORMAL      1<<0
#define DIALTYPE_CFWD        1<<1
#define DIALTYPE_XFER        1<<2

struct skinny_subchannel {
	struct ast_channel *owner;
	struct ast_rtp_instance *rtp;
	struct ast_rtp_instance *vrtp;
	unsigned int callid;
	char exten[AST_MAX_EXTENSION];
	/* time_t lastouttime; */ /* Unused */
	int progress;
	int ringing;
	/* int lastout; */ /* Unused */
	int cxmode;
	int nat;
	int calldirection;
	int blindxfer;
	int xferor;
	int substate;
	int aa_sched;
	int aa_beep;
	int aa_mute;
	int dialer_sched;
	int cfwd_sched;
	int dialType;
	int getforward;
	char *origtonum;
	char *origtoname;

	AST_LIST_ENTRY(skinny_subchannel) list;
	struct skinny_subchannel *related;
	struct skinny_line *line;
	struct skinny_subline *subline;
};

#define SKINNY_LINE_OPTIONS				\
	char name[80];					\
	char label[24];					\
	char accountcode[AST_MAX_ACCOUNT_CODE];		\
	char exten[AST_MAX_EXTENSION];			\
	char context[AST_MAX_CONTEXT];			\
	char language[MAX_LANGUAGE];			\
	char cid_num[AST_MAX_EXTENSION];		\
	char cid_name[AST_MAX_EXTENSION];		\
	char lastcallerid[AST_MAX_EXTENSION];		\
	int cfwdtype;					\
	char call_forward_all[AST_MAX_EXTENSION];	\
	char call_forward_busy[AST_MAX_EXTENSION];	\
	char call_forward_noanswer[AST_MAX_EXTENSION];	\
	char mailbox[AST_MAX_MAILBOX_UNIQUEID];		\
	char vmexten[AST_MAX_EXTENSION];		\
	char regexten[AST_MAX_EXTENSION];		\
	char regcontext[AST_MAX_CONTEXT];		\
	char parkinglot[AST_MAX_CONTEXT];		\
	char mohinterpret[MAX_MUSICCLASS];		\
	char mohsuggest[MAX_MUSICCLASS];		\
	char lastnumberdialed[AST_MAX_EXTENSION];	\
	char dialoutexten[AST_MAX_EXTENSION];		\
	char dialoutcontext[AST_MAX_CONTEXT];		\
	ast_group_t callgroup;				\
	ast_group_t pickupgroup;			\
	struct ast_namedgroups *named_callgroups;	\
	struct ast_namedgroups *named_pickupgroups;	\
	int callwaiting;				\
	int transfer;					\
	int threewaycalling;				\
	int mwiblink;					\
	int cancallforward;				\
	int callfwdtimeout;				\
	int dnd;					\
	int hidecallerid;				\
	int amaflags;					\
	int instance;					\
	int group;					\
	int nonCodecCapability;				\
	int immediate;					\
	int nat;					\
	int directmedia;				\
	int prune;

struct skinny_line {
	SKINNY_LINE_OPTIONS
	ast_mutex_t lock;
	struct skinny_container *container;
	struct stasis_subscription *mwi_event_sub; /* Event based MWI */
	struct skinny_subchannel *activesub;
	AST_LIST_HEAD(, skinny_subchannel) sub;
	AST_LIST_HEAD(, skinny_subline) sublines;
	AST_LIST_ENTRY(skinny_line) list;
	AST_LIST_ENTRY(skinny_line) all;
	struct skinny_device *device;
	struct ast_format_cap *cap;
	struct ast_format_cap *confcap;
	struct ast_variable *chanvars; /*!< Channel variables to set for inbound call */
	int newmsgs;
};

static struct skinny_line_options{
	SKINNY_LINE_OPTIONS
} default_line_struct = {
	.callwaiting = 1,
	.transfer = 1,
	.mwiblink = 0,
	.dnd = 0,
	.hidecallerid = 0,
	.amaflags = 0,
	.instance = 0,
	.directmedia = 0,
	.nat = 0,
	.callfwdtimeout = 20000,
	.prune = 0,
};
static struct skinny_line_options *default_line = &default_line_struct;

static AST_LIST_HEAD_STATIC(lines, skinny_line);

struct skinny_subline {
	struct skinny_container *container;
	struct skinny_line *line;
	struct skinny_subchannel *sub;
	AST_LIST_ENTRY(skinny_subline) list;
	char name[80];
	char context[AST_MAX_CONTEXT];
	char exten[AST_MAX_EXTENSION];
	char stname[AST_MAX_EXTENSION];
	char lnname[AST_MAX_EXTENSION];
	char ourName[40];
	char ourNum[24];
	char theirName[40];
	char theirNum[24];
	int calldirection;
	int substate;
	int extenstate;
	unsigned int callid;
};

struct skinny_speeddial {
	ast_mutex_t lock;
	struct skinny_container *container;
	char label[42];
	char context[AST_MAX_CONTEXT];
	char exten[AST_MAX_EXTENSION];
	int instance;
	int stateid;
	int laststate;
	int isHint;

	AST_LIST_ENTRY(skinny_speeddial) list;
	struct skinny_device *parent;
};

struct skinny_serviceurl {
	int instance;
	char url[MAX_SERVICEURL];
	char displayName[40];
	AST_LIST_ENTRY(skinny_serviceurl) list;
	struct skinny_device *device;
};

#define SKINNY_DEVICECONTAINER 1
#define SKINNY_LINECONTAINER 2
#define SKINNY_SUBLINECONTAINER 3
#define SKINNY_SDCONTAINER 4

struct skinny_container {
	int type;
	void *data;
};

struct skinny_addon {
	ast_mutex_t lock;
	char type[10];
	AST_LIST_ENTRY(skinny_addon) list;
	struct skinny_device *parent;
};

#define SKINNY_DEVICE_OPTIONS					\
	char name[80];						\
	char id[16];						\
	char version_id[16];					\
	char vmexten[AST_MAX_EXTENSION];			\
	int type;						\
	int protocolversion;				\
	int hookstate;					\
	int lastlineinstance;					\
	int lastcallreference;					\
	int earlyrtp;						\
	int transfer;						\
	int callwaiting;					\
	int mwiblink;						\
	int dnd;						\
	int prune;

struct skinny_device {
	SKINNY_DEVICE_OPTIONS
	struct type *first;
	struct type *last;
	ast_mutex_t lock;
	struct sockaddr_in addr;
	struct in_addr ourip;
	struct ast_ha *ha;
	struct skinnysession *session;
	struct skinny_line *activeline;
	struct ast_format_cap *cap;
	struct ast_format_cap *confcap;
	struct ast_endpoint *endpoint;
	AST_LIST_HEAD(, skinny_line) lines;
	AST_LIST_HEAD(, skinny_speeddial) speeddials;
	AST_LIST_HEAD(, skinny_serviceurl) serviceurls;
	AST_LIST_HEAD(, skinny_addon) addons;
	AST_LIST_ENTRY(skinny_device) list;
};

static struct skinny_device_options {
	SKINNY_DEVICE_OPTIONS
} default_device_struct = {
	.transfer = 1,
	.earlyrtp = 1,
	.callwaiting = 1,
	.mwiblink = 0,
	.dnd = 0,
	.prune = 0,
	.hookstate = SKINNY_ONHOOK,
};
static struct skinny_device_options *default_device = &default_device_struct;

static AST_LIST_HEAD_STATIC(devices, skinny_device);

struct skinnysession {
	pthread_t t;
	ast_mutex_t lock;
	struct timeval start;
	struct sockaddr_in sin;
	int fd;
	char outbuf[SKINNY_MAX_PACKET];
	struct skinny_device *device;
	AST_LIST_ENTRY(skinnysession) list;
	int lockstate; /* Only for use in the skinny_session thread */
	int auth_timeout_sched;
	int keepalive_timeout_sched;
	struct timeval last_keepalive;
	int keepalive_count;
};

static struct ast_channel *skinny_request(const char *type, struct ast_format_cap *cap, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *dest, int *cause);
static AST_LIST_HEAD_STATIC(sessions, skinnysession);

static int skinny_devicestate(const char *data);
static int skinny_call(struct ast_channel *ast, const char *dest, int timeout);
static int skinny_hangup(struct ast_channel *ast);
static int skinny_answer(struct ast_channel *ast);
static struct ast_frame *skinny_read(struct ast_channel *ast);
static int skinny_write(struct ast_channel *ast, struct ast_frame *frame);
static int skinny_indicate(struct ast_channel *ast, int ind, const void *data, size_t datalen);
static int skinny_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
static int skinny_senddigit_begin(struct ast_channel *ast, char digit);
static int skinny_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
static void mwi_event_cb(void *userdata, struct stasis_subscription *sub, struct stasis_message *msg);
static int skinny_dialer_cb(const void *data);
static int skinny_reload(void);

static void skinny_set_owner(struct skinny_subchannel* sub, struct ast_channel* chan);
static void setsubstate(struct skinny_subchannel *sub, int state);
static void dumpsub(struct skinny_subchannel *sub, int forcehangup);
static void activatesub(struct skinny_subchannel *sub, int state);
static void dialandactivatesub(struct skinny_subchannel *sub, char exten[AST_MAX_EXTENSION]);
static int skinny_nokeepalive_cb(const void *data);

static void transmit_definetimedate(struct skinny_device *d);

static struct ast_channel_tech skinny_tech = {
	.type = "Skinny",
	.description = tdesc,
	.properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
	.requester = skinny_request,
	.devicestate = skinny_devicestate,
	.call = skinny_call,
	.hangup = skinny_hangup,
	.answer = skinny_answer,
	.read = skinny_read,
	.write = skinny_write,
	.indicate = skinny_indicate,
	.fixup = skinny_fixup,
	.send_digit_begin = skinny_senddigit_begin,
	.send_digit_end = skinny_senddigit_end,
};

static int skinny_extensionstate_cb(char *context, char *id, struct ast_state_cb_info *info, void *data);

static struct skinny_line *skinny_line_alloc(void)
{
	struct skinny_line *l;
	if (!(l = ast_calloc(1, sizeof(*l)))) {
		return NULL;
	}

	l->cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
	l->confcap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
	if (!l->cap || !l->confcap) {
		ao2_cleanup(l->cap);
		ao2_cleanup(l->confcap);
		ast_free(l);
		return NULL;
	}
	return l;
}
static struct skinny_line *skinny_line_destroy(struct skinny_line *l)
{
	ao2_ref(l->cap, -1);
	ao2_ref(l->confcap, -1);
	l->named_callgroups = ast_unref_namedgroups(l->named_callgroups);
	l->named_pickupgroups = ast_unref_namedgroups(l->named_pickupgroups);
	ast_free(l->container);
	ast_free(l);
	return NULL;
}
static struct skinny_device *skinny_device_alloc(const char *dname)
{
	struct skinny_device *d;
	if (!(d = ast_calloc(1, sizeof(*d)))) {
		return NULL;
	}

	d->cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
	d->confcap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
	d->endpoint = ast_endpoint_create("Skinny", dname);
	if (!d->cap || !d->confcap || !d->endpoint) {
		ao2_cleanup(d->cap);
		ao2_cleanup(d->confcap);
		ast_free(d);
		return NULL;
	}

	ast_copy_string(d->name, dname, sizeof(d->name));

	return d;
}
static struct skinny_device *skinny_device_destroy(struct skinny_device *d)
{
	ao2_ref(d->cap, -1);
	ao2_ref(d->confcap, -1);
	ast_endpoint_shutdown(d->endpoint);
	ast_free(d);
	return NULL;
}

static void *get_button_template(struct skinnysession *s, struct button_definition_template *btn)
{
	struct skinny_device *d = s->device;
	struct skinny_addon *a;
	int i;

	switch (d->type) {
		case SKINNY_DEVICE_30SPPLUS:
		case SKINNY_DEVICE_30VIP:
			/* 13 rows, 2 columns */
			for (i = 0; i < 4; i++)
				(btn++)->buttonDefinition = BT_CUST_LINE;
			(btn++)->buttonDefinition = BT_REDIAL;
			(btn++)->buttonDefinition = BT_VOICEMAIL;
			(btn++)->buttonDefinition = BT_CALLPARK;
			(btn++)->buttonDefinition = BT_FORWARDALL;
			(btn++)->buttonDefinition = BT_CONFERENCE;
			for (i = 0; i < 4; i++)
				(btn++)->buttonDefinition = BT_NONE;
			for (i = 0; i < 13; i++)
				(btn++)->buttonDefinition = BT_SPEEDDIAL;

			break;
		case SKINNY_DEVICE_12SPPLUS:
		case SKINNY_DEVICE_12SP:
		case SKINNY_DEVICE_12:
			/* 6 rows, 2 columns */
			for (i = 0; i < 2; i++)
				(btn++)->buttonDefinition = BT_CUST_LINE;
			for (i = 0; i < 4; i++)
				(btn++)->buttonDefinition = BT_SPEEDDIAL;
			(btn++)->buttonDefinition = BT_HOLD;
			(btn++)->buttonDefinition = BT_REDIAL;
			(btn++)->buttonDefinition = BT_TRANSFER;
			(btn++)->buttonDefinition = BT_FORWARDALL;
			(btn++)->buttonDefinition = BT_CALLPARK;
			(btn++)->buttonDefinition = BT_VOICEMAIL;
			break;
		case SKINNY_DEVICE_7910:
			(btn++)->buttonDefinition = BT_LINE;
			(btn++)->buttonDefinition = BT_HOLD;
			(btn++)->buttonDefinition = BT_TRANSFER;
			(btn++)->buttonDefinition = BT_DISPLAY;
			(btn++)->buttonDefinition = BT_VOICEMAIL;
			(btn++)->buttonDefinition = BT_CONFERENCE;
			(btn++)->buttonDefinition = BT_FORWARDALL;
			for (i = 0; i < 2; i++)
				(btn++)->buttonDefinition = BT_SPEEDDIAL;
			(btn++)->buttonDefinition = BT_REDIAL;
			break;
		case SKINNY_DEVICE_7960:
		case SKINNY_DEVICE_7961:
		case SKINNY_DEVICE_7961GE:
		case SKINNY_DEVICE_7962:
		case SKINNY_DEVICE_7965:
			for (i = 0; i < 6; i++)
				(btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
			break;
		case SKINNY_DEVICE_7940:
		case SKINNY_DEVICE_7941:
		case SKINNY_DEVICE_7941GE:
		case SKINNY_DEVICE_7942:
		case SKINNY_DEVICE_7945:
			for (i = 0; i < 2; i++)
				(btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
			break;
		case SKINNY_DEVICE_7935:
		case SKINNY_DEVICE_7936:
			for (i = 0; i < 2; i++)
				(btn++)->buttonDefinition = BT_LINE;
			break;
		case SKINNY_DEVICE_ATA186:
			(btn++)->buttonDefinition = BT_LINE;
			break;
		case SKINNY_DEVICE_7970:
		case SKINNY_DEVICE_7971:
		case SKINNY_DEVICE_7975:
		case SKINNY_DEVICE_CIPC:
			for (i = 0; i < 8; i++)
				(btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
			break;
		case SKINNY_DEVICE_7985:
			/* XXX I have no idea what the buttons look like on these. */
			ast_log(LOG_WARNING, "Unsupported device type '%d (7985)' found.\n", d->type);
			break;
		case SKINNY_DEVICE_7912:
		case SKINNY_DEVICE_7911:
		case SKINNY_DEVICE_7905:
			(btn++)->buttonDefinition = BT_LINE;
			(btn++)->buttonDefinition = BT_HOLD;
			break;
		case SKINNY_DEVICE_7920:
			/* XXX I don't know if this is right. */
			for (i = 0; i < 4; i++)
				(btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
			break;
		case SKINNY_DEVICE_7921:
			for (i = 0; i < 6; i++)
				(btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
			break;
		case SKINNY_DEVICE_7902:
			ast_log(LOG_WARNING, "Unsupported device type '%d (7902)' found.\n", d->type);
			break;
		case SKINNY_DEVICE_7906:
			ast_log(LOG_WARNING, "Unsupported device type '%d (7906)' found.\n", d->type);
			break;
		case SKINNY_DEVICE_7931:
			ast_log(LOG_WARNING, "Unsupported device type '%d (7931)' found.\n", d->type);
			break;
		case SKINNY_DEVICE_7937:
			ast_log(LOG_WARNING, "Unsupported device type '%d (7937)' found.\n", d->type);
			break;
		case SKINNY_DEVICE_7914:
			ast_log(LOG_WARNING, "Unsupported device type '%d (7914)' found.  Expansion module registered by itself?\n", d->type);
			break;
		case SKINNY_DEVICE_SCCPGATEWAY_AN:
		case SKINNY_DEVICE_SCCPGATEWAY_BRI:
			ast_log(LOG_WARNING, "Unsupported device type '%d (SCCP gateway)' found.\n", d->type);
			break;
		default:
			ast_log(LOG_WARNING, "Unknown device type '%d' found.\n", d->type);
			break;
	}

	AST_LIST_LOCK(&d->addons);
	AST_LIST_TRAVERSE(&d->addons, a, list) {
		if (!strcasecmp(a->type, "7914")) {
			for (i = 0; i < 14; i++)
				(btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
		} else {
			ast_log(LOG_WARNING, "Unknown addon type '%s' found.  Skipping.\n", a->type);
		}
	}
	AST_LIST_UNLOCK(&d->addons);

	return btn;
}

static struct skinny_req *req_alloc(size_t size, int response_message)
{
	struct skinny_req *req;

	if (!(req = ast_calloc(1, skinny_header_size + size + 4)))
		return NULL;

	req->len = htolel(size+4);
	req->e = htolel(response_message);

	return req;
}

static struct skinny_line *find_line_by_instance(struct skinny_device *d, int instance)
{
	struct skinny_line *l;

	/*Dialing from on hook or on a 7920 uses instance 0 in requests
	  but we need to start looking at instance 1 */

	if (!instance)
		instance = 1;

	AST_LIST_TRAVERSE(&d->lines, l, list){
		if (l->instance == instance)
			break;
	}

	if (!l) {
		ast_log(LOG_WARNING, "Could not find line with instance '%d' on device '%s'\n", instance, d->name);
	}
	return l;
}

static struct skinny_line *find_line_by_name(const char *dest)
{
	struct skinny_line *l;
	struct skinny_line *tmpl = NULL;
	struct skinny_device *d;
	char line[256];
	char *at;
	char *device;
	int checkdevice = 0;

	ast_copy_string(line, dest, sizeof(line));
	at = strchr(line, '@');
	if (at)
		*at++ = '\0';
	device = at;

	if (!ast_strlen_zero(device))
		checkdevice = 1;

	AST_LIST_LOCK(&devices);
	AST_LIST_TRAVERSE(&devices, d, list){
		if (checkdevice && tmpl)
			break;
		else if (!checkdevice) {
			/* This is a match, since we're checking for line on every device. */
		} else if (!strcasecmp(d->name, device)) {
		} else
			continue;

		/* Found the device (or we don't care which device) */
		AST_LIST_TRAVERSE(&d->lines, l, list){
			/* Search for the right line */
			if (!strcasecmp(l->name, line)) {
				if (tmpl) {
					ast_log(LOG_WARNING, "Ambiguous line name: %s\n", line);
					AST_LIST_UNLOCK(&devices);
					return NULL;
				} else
					tmpl = l;
			}
		}
	}
	AST_LIST_UNLOCK(&devices);
	return tmpl;
}

static struct skinny_subline *find_subline_by_name(const char *dest)
{
	struct skinny_line *l;
	struct skinny_subline *subline;
	struct skinny_subline *tmpsubline = NULL;
	struct skinny_device *d;

	AST_LIST_LOCK(&devices);
	AST_LIST_TRAVERSE(&devices, d, list){
		AST_LIST_TRAVERSE(&d->lines, l, list){
			AST_LIST_TRAVERSE(&l->sublines, subline, list){
				if (!strcasecmp(subline->name, dest)) {
					if (tmpsubline) {
						ast_verb(2, "Ambiguous subline name: %s\n", dest);
						AST_LIST_UNLOCK(&devices);
						return NULL;
					} else
						tmpsubline = subline;
				}
			}
		}
	}
	AST_LIST_UNLOCK(&devices);
	return tmpsubline;
}

static struct skinny_subline *find_subline_by_callid(struct skinny_device *d, int callid)
{
	struct skinny_subline *subline;
	struct skinny_line *l;

	AST_LIST_TRAVERSE(&d->lines, l, list){
		AST_LIST_TRAVERSE(&l->sublines, subline, list){
			if (subline->callid == callid) {
				return subline;
			}
		}
	}
	return NULL;
}

/*!
 * 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;
}

static void skinny_locksub(struct skinny_subchannel *sub)
{
	if (sub && sub->owner) {
		ast_channel_lock(sub->owner);
	}
}

static void skinny_unlocksub(struct skinny_subchannel *sub)
{
	if (sub && sub->owner) {
		ast_channel_unlock(sub->owner);
	}
}

static int skinny_sched_del(int sched_id, struct skinny_subchannel *sub)
{
	SKINNY_DEBUG(DEBUG_SUB, 3, "Sub %u - Deleting SCHED %d\n",
		sub->callid, sched_id);
	return ast_sched_del(sched, sched_id);
}

static int skinny_sched_add(int when, ast_sched_cb callback, struct skinny_subchannel *sub)
{
	int ret;
	ret = ast_sched_add(sched, when, callback, sub);
	SKINNY_DEBUG(DEBUG_SUB, 3, "Sub %u - Added SCHED %d\n",
		sub->callid, ret);
	return ret;
}

/* It's quicker/easier to find the subchannel when we know the instance number too */
static struct skinny_subchannel *find_subchannel_by_instance_reference(struct skinny_device *d, int instance, int reference)
{
	struct skinny_line *l = find_line_by_instance(d, instance);
	struct skinny_subchannel *sub;

	if (!l) {
		return NULL;
	}

	/* 7920 phones set call reference to 0, so use the first
	   sub-channel on the list.
           This MIGHT need more love to be right */
	if (!reference)
		sub = AST_LIST_FIRST(&l->sub);
	else {
		AST_LIST_TRAVERSE(&l->sub, sub, list) {
			if (sub->callid == reference)
				break;
		}
	}
	if (!sub) {
		ast_log(LOG_WARNING, "Could not find subchannel with reference '%d' on '%s'\n", reference, d->name);
	}
	return sub;
}

/* Find the subchannel when we only have the callid - this shouldn't happen often */
static struct skinny_subchannel *find_subchannel_by_reference(struct skinny_device *d, int reference)
{
	struct skinny_line *l;
	struct skinny_subchannel *sub = NULL;

	AST_LIST_TRAVERSE(&d->lines, l, list){
		AST_LIST_TRAVERSE(&l->sub, sub, list){
			if (sub->callid == reference)
				break;
		}
		if (sub)
			break;
	}

	if (!l) {
		ast_log(LOG_WARNING, "Could not find any lines that contained a subchannel with reference '%d' on device '%s'\n", reference, d->name);
	} else {
		if (!sub) {
			ast_log(LOG_WARNING, "Could not find subchannel with reference '%d' on '%s@%s'\n", reference, l->name, d->name);
		}
	}
	return sub;
}

static struct skinny_speeddial *find_speeddial_by_instance(struct skinny_device *d, int instance, int isHint)
{
	struct skinny_speeddial *sd;

	AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
		if (sd->isHint == isHint && sd->instance == instance)
			break;
	}

	if (!sd) {
		ast_log(LOG_WARNING, "Could not find speeddial with instance '%d' on device '%s'\n", instance, d->name);
	}
	return sd;
}

static struct ast_format *codec_skinny2ast(enum skinny_codecs skinnycodec)
{
	switch (skinnycodec) {
	case SKINNY_CODEC_ALAW:
		return ast_format_alaw;
	case SKINNY_CODEC_ULAW:
		return ast_format_ulaw;
	case SKINNY_CODEC_G722:
		return ast_format_g722;
	case SKINNY_CODEC_G723_1:
		return ast_format_g723;
	case SKINNY_CODEC_G729A:
		return ast_format_g729;
	case SKINNY_CODEC_G726_32:
		return ast_format_g726; /* XXX Is this right? */
	case SKINNY_CODEC_H261:
		return ast_format_h261;
	case SKINNY_CODEC_H263:
		return ast_format_h263;
	default:
		return ast_format_none;
	}
}

static int codec_ast2skinny(const struct ast_format *astcodec)
{
	if (ast_format_cmp(astcodec, ast_format_alaw) == AST_FORMAT_CMP_EQUAL) {
		return SKINNY_CODEC_ALAW;
	} else if (ast_format_cmp(astcodec, ast_format_ulaw) == AST_FORMAT_CMP_EQUAL) {
		return SKINNY_CODEC_ULAW;
	} else if (ast_format_cmp(astcodec, ast_format_g722) == AST_FORMAT_CMP_EQUAL) {
		return SKINNY_CODEC_G722;
	} else if (ast_format_cmp(astcodec, ast_format_g723) == AST_FORMAT_CMP_EQUAL) {
		return SKINNY_CODEC_G723_1;
	} else if (ast_format_cmp(astcodec, ast_format_g729) == AST_FORMAT_CMP_EQUAL) {
		return SKINNY_CODEC_G729A;
	} else if (ast_format_cmp(astcodec, ast_format_g726) == AST_FORMAT_CMP_EQUAL) {
		return SKINNY_CODEC_G726_32;
	} else if (ast_format_cmp(astcodec, ast_format_h261) == AST_FORMAT_CMP_EQUAL) {
		return SKINNY_CODEC_H261;
	} else if (ast_format_cmp(astcodec, ast_format_h263) == AST_FORMAT_CMP_EQUAL) {
		return SKINNY_CODEC_H263;
	} else {
		return 0;
	}
}

static int set_callforwards(struct skinny_line *l, const char *cfwd, int cfwdtype)
{
	if (!l)
		return 0;

	if (!ast_strlen_zero(cfwd)) {
		if (cfwdtype & SKINNY_CFWD_ALL) {
			l->cfwdtype |= SKINNY_CFWD_ALL;
			ast_copy_string(l->call_forward_all, cfwd, sizeof(l->call_forward_all));
		}
		if (cfwdtype & SKINNY_CFWD_BUSY) {
			l->cfwdtype |= SKINNY_CFWD_BUSY;
			ast_copy_string(l->call_forward_busy, cfwd, sizeof(l->call_forward_busy));
		}
		if (cfwdtype & SKINNY_CFWD_NOANSWER) {
			l->cfwdtype |= SKINNY_CFWD_NOANSWER;
			ast_copy_string(l->call_forward_noanswer, cfwd, sizeof(l->call_forward_noanswer));
		}
	} else {
		if (cfwdtype & SKINNY_CFWD_ALL) {
			l->cfwdtype &= ~SKINNY_CFWD_ALL;
			memset(l->call_forward_all, 0, sizeof(l->call_forward_all));
		}
		if (cfwdtype & SKINNY_CFWD_BUSY) {
			l->cfwdtype &= ~SKINNY_CFWD_BUSY;
			memset(l->call_forward_busy, 0, sizeof(l->call_forward_busy));
		}
		if (cfwdtype & SKINNY_CFWD_NOANSWER) {
			l->cfwdtype &= ~SKINNY_CFWD_NOANSWER;
			memset(l->call_forward_noanswer, 0, sizeof(l->call_forward_noanswer));
		}
	}
	return l->cfwdtype;
}

static void cleanup_stale_contexts(char *new, char *old)
{
	char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];

	while ((oldcontext = strsep(&old, "&"))) {
		stalecontext = NULL;
		ast_copy_string(newlist, new, sizeof(newlist));
		stringp = newlist;
		while ((newcontext = strsep(&stringp, "&"))) {
			if (strcmp(newcontext, oldcontext) == 0) {
				/* This is not the context you're looking for */
				stalecontext = NULL;
				break;
			} else if (strcmp(newcontext, oldcontext)) {
				stalecontext = oldcontext;
			}

		}
		ast_context_destroy_by_name(stalecontext, "Skinny");
	}
}

static void register_exten(struct skinny_line *l)
{
	char multi[256];
	char *stringp, *ext, *context;

	if (ast_strlen_zero(regcontext))
		return;

	ast_copy_string(multi, S_OR(l->regexten, l->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 skinny.conf!\n", context);
				continue;
			}
		} else {
			context = regcontext;
		}
		ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
			 ast_strdup(l->name), ast_free_ptr, "Skinny");
	}
}

static void unregister_exten(struct skinny_line *l)
{
	char multi[256];
	char *stringp, *ext, *context;

	if (ast_strlen_zero(regcontext))
		return;

	ast_copy_string(multi, S_OR(l->regexten, l->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 skinny.conf!\n", context);
				continue;
			}
		} else {
			context = regcontext;
		}
		ast_context_remove_extension(context, ext, 1, NULL);
	}
}

static int skinny_register(struct skinny_req *req, struct skinnysession *s)
{
	struct skinny_device *d;
	struct skinny_line *l;
	struct skinny_subline *subline;
	struct skinny_speeddial *sd;
	struct sockaddr_in sin;
	socklen_t slen;
	int instance;
	int res = -1;

	if (-1 < s->auth_timeout_sched) {
		not_used = ast_sched_del(sched, s->auth_timeout_sched);
		s->auth_timeout_sched = -1;
	}

	AST_LIST_LOCK(&devices);
	AST_LIST_TRAVERSE(&devices, d, list){
		struct ast_sockaddr addr;
		ast_sockaddr_from_sin(&addr, &s->sin);
		if (!strcasecmp(req->data.reg.name, d->id)
				&& ast_apply_ha(d->ha, &addr)) {
			RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);

			if (d->session) {
				ast_log(LOG_WARNING, "Device already registered.\n");
				transmit_definetimedate(d);
				res = 0;
				break;
			}
			s->device = d;
			d->type = letohl(req->data.reg.type);
			d->protocolversion = letohl(req->data.reg.protocolVersion);
			if (ast_strlen_zero(d->version_id)) {
				ast_copy_string(d->version_id, version_id, sizeof(d->version_id));
			}
			d->session = s;

			slen = sizeof(sin);
			if (getsockname(s->fd, (struct sockaddr *)&sin, &slen)) {
				ast_log(LOG_WARNING, "Cannot get socket name\n");
				sin.sin_addr = __ourip;
			}
			d->ourip = sin.sin_addr;

			AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
				sd->stateid = ast_extension_state_add(sd->context, sd->exten, skinny_extensionstate_cb, sd->container);
			}
			instance = 0;
			AST_LIST_TRAVERSE(&d->lines, l, list) {
				instance++;
			}
			AST_LIST_TRAVERSE(&d->lines, l, list) {
				ast_format_cap_get_compatible(l->confcap, d->cap, l->cap);
				/* l->capability = d->capability; */
				l->instance = instance;
				l->newmsgs = ast_app_has_voicemail(l->mailbox, NULL);
				set_callforwards(l, NULL, SKINNY_CFWD_ALL|SKINNY_CFWD_BUSY|SKINNY_CFWD_NOANSWER);
				register_exten(l);
				/* initialize MWI on line and device */
				mwi_event_cb(l, NULL, NULL);
				AST_LIST_TRAVERSE(&l->sublines, subline, list) {
					ast_extension_state_add(subline->context, subline->exten, skinny_extensionstate_cb, subline->container);
				}
				ast_devstate_changed(AST_DEVICE_NOT_INUSE, AST_DEVSTATE_CACHABLE, "Skinny/%s", l->name);
				--instance;
			}
			ast_endpoint_set_state(d->endpoint, AST_ENDPOINT_ONLINE);
			blob = ast_json_pack("{s: s}", "peer_status", "Registered");
			ast_endpoint_blob_publish(d->endpoint, ast_endpoint_state_type(), blob);
			res = 1;
			break;
		}
	}
	AST_LIST_UNLOCK(&devices);
	return res;
}

static void end_session(struct skinnysession *s)
{
	pthread_cancel(s->t);
}

#ifdef AST_DEVMODE
static char *callstate2str(int ind)
{
	char *tmp;

	switch (ind) {
	case SKINNY_OFFHOOK:
		return "SKINNY_OFFHOOK";
	case SKINNY_ONHOOK:
		return "SKINNY_ONHOOK";
	case SKINNY_RINGOUT:
		return "SKINNY_RINGOUT";
	case SKINNY_RINGIN:
		return "SKINNY_RINGIN";
	case SKINNY_CONNECTED:
		return "SKINNY_CONNECTED";
	case SKINNY_BUSY:
		return "SKINNY_BUSY";
	case SKINNY_CONGESTION:
		return "SKINNY_CONGESTION";
	case SKINNY_PROGRESS:
		return "SKINNY_PROGRESS";
	case SKINNY_HOLD:
		return "SKINNY_HOLD";
	case SKINNY_CALLWAIT:
		return "SKINNY_CALLWAIT";
	default:
		if (!(tmp = ast_threadstorage_get(&callstate2str_threadbuf, CALLSTATE2STR_BUFSIZE)))
                        return "Unknown";
		snprintf(tmp, CALLSTATE2STR_BUFSIZE, "UNKNOWN-%d", ind);
		return tmp;
	}
}

#endif

static int transmit_response_bysession(struct skinnysession *s, struct skinny_req *req)
{
	int res = 0;
	unsigned long len;

	if (!s) {
		ast_log(LOG_WARNING, "Asked to transmit to a non-existent session!\n");
		return -1;
	}

	ast_mutex_lock(&s->lock);

	/* Don't optimize out assigning letohl() to len. It is necessary to guarantee that the comparison will always catch invalid values.
	 * letohl() may or may not return a signed value depending upon which definition is used. */
	len = letohl(req->len);
	if (SKINNY_MAX_PACKET < len) {
		ast_log(LOG_WARNING, "transmit_response: the length of the request (%u) is out of bounds (%d)\n", letohl(req->len), SKINNY_MAX_PACKET);
		ast_mutex_unlock(&s->lock);
		return -1;
	}

	memset(s->outbuf, 0, sizeof(s->outbuf));
	memcpy(s->outbuf, req, skinny_header_size);
	memcpy(s->outbuf+skinny_header_size, &req->data, letohl(req->len));

	res = write(s->fd, s->outbuf, letohl(req->len)+8);

	if (res != letohl(req->len)+8) {
		ast_log(LOG_WARNING, "Transmit: write only sent %d out of %u bytes: %s\n", res, letohl(req->len)+8, strerror(errno));
		if (res == -1) {
			ast_log(LOG_WARNING, "Transmit: Skinny Client was lost, unregistering\n");
			end_session(s);
		}

	}

	ast_free(req);
	ast_mutex_unlock(&s->lock);
	return 1;
}

static void transmit_response(struct skinny_device *d, struct skinny_req *req)
{
	transmit_response_bysession(d->session, req);
}

static void transmit_registerrej(struct skinnysession *s)
{
	struct skinny_req *req;
	char name[16];

	if (!(req = req_alloc(sizeof(struct register_rej_message), REGISTER_REJ_MESSAGE)))
		return;

	memcpy(&name, req->data.reg.name, sizeof(name));
	snprintf(req->data.regrej.errMsg, sizeof(req->data.regrej.errMsg), "No Authority: %s", name);

	SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting REGISTER_REJ_MESSAGE to UNKNOWN_DEVICE\n");
	transmit_response_bysession(s, req);
}

static void transmit_speaker_mode(struct skinny_device *d, int mode)
{
	struct skinny_req *req;

	if (!(req = req_alloc(sizeof(struct set_speaker_message), SET_SPEAKER_MESSAGE)))
		return;

	req->data.setspeaker.mode = htolel(mode);

	SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SET_SPEAKER_MESSAGE to %s, mode %d\n", d->name, mode);
	transmit_response(d, req);
}

static void transmit_microphone_mode(struct skinny_device *d, int mode)
{
	struct skinny_req *req;

	if (!(req = req_alloc(sizeof(struct set_microphone_message), SET_MICROPHONE_MESSAGE)))
		return;

	req->data.setmicrophone.mode = htolel(mode);

	SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SET_MICROPHONE_MESSAGE to %s, mode %d\n", d->name, mode);
	transmit_response(d, req);
}

//static void transmit_callinfo(struct skinny_subchannel *sub)
static void transmit_callinfo(struct skinny_device *d, int instance, int callid,
	char *fromname, char *fromnum, char *toname, char *tonum, int calldirection, char *origtonum, char *origtoname)
{
	struct skinny_req *req;

	if (!(req = req_alloc(sizeof(struct call_info_message), CALL_INFO_MESSAGE)))
		return;

	ast_copy_string(req->data.callinfo.callingPartyName, fromname, sizeof(req->data.callinfo.callingPartyName));
	ast_copy_string(req->data.callinfo.callingParty, fromnum, sizeof(req->data.callinfo.callingParty));
	ast_copy_string(req->data.callinfo.calledPartyName, toname, sizeof(req->data.callinfo.calledPartyName));
	ast_copy_string(req->data.callinfo.calledParty, tonum, sizeof(req->data.callinfo.calledParty));
	if (origtoname) {
		ast_copy_string(req->data.callinfo.originalCalledPartyName, origtoname, sizeof(req->data.callinfo.originalCalledPartyName));
	}
	if (origtonum) {
		ast_copy_string(req->data.callinfo.originalCalledParty, origtonum, sizeof(req->data.callinfo.originalCalledParty));
	}

	req->data.callinfo.instance = htolel(instance);
	req->data.callinfo.reference = htolel(callid);
	req->data.callinfo.type = htolel(calldirection);

	SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting CALL_INFO_MESSAGE to %s, to %s(%s) from %s(%s), origto %s(%s) (dir=%d) on %s(%d)\n",
		d->name, toname, tonum, fromname, fromnum, origtoname, origtonum, calldirection, d->name, instance);
	transmit_response(d, req);
}

static void transmit_callinfo_variable(struct skinny_device *d, int instance, int callreference,
	char *fromname, char *fromnum, char *toname, char *tonum, int calldirection, char *origtonum, char *origtoname)
{
	struct skinny_req *req;
	char *strptr;
	char *thestrings[13];
	int i;
	int callinfostrleft = MAXCALLINFOSTR;

	if (!(req = req_alloc(sizeof(struct call_info_message_variable), CALL_INFO_MESSAGE_VARIABLE)))
		return;

	req->data.callinfomessagevariable.instance = htolel(instance);
	req->data.callinfomessagevariable.callreference = htolel(callreference);
	req->data.callinfomessagevariable.calldirection = htolel(calldirection);

	req->data.callinfomessagevariable.unknown1 = htolel(0x00);
	req->data.callinfomessagevariable.unknown2 = htolel(0x00);
	req->data.callinfomessagevariable.unknown3 = htolel(0x00);
	req->data.callinfomessagevariable.unknown4 = htolel(0x00);
	req->data.callinfomessagevariable.unknown5 = htolel(0x00);

	thestrings[0] = fromnum;
	thestrings[1] = "";                     /* Appears to be origfrom */
	if (calldirection == SKINNY_OUTGOING) {
		thestrings[2] = tonum;
		thestrings[3] = origtonum;
	} else {
		thestrings[2] = "";
		thestrings[3] = "";
	}
	thestrings[4] = "";
	thestrings[5] = "";
	thestrings[6] = "";
	thestrings[7] = "";

	thestrings[8] = "";
	thestrings[9] = fromname;
	thestrings[10] = toname;
	thestrings[11] = origtoname;
	thestrings[12] = "";

	strptr = req->data.callinfomessagevariable.calldetails;

	for(i = 0; i < 13; i++) {
		if (thestrings[i]) {
			ast_copy_string(strptr, thestrings[i], callinfostrleft);
			strptr += strlen(thestrings[i]) + 1;
			callinfostrleft -= strlen(thestrings[i]) + 1;
		} else {
			ast_copy_string(strptr, "", callinfostrleft);
			strptr++;
			callinfostrleft--;
		}
	}

	req->len = req->len - (callinfostrleft & ~0x3);

	SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting CALL_INFO_MESSAGE_VARIABLE to %s, to %s(%s) from %s(%s), origto %s(%s) (dir=%d) on %s(%d)\n",
		d->name, toname, tonum, fromname, fromnum, origtoname, origtonum, calldirection, d->name, instance);
	transmit_response(d, req);
}

static void send_callinfo(struct skinny_subchannel *sub)
{
	struct ast_channel *ast;
	struct skinny_device *d;
	struct skinny_line *l;
	struct ast_party_id connected_id;
	char *fromname;
	char *fromnum;
	char *toname;
	char *tonum;

	if (!sub || !sub->owner || !sub->line || !sub->line->device) {
		return;
	}

	ast = sub->owner;
	l = sub->line;
	d = l->device;
	connected_id = ast_channel_connected_effective_id(ast);

	if (sub->calldirection == SKINNY_INCOMING) {
		if ((ast_party_id_presentation(&connected_id) & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED) {
			fromname = S_COR(connected_id.name.valid, connected_id.name.str, "");
			fromnum = S_COR(connected_id.number.valid, connected_id.number.str, "");
		} else {
			fromname = "";
			fromnum = "";
		}
		toname = S_COR(ast_channel_caller(ast)->id.name.valid, ast_channel_caller(ast)->id.name.str, "");
		tonum = S_COR(ast_channel_caller(ast)->id.number.valid, ast_channel_caller(ast)->id.number.str, "");
	} else if (sub->calldirection == SKINNY_OUTGOING) {
		fromname = S_COR(ast_channel_caller(ast)->id.name.valid, ast_channel_caller(ast)->id.name.str, "");
		fromnum = S_COR(ast_channel_caller(ast)->id.number.valid, ast_channel_caller(ast)->id.number.str, "");
		toname = S_COR(ast_channel_connected(ast)->id.name.valid, ast_channel_connected(ast)->id.name.str, "");
		tonum = S_COR(ast_channel_connected(ast)->id.number.valid, ast_channel_connected(ast)->id.number.str, l->lastnumberdialed);
	} else {
		ast_verb(1, "Error sending Callinfo to %s(%d) - No call direction in sub\n", d->name, l->instance);
		return;
	}

	if (d->protocolversion < 17) {
		transmit_callinfo(d, l->instance, sub->callid, fromname, fromnum, toname, tonum, sub->calldirection, sub->origtonum, sub->origtoname);
	} else {
		transmit_callinfo_variable(d, l->instance, sub->callid, fromname, fromnum, toname, tonum, sub->calldirection, sub->origtonum, sub->origtoname);
	}
}

static void push_callinfo(struct skinny_subline *subline, struct skinny_subchannel *sub)
{
	struct ast_channel *ast;
	struct skinny_device *d;
	struct skinny_line *l;
	struct ast_party_id connected_id;
	char *fromname;
	char *fromnum;
	char *toname;
	char *tonum;

	if (!sub || !sub->owner || !sub->line || !sub->line->device) {
		return;
	}

	ast = sub->owner;
	l = sub->line;
	d = l->device;
	connected_id = ast_channel_connected_effective_id(ast);

	if (sub->calldirection == SKINNY_INCOMING) {
		if((ast_party_id_presentation(&connected_id) & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED) {
			fromname = S_COR(connected_id.name.valid, connected_id.name.str, "");
			fromnum = S_COR(connected_id.number.valid, connected_id.number.str, "");
		} else {
			fromname = "";
			fromnum = "";
		}
		toname = S_COR(ast_channel_caller(ast)->id.name.valid, ast_channel_caller(ast)->id.name.str, "");
		tonum = S_COR(ast_channel_caller(ast)->id.number.valid, ast_channel_caller(ast)->id.number.str, "");
	} else if (sub->calldirection == SKINNY_OUTGOING) {
		fromname = S_COR(ast_channel_caller(ast)->id.name.valid, ast_channel_caller(ast)->id.name.str, "");
		fromnum = S_COR(ast_channel_caller(ast)->id.number.valid, ast_channel_caller(ast)->id.number.str, "");
		toname = S_COR(ast_channel_connected(ast)->id.name.valid, ast_channel_connected(ast)->id.name.str, "");
		tonum = S_COR(ast_channel_connected(ast)->id.number.valid, ast_channel_connected(ast)->id.number.str, l->lastnumberdialed);
	} else {
		ast_verb(1, "Error sending Callinfo to %s(%d) - No call direction in sub\n", d->name, l->instance);
		return;
	}

	if (d->protocolversion < 17) {
		transmit_callinfo(subline->line->device, subline->line->instance, subline->callid, fromname, fromnum, toname, tonum, sub->calldirection, sub->origtonum, sub->origtoname);
	} else {
		transmit_callinfo_variable(subline->line->device, subline->line->instance, subline->callid, fromname, fromnum, toname, tonum, sub->calldirection, sub->origtonum, sub->origtoname);
	}
}

static void transmit_connect(struct skinny_device *d, struct skinny_subchannel *sub)
{
	struct skinny_req *req;
	struct skinny_line *l = sub->line;
	struct ast_format *tmpfmt;
	unsigned int framing;

	if (!(req = req_alloc(sizeof(struct open_receive_channel_message), OPEN_RECEIVE_CHANNEL_MESSAGE)))
		return;

	tmpfmt = ast_format_cap_get_format(l->cap, 0);
	framing = ast_format_cap_get_format_framing(l->cap, tmpfmt);

	req->data.openreceivechannel.conferenceId = htolel(sub->callid);
	req->data.openreceivechannel.partyId = htolel(sub->callid);
	req->data.openreceivechannel.packets = htolel(framing);
	req->data.openreceivechannel.capability = htolel(codec_ast2skinny(tmpfmt));
	req->data.openreceivechannel.echo = htolel(0);
	req->data.openreceivechannel.bitrate = htolel(0);

	SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting OPEN_RECEIVE_CHANNEL_MESSAGE to %s, confid %u, partyid %u, ms %u, fmt %d, echo %d, brate %d\n",
		d->name, sub->callid, sub->callid, framing, codec_ast2skinny(tmpfmt), 0, 0);

	ao2_ref(tmpfmt, -1);

	transmit_response(d, req);
}

static void transmit_start_tone(struct skinny_device *d, int tone, int instance, int reference)
{
	struct skinny_req *req;
	if (!(req = req_alloc(sizeof(struct start_tone_message), START_TONE_MESSAGE)))
		return;
	req->data.starttone.tone = htolel(tone);
	req->data.starttone.instance = htolel(instance);
	req->data.starttone.reference = htolel(reference);

	SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting START_TONE_MESSAGE to %s, tone %d, inst %d, ref %d\n",
		d->name, tone, instance, reference);
	transmit_response(d, req);
}

static void transmit_stop_tone(struct skinny_device *d, int instance, int reference)
{
	struct skinny_req *req;
	if (!(req = req_alloc(sizeof(struct stop_tone_message), STOP_TONE_MESSAGE)))
		return;
	req->data.stoptone.instance = htolel(instance);
	req->data.stoptone.reference = htolel(reference);

	SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting STOP_TONE_MESSAGE to %s, inst %d, ref %d\n",
		d->name, instance, reference);
	transmit_response(d, req);
}

static int keyset_translatebitmask(int keyset, int intmask)
{
	int extmask = 0;
	int x, y;
	const struct soft_key_definitions *softkeymode = soft_key_default_definitions;

	for(x = 0; x < ARRAY_LEN(soft_key_default_definitions); x++) {
		if (softkeymode[x].mode == keyset) {
			const uint8_t *defaults = softkeymode[x].defaults;

			for (y = 0; y < softkeymode[x].count; y++) {
				if (intmask & (1 << (defaults[y]))) {
					extmask |= (1 << ((y)));
				}
			}
			break;
		}
	}

	return extmask;
}

static void transmit_selectsoftkeys(struct skinny_device *d, int instance, int callid, int softkey, int mask)
{
	struct skinny_req *req;
	int newmask;

	if (!(req = req_alloc(sizeof(struct select_soft_keys_message), SELECT_SOFT_KEYS_MESSAGE)))
		return;

	newmask = keyset_translatebitmask(softkey, mask);
	req->data.selectsoftkey.instance = htolel(instance);
	req->data.selectsoftkey.reference = htolel(callid);
	req->data.selectsoftkey.softKeySetIndex = htolel(softkey);
	req->data.selectsoftkey.validKeyMask = htolel(newmask);

	SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SELECT_SOFT_KEYS_MESSAGE to %s, inst %d, callid %d, softkey %d, mask 0x%08x\n",
		d->name, instance, callid, softkey, (unsigned)newmask);
	transmit_response(d, req);
}

static void transmit_lamp_indication(struct skinny_device *d, int stimulus, int instance, int indication)
{
	struct skinny_req *req;

	if (!(req = req_alloc(sizeof(struct set_lamp_message), SET_LAMP_MESSAGE)))
		return;

	req->data.setlamp.stimulus = htolel(stimulus);
	req->data.setlamp.stimulusInstance = htolel(instance);
	req->data.setlamp.deviceStimulus = htolel(indication);

	SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SET_LAMP_MESSAGE to %s, stim %d, inst %d, ind %d\n",
		d->name, stimulus, instance, indication);
	transmit_response(d, req);
}

static void transmit_ringer_mode(struct skinny_device *d, int mode)
{
	struct skinny_req *req;

	if (!(req = req_alloc(sizeof(struct set_ringer_message), SET_RINGER_MESSAGE)))
		return;

	req->data.setringer.ringerMode = htolel(mode);
	/* XXX okay, I don't quite know what this is, but here's what happens (on a 7960).
	   Note: The phone will always show as ringing on the display.

	   1: phone will audibly ring over and over
	   2: phone will audibly ring only once
	   any other value, will NOT cause the phone to audibly ring
	*/
	req->data.setringer.unknown1 = htolel(1);
	/* XXX the value here doesn't seem to change anything.  Must be higher than 0.
	   Perhaps a packet capture can shed some light on this. */
	req->data.setringer.unknown2 = htolel(1);

	SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SET_RINGER_MESSAGE to %s, mode %d, unk1 1, unk2 1\n",
		d->name, mode);
	transmit_response(d, req);
}

static void transmit_clear_display_message(struct skinny_device *d, int instance, int reference)
{
	struct skinny_req *req;
	if (!(req = req_alloc(sizeof(struct clear_display_message), CLEAR_DISPLAY_MESSAGE)))
		return;

	//what do we want hear CLEAR_DISPLAY_MESSAGE or CLEAR_PROMPT_STATUS???
	//if we are clearing the display, it appears there is no instance and refernece info (size 0)
	//req->data.clearpromptstatus.lineInstance = instance;
	//req->data.clearpromptstatus.callReference = reference;

	SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting CLEAR_DISPLAY_MESSAGE to %s\n", d->name);
	transmit_response(d, req);
}

/* This function is not currently used, but will be (wedhorn)*/
/* static void transmit_display_message(struct skinny_device *d, const char *text, int instance, int reference)
{
	struct skinny_req *req;

	if (text == 0) {
		ast_verb(1, "Bug, Asked to display empty message\n");
		return;
	}

	if (!(req = req_alloc(sizeof(struct displaytext_message), DISPLAYTEXT_MESSAGE)))
		return;

	ast_copy_string(req->data.displaytext.text, text, sizeof(req->data.displaytext.text));
	SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DISPLAYTEXT_MESSAGE to %s, text %s\n", d->name, text);
	transmit_response(d, req);
} */

static void transmit_displaynotify(struct skinny_device *d, const char *text, int t)
{
	struct skinny_req *req;

	if (!(req = req_alloc(sizeof(struct display_notify_message), DISPLAY_NOTIFY_MESSAGE)))
		return;

	ast_copy_string(req->data.displaynotify.displayMessage, text, sizeof(req->data.displaynotify.displayMessage));
	req->data.displaynotify.displayTimeout = htolel(t);

	SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DISPLAY_NOTIFY_MESSAGE to %s, text %s\n", d->name, text);
	transmit_response(d, req);
}

static void transmit_clearprinotify(struct skinny_device *d, int priority)
{
	struct skinny_req *req;

	if (!(req = req_alloc(sizeof(struct clear_prinotify_message), CLEAR_PRINOTIFY_MESSAGE)))
		return;

	req->data.clearprinotify.priority = htolel(priority);

	SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting CLEAR_PRINOTIFY_MESSAGE to %s, priority %d\n", d->name, priority);
	transmit_response(d, req);
}

static void _transmit_displayprinotify(struct skinny_device *d, const char *text, const char *extratext, int timeout, int priority)
{
	struct skinny_req *req;

	if (!(req = req_alloc(sizeof(struct display_prinotify_message), DISPLAY_PRINOTIFY_MESSAGE)))
		return;

	req->data.displayprinotify.timeout = htolel(timeout);
	req->data.displayprinotify.priority = htolel(priority);

	if ((char)*text == '\200') {
		int octalstrlen = strlen(text);
		ast_copy_string(req->data.displayprinotify.text, text, sizeof(req->data.displayprinotify.text));
		ast_copy_string(req->data.displayprinotify.text+octalstrlen, extratext, sizeof(req->data.displayprinotify.text)-octalstrlen);
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DISPLAY_PRINOTIFY_MESSAGE to %s, '\\%03o\\%03o', '%s', timeout=%d, priority=%d\n",
			d->name, (unsigned)*text, (unsigned)*(text+1), extratext, timeout, priority);
	} else {
		ast_copy_string(req->data.displayprinotify.text, text, sizeof(req->data.displayprinotify.text));
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DISPLAY_PRINOTIFY_MESSAGE to %s, '%s', timeout=%d, priority=%d\n",
			d->name, text, timeout, priority);
	}

	transmit_response(d, req);
}

static void _transmit_displayprinotifyvar(struct skinny_device *d, const char *text, const char *extratext, int timeout, int priority)
{
	struct skinny_req *req;
	int packetlen;

	if (!(req = req_alloc(sizeof(struct display_prinotify_message_variable), DISPLAY_PRINOTIFY_MESSAGE_VARIABLE)))
		return;

	req->data.displayprinotifyvar.timeout = htolel(timeout);
	req->data.displayprinotifyvar.priority = htolel(priority);

	if ((char)*text == '\200') {
		int octalstrlen = strlen(text);
		ast_copy_string(req->data.displayprinotifyvar.text, text, sizeof(req->data.displayprinotifyvar.text));
		ast_copy_string(req->data.displayprinotifyvar.text+octalstrlen, extratext, sizeof(req->data.displayprinotifyvar.text)-octalstrlen);
		packetlen = req->len - MAXDISPLAYNOTIFYSTR + strlen(text) + strlen(extratext);
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DISPLAY_PRINOTIFY_MESSAGE_VARIABLE to %s, '\\%03o\\%03o', '%s', timeout=%d, priority=%d\n",
			d->name, (unsigned)*text, (unsigned)*(text+1), extratext, timeout, priority);
	} else {
		ast_copy_string(req->data.displayprinotifyvar.text, text, sizeof(req->data.displayprinotifyvar.text));
		packetlen = req->len - MAXDISPLAYNOTIFYSTR + strlen(text);
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DISPLAY_PRINOTIFY_MESSAGE_VARIABLE to %s, '%s', timeout=%d, priority=%d\n",
			d->name, text, timeout, priority);
	}

	req->len = (packetlen & ~0x3) + 4;

	transmit_response(d, req);
}

static void send_displayprinotify(struct skinny_device *d, const char *text, const char *extratext, int timeout, int priority)
{
	if (d->protocolversion < 17) {
		_transmit_displayprinotify(d, text, extratext, timeout, priority);
	} else {
		_transmit_displayprinotifyvar(d, text, extratext, timeout, priority);
	}
}

static void transmit_displaypromptstatus(struct skinny_device *d, const char *text, const char *extratext, int t, int instance, int callid)
{
	struct skinny_req *req;

	if (!(req = req_alloc(sizeof(struct display_prompt_status_message), DISPLAY_PROMPT_STATUS_MESSAGE)))
		return;

	req->data.displaypromptstatus.messageTimeout = htolel(t);
	req->data.displaypromptstatus.lineInstance = htolel(instance);
	req->data.displaypromptstatus.callReference = htolel(callid);

	if ((char)*text == '\200') {
		int octalstrlen = strlen(text);
		ast_copy_string(req->data.displaypromptstatus.promptMessage, text, sizeof(req->data.displaypromptstatusvar.promptMessage));
		ast_copy_string(req->data.displaypromptstatus.promptMessage+octalstrlen, extratext, sizeof(req->data.displaypromptstatus.promptMessage)-octalstrlen);
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DISPLAY_PROMPT_STATUS_MESSAGE to %s, '\\%03o\\%03o', '%s'\n",
			d->name, (unsigned)*text, (unsigned)*(text+1), extratext);
	} else {
		ast_copy_string(req->data.displaypromptstatus.promptMessage, text, sizeof(req->data.displaypromptstatus.promptMessage));
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DISPLAY_PROMPT_STATUS_MESSAGE to %s, '%s'\n",
			d->name, text);
	}
	transmit_response(d, req);
}

static void transmit_displaypromptstatusvar(struct skinny_device *d, const char *text, const char *extratext, int t, int instance, int callid)
{
	struct skinny_req *req;
	int packetlen;

	if (!(req = req_alloc(sizeof(struct display_prompt_status_message_variable), DISPLAY_PROMPT_STATUS_MESSAGE_VARIABLE)))
		return;

	req->data.displaypromptstatusvar.lineInstance = htolel(instance);
	req->data.displaypromptstatusvar.callReference = htolel(callid);

	if ((char)*text == '\200') {
		int octalstrlen = strlen(text);
		ast_copy_string(req->data.displaypromptstatusvar.promptMessage, text, sizeof(req->data.displaypromptstatusvar.promptMessage));
		ast_copy_string(req->data.displaypromptstatusvar.promptMessage+octalstrlen, extratext, sizeof(req->data.displaypromptstatusvar.promptMessage)-octalstrlen);
		packetlen = req->len - MAXCALLINFOSTR + strlen(text) + strlen(extratext);
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DISPLAY_PROMPT_STATUS_MESSAGE_VARIABLE to %s, '\\%03o\\%03o', '%s'\n",
			d->name, (unsigned)*text, (unsigned)*(text+1), extratext);
	} else {
		ast_copy_string(req->data.displaypromptstatusvar.promptMessage, text, sizeof(req->data.displaypromptstatus.promptMessage));
		packetlen = req->len - MAXCALLINFOSTR + strlen(text);
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DISPLAY_PROMPT_STATUS_MESSAGE_VARIABLE to %s, '%s'\n",
			d->name, text);
	}
	req->len = (packetlen & ~0x3) + 4;

	transmit_response(d, req);
}

static void send_displaypromptstatus(struct skinny_device *d, const char *text, const char *extratext, int t, int instance, int callid)
{
	if (d->protocolversion < 17) {
		transmit_displaypromptstatus(d, text, extratext, t, instance, callid);
	} else {
		transmit_displaypromptstatusvar(d, text, extratext, t, instance, callid);
	}
}

static void transmit_clearpromptmessage(struct skinny_device *d, int instance, int callid)
{
	struct skinny_req *req;

	if (!(req = req_alloc(sizeof(struct clear_prompt_message), CLEAR_PROMPT_MESSAGE)))
		return;

	req->data.clearpromptstatus.lineInstance = htolel(instance);
	req->data.clearpromptstatus.callReference = htolel(callid);

	SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting CLEAR_PROMPT_MESSAGE to %s, inst %d, callid %d\n",
		d->name, instance, callid);
	transmit_response(d, req);
}

static void transmit_dialednumber(struct skinny_device *d, const char *text, int instance, int callid)
{
	struct skinny_req *req;

	if (!(req = req_alloc(sizeof(struct dialed_number_message), DIALED_NUMBER_MESSAGE)))
		return;

	ast_copy_string(req->data.dialednumber.dialedNumber, text, sizeof(req->data.dialednumber.dialedNumber));
	req->data.dialednumber.lineInstance = htolel(instance);
	req->data.dialednumber.callReference = htolel(callid);

	SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DIALED_NUMBER_MESSAGE to %s, num %s, inst %d, callid %d\n",
		d->name, text, instance, callid);
	transmit_response(d, req);
}

static void transmit_closereceivechannel(struct skinny_device *d, struct skinny_subchannel *sub)
{
	struct skinny_req *req;

	if (!(req = req_alloc(sizeof(struct close_receive_channel_message), CLOSE_RECEIVE_CHANNEL_MESSAGE)))
		return;

	req->data.closereceivechannel.conferenceId = htolel(0);
	req->data.closereceivechannel.partyId = htolel(sub->callid);

	SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting CLOSE_RECEIVE_CHANNEL_MESSAGE to %s, confid %d, callid %u\n",
		d->name, 0, sub->callid);
	transmit_response(d, req);
}

static void transmit_stopmediatransmission(struct skinny_device *d, struct skinny_subchannel *sub)
{
	struct skinny_req *req;

	if (!(req = req_alloc(sizeof(struct stop_media_transmission_message), STOP_MEDIA_TRANSMISSION_MESSAGE)))
		return;

	req->data.stopmedia.conferenceId = htolel(0);
	req->data.stopmedia.passThruPartyId = htolel(sub->callid);

	SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting STOP_MEDIA_TRANSMISSION_MESSAGE to %s, confid %d, passthrupartyid %u\n",
		d->name, 0, sub->callid);
	transmit_response(d, req);
}

static void transmit_startmediatransmission(struct skinny_device *d, struct skinny_subchannel *sub, struct sockaddr_in dest,
	struct ast_format *format, unsigned int framing)
{
	struct skinny_req *req;

	if (d->protocolversion < 17) {
		if (!(req = req_alloc(sizeof(struct start_media_transmission_message_ip4), START_MEDIA_TRANSMISSION_MESSAGE)))
			return;
		req->data.startmedia_ip4.conferenceId = htolel(sub->callid);
		req->data.startmedia_ip4.passThruPartyId = htolel(sub->callid);
		req->data.startmedia_ip4.remoteIp = dest.sin_addr.s_addr;
		req->data.startmedia_ip4.remotePort = htolel(ntohs(dest.sin_port));
		req->data.startmedia_ip4.packetSize = htolel(framing);
		req->data.startmedia_ip4.payloadType = htolel(codec_ast2skinny(format));
		req->data.startmedia_ip4.qualifier.precedence = htolel(127);
		req->data.startmedia_ip4.qualifier.vad = htolel(0);
		req->data.startmedia_ip4.qualifier.packets = htolel(0);
		req->data.startmedia_ip4.qualifier.bitRate = htolel(0);
	} else {
		if (!(req = req_alloc(sizeof(struct start_media_transmission_message_ip6), START_MEDIA_TRANSMISSION_MESSAGE)))
			return;
		req->data.startmedia_ip6.conferenceId = htolel(sub->callid);
		req->data.startmedia_ip6.passThruPartyId = htolel(sub->callid);
		memcpy(req->data.startmedia_ip6.remoteIp, &dest.sin_addr.s_addr, sizeof(dest.sin_addr.s_addr));
		req->data.startmedia_ip6.remotePort = htolel(ntohs(dest.sin_port));
		req->data.startmedia_ip6.packetSize = htolel(framing);
		req->data.startmedia_ip6.payloadType = htolel(codec_ast2skinny(format));
		req->data.startmedia_ip6.qualifier.precedence = htolel(127);
		req->data.startmedia_ip6.qualifier.vad = htolel(0);
		req->data.startmedia_ip6.qualifier.packets = htolel(0);
		req->data.startmedia_ip6.qualifier.bitRate = htolel(0);
	}

	SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting START_MEDIA_TRANSMISSION_MESSAGE to %s, callid %u, passthrupartyid %u, ip %s:%d, ms %u, fmt %d, prec 127\n",
		d->name, sub->callid, sub->callid, ast_inet_ntoa(dest.sin_addr), dest.sin_port, framing, codec_ast2skinny(format));
	transmit_response(d, req);
}

static void transmit_activatecallplane(struct skinny_device *d, struct skinny_line *l)
{
	struct skinny_req *req;

	if (!(req = req_alloc(sizeof(struct activate_call_plane_message), ACTIVATE_CALL_PLANE_MESSAGE)))
		return;

	req->data.activatecallplane.lineInstance = htolel(l->instance);

	SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting ACTIVATE_CALL_PLANE_MESSAGE to %s, inst %d\n",
		d->name, l->instance);
	transmit_response(d, req);
}

static void transmit_callstate(struct skinny_device *d, int buttonInstance, unsigned callid, int state)
{
	struct skinny_req *req;

	if (!(req = req_alloc(sizeof(struct call_state_message), CALL_STATE_MESSAGE)))
		return;

	req->data.callstate.callState = htolel(state);
	req->data.callstate.lineInstance = htolel(buttonInstance);
	req->data.callstate.callReference = htolel(callid);

	SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting CALL_STATE_MESSAGE to %s, state %s, inst %d, callid %u\n",
		d->name, callstate2str(state), buttonInstance, callid);
	transmit_response(d, req);
}

static void transmit_cfwdstate(struct skinny_device *d, struct skinny_line *l)
{
	struct skinny_req *req;
	int anyon = 0;

	if (!(req = req_alloc(sizeof(struct forward_stat_message), FORWARD_STAT_MESSAGE)))
		return;

	if (l->cfwdtype & SKINNY_CFWD_ALL) {
		if (!ast_strlen_zero(l->call_forward_all)) {
			ast_copy_string(req->data.forwardstat.fwdallnum, l->call_forward_all, sizeof(req->data.forwardstat.fwdallnum));
			req->data.forwardstat.fwdall = htolel(1);
			anyon++;
		} else {
			req->data.forwardstat.fwdall = htolel(0);
		}
	}
	if (l->cfwdtype & SKINNY_CFWD_BUSY) {
		if (!ast_strlen_zero(l->call_forward_busy)) {
			ast_copy_string(req->data.forwardstat.fwdbusynum, l->call_forward_busy, sizeof(req->data.forwardstat.fwdbusynum));
			req->data.forwardstat.fwdbusy = htolel(1);
			anyon++;
		} else {
			req->data.forwardstat.fwdbusy = htolel(0);
		}
	}
	if (l->cfwdtype & SKINNY_CFWD_NOANSWER) {
		if (!ast_strlen_zero(l->call_forward_noanswer)) {
			ast_copy_string(req->data.forwardstat.fwdnoanswernum, l->call_forward_noanswer, sizeof(req->data.forwardstat.fwdnoanswernum));
			req->data.forwardstat.fwdnoanswer = htolel(1);
			anyon++;
		} else {
			req->data.forwardstat.fwdnoanswer = htolel(0);
		}
	}
	req->data.forwardstat.lineNumber = htolel(l->instance);
	if (anyon)
		req->data.forwardstat.activeforward = htolel(7);
	else
		req->data.forwardstat.activeforward = htolel(0);

	SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting FORWARD_STAT_MESSAGE to %s, inst %d, all %s, busy %s, noans %s, acitve %d\n",
		d->name, l->instance, l->call_forward_all, l->call_forward_busy, l->call_forward_noanswer, anyon ? 7 : 0);
	transmit_response(d, req);
}

static void transmit_speeddialstatres(struct skinny_device *d, struct skinny_speeddial *sd)
{
	struct skinny_req *req;

	if (!(req = req_alloc(sizeof(struct speed_dial_stat_res_message), SPEED_DIAL_STAT_RES_MESSAGE)))
		return;

	req->data.speeddialreq.speedDialNumber = htolel(sd->instance);
	ast_copy_string(req->data.speeddial.speedDialDirNumber, sd->exten, sizeof(req->data.speeddial.speedDialDirNumber));
	ast_copy_string(req->data.speeddial.speedDialDisplayName, sd->label, sizeof(req->data.speeddial.speedDialDisplayName));

	SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SPEED_DIAL_STAT_RES_MESSAGE to %s, inst %d, dir %s, display %s\n",
		d->name, sd->instance, sd->exten, sd->label);
	transmit_response(d, req);
}

//static void transmit_linestatres(struct skinny_device *d, struct skinny_line *l)
static void transmit_linestatres(struct skinny_device *d, int instance)
{
	struct skinny_req *req;
	struct skinny_line *l;
	struct skinny_speeddial *sd;

	if (!(req = req_alloc(sizeof(struct line_stat_res_message), LINE_STAT_RES_MESSAGE)))
		return;

	if ((l = find_line_by_instance(d, instance))) {
		req->data.linestat.lineNumber = letohl(l->instance);
		memcpy(req->data.linestat.lineDirNumber, l->name, sizeof(req->data.linestat.lineDirNumber));
		memcpy(req->data.linestat.lineDisplayName, l->label, sizeof(req->data.linestat.lineDisplayName));
	} else if ((sd = find_speeddial_by_instance(d, instance, 1))) {
		req->data.linestat.lineNumber = letohl(sd->instance);
		memcpy(req->data.linestat.lineDirNumber, sd->label, sizeof(req->data.linestat.lineDirNumber));
		memcpy(req->data.linestat.lineDisplayName, sd->label, sizeof(req->data.linestat.lineDisplayName));
	}

	SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting LINE_STAT_RES_MESSAGE to %s, inst %d, num %s, label %s\n",
		d->name, l->instance, req->data.linestat.lineDirNumber, req->data.linestat.lineDisplayName);
	transmit_response(d, req);
}

static void transmit_definetimedate(struct skinny_device *d)
{
	struct skinny_req *req;
	struct timeval now = ast_tvnow();
	struct ast_tm cmtime;

	if (!(req = req_alloc(sizeof(struct definetimedate_message), DEFINETIMEDATE_MESSAGE)))
		return;

	ast_localtime(&now, &cmtime, NULL);
	req->data.definetimedate.year = htolel(cmtime.tm_year+1900);
	req->data.definetimedate.month = htolel(cmtime.tm_mon+1);
	req->data.definetimedate.dayofweek = htolel(cmtime.tm_wday);
	req->data.definetimedate.day = htolel(cmtime.tm_mday);
	req->data.definetimedate.hour = htolel(cmtime.tm_hour);
	req->data.definetimedate.minute = htolel(cmtime.tm_min);
	req->data.definetimedate.seconds = htolel(cmtime.tm_sec);
	req->data.definetimedate.milliseconds = htolel(cmtime.tm_usec / 1000);
	req->data.definetimedate.timestamp = htolel(now.tv_sec);

	SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DEFINETIMEDATE_MESSAGE to %s, date %u %u %u dow %u time %u:%u:%u.%u\n",
		d->name, req->data.definetimedate.year, req->data.definetimedate.month, req->data.definetimedate.day, req->data.definetimedate.dayofweek,
		req->data.definetimedate.hour, req->data.definetimedate.minute, req->data.definetimedate.seconds, req->data.definetimedate.milliseconds);
	transmit_response(d, req);
}

static void transmit_versionres(struct skinny_device *d)
{
	struct skinny_req *req;
	if (!(req = req_alloc(sizeof(struct version_res_message), VERSION_RES_MESSAGE)))
		return;

	ast_copy_string(req->data.version.version, d->version_id, sizeof(req->data.version.version));

	SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting VERSION_RES_MESSAGE to %s, version %s\n", d->name, d->version_id);
	transmit_response(d, req);
}

static void transmit_serverres(struct skinny_device *d)
{
	struct skinny_req *req;
	if (!(req = req_alloc(sizeof(struct server_res_message), SERVER_RES_MESSAGE)))
		return;

	memcpy(req->data.serverres.server[0].serverName, ourhost,
			sizeof(req->data.serverres.server[0].serverName));
	req->data.serverres.serverListenPort[0] = htolel(ourport);
	req->data.serverres.serverIpAddr[0] = htolel(d->ourip.s_addr);

	SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SERVER_RES_MESSAGE to %s, srvname %s %s:%d\n",
		d->name, ourhost, ast_inet_ntoa(d->ourip), ourport);
	transmit_response(d, req);
}

static void transmit_softkeysetres(struct skinny_device *d)
{
	struct skinny_req *req;
	int i;
	int x;
	int y;
	int keydefcount;
	const struct soft_key_definitions *softkeymode = soft_key_default_definitions;

	if (!(req = req_alloc(sizeof(struct soft_key_set_res_message), SOFT_KEY_SET_RES_MESSAGE)))
		return;

	SKINNY_DEBUG(DEBUG_TEMPLATE, 3, "Creating Softkey Template\n");

	keydefcount = ARRAY_LEN(soft_key_default_definitions);
	req->data.softkeysets.softKeySetOffset = htolel(0);
	req->data.softkeysets.softKeySetCount = htolel(keydefcount);
	req->data.softkeysets.totalSoftKeySetCount = htolel(keydefcount);
	for (x = 0; x < keydefcount; x++) {
		const uint8_t *defaults = softkeymode->defaults;
		/* XXX I wanted to get the size of the array dynamically, but that wasn't wanting to work.
		   This will have to do for now. */
		for (y = 0; y < softkeymode->count; y++) {
			for (i = 0; i < (sizeof(soft_key_template_default) / sizeof(struct soft_key_template_definition)); i++) {
				if (defaults[y] == i+1) {
					req->data.softkeysets.softKeySetDefinition[softkeymode->mode].softKeyTemplateIndex[y] = (i+1);
					req->data.softkeysets.softKeySetDefinition[softkeymode->mode].softKeyInfoIndex[y] = htoles(i+301);
					SKINNY_DEBUG(DEBUG_TEMPLATE, 4, "softKeySetDefinition : softKeyTemplateIndex: %d softKeyInfoIndex: %d\n",
						i+1, i+301);
				}
			}
		}
		softkeymode++;
	}

	SKINNY_DEBUG(DEBUG_PACKET | DEBUG_TEMPLATE, 3, "Transmitting SOFT_KEY_SET_RES_MESSAGE to %s, template data\n",
		d->name);
	transmit_response(d, req);
}

static void transmit_softkeytemplateres(struct skinny_device *d)
{
	struct skinny_req *req;

	if (!(req = req_alloc(sizeof(struct soft_key_template_res_message), SOFT_KEY_TEMPLATE_RES_MESSAGE)))
		return;

	req->data.softkeytemplate.softKeyOffset = htolel(0);
	req->data.softkeytemplate.softKeyCount = htolel(sizeof(soft_key_template_default) / sizeof(struct soft_key_template_definition));
	req->data.softkeytemplate.totalSoftKeyCount = htolel(sizeof(soft_key_template_default) / sizeof(struct soft_key_template_definition));
	memcpy(req->data.softkeytemplate.softKeyTemplateDefinition,
		soft_key_template_default,
		sizeof(soft_key_template_default));

	SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SOFT_KEY_TEMPLATE_RES_MESSAGE to %s, offset 0, keycnt %u, totalkeycnt %u, template data\n",
		d->name, req->data.softkeytemplate.softKeyCount, req->data.softkeytemplate.totalSoftKeyCount);
	transmit_response(d, req);
}

static void transmit_reset(struct skinny_device *d, int fullrestart)
{
	struct skinny_req *req;

	if (!(req = req_alloc(sizeof(struct reset_message), RESET_MESSAGE)))
		return;

	if (fullrestart)
		req->data.reset.resetType = 2;
	else
		req->data.reset.resetType = 1;

	SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting RESET_MESSAGE to %s, type %s\n",
		d->name, (fullrestart) ? "Restarting" : "Resetting");
	transmit_response(d, req);
}

static void transmit_keepaliveack(struct skinnysession *s)
{
	struct skinny_req *req;

	if (!(req = req_alloc(0, KEEP_ALIVE_ACK_MESSAGE)))
		return;

#ifdef AST_DEVMODE
	{
	struct skinny_device *d = s->device;
	SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting KEEP_ALIVE_ACK_MESSAGE to %s\n", (d ? d->name : "unregistered"));
	}
#endif
	transmit_response_bysession(s, req);
}

static void transmit_registerack(struct skinny_device *d)
{
	struct skinny_req *req;

	if (!(req = req_alloc(sizeof(struct register_ack_message), REGISTER_ACK_MESSAGE)))
		return;

	req->data.regack.res[0] = '0';
	req->data.regack.res[1] = '\0';
	req->data.regack.keepAlive = htolel(keep_alive);
	memcpy(req->data.regack.dateTemplate, date_format, sizeof(req->data.regack.dateTemplate));
	req->data.regack.res2[0] = '0';
	req->data.regack.res2[1] = '\0';
	req->data.regack.secondaryKeepAlive = htolel(keep_alive);

#ifdef AST_DEVMODE
	{
	short res = req->data.regack.res[0] << 8 | req->data.regack.res[1];
	unsigned int res2 = req->data.regack.res2[0] << 24 | req->data.regack.res2[1] << 16 | req->data.regack.res2[2] << 8 | req->data.regack.res2[3];
	SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting REGISTER_ACK_MESSAGE to %s, keepalive %d, datetemplate %s, seckeepalive %d, res 0x%04x, res2 0x%08x\n",
		d->name, keep_alive, date_format, keep_alive, (unsigned)res, res2);
	}
#endif

	transmit_response(d, req);
}

static void transmit_capabilitiesreq(struct skinny_device *d)
{
	struct skinny_req *req;

	if (!(req = req_alloc(0, CAPABILITIES_REQ_MESSAGE)))
		return;

	SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting CAPABILITIES_REQ_MESSAGE to %s\n", d->name);
	transmit_response(d, req);
}

static void transmit_backspace(struct skinny_device *d, int instance, unsigned callid)
{
	struct skinny_req *req;

	if (!(req = req_alloc(sizeof(struct bksp_req_message), BKSP_REQ_MESSAGE)))
		return;

	req->data.bkspmessage.instance = htolel(instance);
	req->data.bkspmessage.callreference = htolel(callid);

	SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting BKSP_REQ_MESSAGE to %s, inst %d, callid %u \n",
		d->name, instance, callid);
	transmit_response(d, req);
}

static void transmit_serviceurlstat(struct skinny_device *d, int instance)
{
	struct skinny_req *req;
	struct skinny_serviceurl *surl;

	if (!(req = req_alloc(sizeof(struct serviceurl_stat_message), SERVICEURL_STAT_MESSAGE)))
		return;

	AST_LIST_TRAVERSE(&d->serviceurls, surl, list) {
		if (surl->instance == instance) {
			break;
		}
	}

	if (surl) {
		memcpy(req->data.serviceurlmessage.displayName, surl->displayName, sizeof(req->data.serviceurlmessage.displayName));
		memcpy(req->data.serviceurlmessage.url, surl->url, sizeof(req->data.serviceurlmessage.url));
	}
	req->data.serviceurlmessage.instance = htolel(instance);

	SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SERVICEURL_STAT_MESSAGE to %s, inst %d\n",
		d->name, instance);
	transmit_response(d, req);
}

static int skinny_extensionstate_cb(char *context, char *exten, struct ast_state_cb_info *info, void *data)
{
	struct skinny_container *container = data;
	struct skinny_device *d = NULL;
	char hint[AST_MAX_EXTENSION];
	int state = info->exten_state;

	/* only interested in device state here */
	if (info->reason != AST_HINT_UPDATE_DEVICE) {
		return 0;
	}

	if (container->type == SKINNY_SDCONTAINER) {
		struct skinny_speeddial *sd = container->data;
		d = sd->parent;

		SKINNY_DEBUG(DEBUG_HINT, 3, "Got hint %s on speeddial %s\n", ast_extension_state2str(state), sd->label);

		if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, sd->context, sd->exten)) {
			/* If they are not registered, we will override notification and show no availability */
			if (ast_device_state(hint) == AST_DEVICE_UNAVAILABLE) {
				transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, SKINNY_LAMP_FLASH);
				transmit_callstate(d, sd->instance, 0, SKINNY_ONHOOK);
				return 0;
			}
			switch (state) {
			case AST_EXTENSION_DEACTIVATED: /* Retry after a while */
			case AST_EXTENSION_REMOVED:     /* Extension is gone */
				SKINNY_DEBUG(DEBUG_HINT, 3, "Extension state: Watcher for hint %s %s. Notify Device %s\n",
					exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", d->name);
				sd->stateid = -1;
				transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, SKINNY_LAMP_OFF);
				transmit_callstate(d, sd->instance, 0, SKINNY_ONHOOK);
				break;
			case AST_EXTENSION_RINGING:
			case AST_EXTENSION_UNAVAILABLE:
				transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, SKINNY_LAMP_BLINK);
				transmit_callstate(d, sd->instance, 0, SKINNY_RINGIN);
				break;
			case AST_EXTENSION_BUSY: /* callstate = SKINNY_BUSY wasn't wanting to work - I'll settle for this */
			case AST_EXTENSION_INUSE:
				transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, SKINNY_LAMP_ON);
				transmit_callstate(d, sd->instance, 0, SKINNY_CALLREMOTEMULTILINE);
				break;
			case AST_EXTENSION_ONHOLD:
				transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, SKINNY_LAMP_WINK);
				transmit_callstate(d, sd->instance, 0, SKINNY_HOLD);
				break;
			case AST_EXTENSION_NOT_INUSE:
			default:
				transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, SKINNY_LAMP_OFF);
				transmit_callstate(d, sd->instance, 0, SKINNY_ONHOOK);
				break;
			}
		}
		sd->laststate = state;
	} else if (container->type == SKINNY_SUBLINECONTAINER) {
		struct skinny_subline *subline = container->data;
		struct skinny_line *l = subline->line;
		d = l->device;

		SKINNY_DEBUG(DEBUG_HINT, 3, "Got hint %s on subline %s (%s@%s)\n", ast_extension_state2str(state), subline->name, exten, context);

		subline->extenstate = state;

		if (subline->callid == 0) {
			return 0;
		}

		switch (state) {
		case AST_EXTENSION_RINGING: /* Handled by normal ringin */
			break;
		case AST_EXTENSION_INUSE:
			if (subline->sub && (subline->sub->substate == SKINNY_CONNECTED)) { /* Device has a real call */
				transmit_callstate(d, l->instance, subline->callid, SKINNY_CONNECTED);
				transmit_selectsoftkeys(d, l->instance, subline->callid, KEYDEF_CONNECTED, KEYMASK_ALL);
				send_displaypromptstatus(d, OCTAL_CONNECTED, "", 0, l->instance, subline->callid);
			} else { /* Some other device has active call */
				transmit_callstate(d, l->instance, subline->callid, SKINNY_CALLREMOTEMULTILINE);
				transmit_selectsoftkeys(d, l->instance, subline->callid, KEYDEF_SLACONNECTEDNOTACTIVE, KEYMASK_ALL);
				send_displaypromptstatus(d, "In Use", "", 0, l->instance, subline->callid);
			}
			transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_ON);
			transmit_ringer_mode(d, SKINNY_RING_OFF);
			transmit_activatecallplane(d, l);
			break;
		case AST_EXTENSION_ONHOLD:
			transmit_callstate(d, l->instance, subline->callid, SKINNY_HOLD);
			transmit_selectsoftkeys(d, l->instance, subline->callid, KEYDEF_SLAHOLD, KEYMASK_ALL);
			send_displaypromptstatus(d, "Hold", "", 0, l->instance, subline->callid);
			transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_BLINK);
			transmit_activatecallplane(d, l);
			break;
		case AST_EXTENSION_NOT_INUSE:
			transmit_callstate(d, l->instance, subline->callid, SKINNY_ONHOOK);
			transmit_selectsoftkeys(d, l->instance, subline->callid, KEYDEF_ONHOOK, KEYMASK_ALL);
			transmit_clearpromptmessage(d, l->instance, subline->callid);
			transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_OFF);
			transmit_activatecallplane(d, l);
			subline->callid = 0;
			break;
		default:
			ast_log(LOG_WARNING, "AST_EXTENSION_STATE %s not configured\n", ast_extension_state2str(state));
		}
	} else {
		ast_log(LOG_WARNING, "Invalid data supplied to skinny_extensionstate_cb\n");
	}

	return 0;
}

static void update_connectedline(struct skinny_subchannel *sub, const void *data, size_t datalen)
{
	struct ast_channel *c = sub->owner;
	struct skinny_line *l = sub->line;
	struct skinny_device *d = l->device;

	if (!d->session) {
		return;
	}

	if (sub->calldirection == SKINNY_OUTGOING && !sub->origtonum) {
		/* Do not set origtonum before here or origtoname won't be set */
		sub->origtonum = ast_strdup(sub->exten);
		if (ast_channel_connected(c)->id.name.valid) {
			sub->origtoname = ast_strdup(ast_channel_connected(c)->id.name.str);
		}
	}

	if (!ast_channel_caller(c)->id.number.valid
		|| ast_strlen_zero(ast_channel_caller(c)->id.number.str)
		|| !ast_channel_connected(c)->id.number.valid
		|| ast_strlen_zero(ast_channel_connected(c)->id.number.str))
		return;

	SKINNY_DEBUG(DEBUG_SUB, 3, "Sub %u - Updating\n", sub->callid);

	send_callinfo(sub);
}

static void mwi_event_cb(void *userdata, struct stasis_subscription *sub, struct stasis_message *msg)
{
	struct skinny_line *l = userdata;
	struct skinny_device *d = l->device;
	struct skinny_line *l2;
	int dev_msgs = 0;

	if (!d || !d->session) {
		return;
	}

	if (msg && ast_mwi_state_type() == stasis_message_type(msg)) {
		struct ast_mwi_state *mwi_state = stasis_message_data(msg);
		l->newmsgs = mwi_state->new_msgs;
	}

	if (l->newmsgs) {
		transmit_lamp_indication(d, STIMULUS_VOICEMAIL, l->instance, l->mwiblink?SKINNY_LAMP_BLINK:SKINNY_LAMP_ON);
	} else {
		transmit_lamp_indication(d, STIMULUS_VOICEMAIL, l->instance, SKINNY_LAMP_OFF);
	}

	/* find out wether the device lamp should be on or off */
	AST_LIST_TRAVERSE(&d->lines, l2, list) {
		if (l2->newmsgs) {
			dev_msgs++;
		}
	}

	if (dev_msgs) {
		transmit_lamp_indication(d, STIMULUS_VOICEMAIL, 0, d->mwiblink?SKINNY_LAMP_BLINK:SKINNY_LAMP_ON);
	} else {
		transmit_lamp_indication(d, STIMULUS_VOICEMAIL, 0, SKINNY_LAMP_OFF);
	}
	ast_verb(3, "Skinny mwi_event_cb found %d new messages\n", l->newmsgs);
}

/* I do not believe skinny can deal with video.
   Anyone know differently? */
/* Yes, it can.  Currently 7985 and Cisco VT Advantage do video. */
static enum ast_rtp_glue_result skinny_get_vrtp_peer(struct ast_channel *c, struct ast_rtp_instance **instance)
{
	struct skinny_subchannel *sub = NULL;

	if (!(sub = ast_channel_tech_pvt(c)) || !(sub->vrtp))
		return AST_RTP_GLUE_RESULT_FORBID;

	ao2_ref(sub->vrtp, +1);
	*instance = sub->vrtp;

	return AST_RTP_GLUE_RESULT_REMOTE;
}

static enum ast_rtp_glue_result skinny_get_rtp_peer(struct ast_channel *c, struct ast_rtp_instance **instance)
{
	struct skinny_subchannel *sub = NULL;
	struct skinny_line *l;
	enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_REMOTE;

	SKINNY_DEBUG(DEBUG_AUDIO, 4, "skinny_get_rtp_peer() Channel = %s\n", ast_channel_name(c));

	if (!(sub = ast_channel_tech_pvt(c)))
		return AST_RTP_GLUE_RESULT_FORBID;

	skinny_locksub(sub);

	if (!(sub->rtp)){
		skinny_unlocksub(sub);
		return AST_RTP_GLUE_RESULT_FORBID;
	}

	ao2_ref(sub->rtp, +1);
	*instance = sub->rtp;

	l = sub->line;

	if (!l->directmedia || l->nat){
		res = AST_RTP_GLUE_RESULT_LOCAL;
		SKINNY_DEBUG(DEBUG_AUDIO, 4, "skinny_get_rtp_peer() Using AST_RTP_GLUE_RESULT_LOCAL \n");
	}

	skinny_unlocksub(sub);

	return res;

}

static int skinny_set_rtp_peer(struct ast_channel *c, struct ast_rtp_instance *rtp, struct ast_rtp_instance *vrtp, struct ast_rtp_instance *trtp, const struct ast_format_cap *codecs, int nat_active)
{
	struct skinny_subchannel *sub;
	struct skinny_line *l;
	struct skinny_device *d;
	struct sockaddr_in us = { 0, };
	struct sockaddr_in them = { 0, };
	struct ast_sockaddr them_tmp;
	struct ast_sockaddr us_tmp;

	sub = ast_channel_tech_pvt(c);

	if (ast_channel_state(c) != AST_STATE_UP)
		return 0;

	if (!sub) {
		return -1;
	}

	l = sub->line;
	d = l->device;

	if (rtp){
		struct ast_format *tmpfmt;
		unsigned int framing;
		ast_rtp_instance_get_remote_address(rtp, &them_tmp);
		ast_sockaddr_to_sin(&them_tmp, &them);

		/* Shutdown any early-media or previous media on re-invite */
		transmit_stopmediatransmission(d, sub);

		SKINNY_DEBUG(DEBUG_AUDIO, 4, "Peerip = %s:%d\n", ast_inet_ntoa(them.sin_addr), ntohs(them.sin_port));

		tmpfmt = ast_format_cap_get_format(l->cap, 0);
		framing = ast_format_cap_get_format_framing(l->cap, tmpfmt);

		SKINNY_DEBUG(DEBUG_AUDIO, 4, "Setting payloadType to '%s' (%u ms)\n", ast_format_get_name(tmpfmt), framing);

		if (!(l->directmedia) || (l->nat)){
			ast_rtp_instance_get_local_address(rtp, &us_tmp);
			ast_sockaddr_to_sin(&us_tmp, &us);
			us.sin_addr.s_addr = us.sin_addr.s_addr ? us.sin_addr.s_addr : d->ourip.s_addr;
			transmit_startmediatransmission(d, sub, us, tmpfmt, framing);
		} else {
			transmit_startmediatransmission(d, sub, them, tmpfmt, framing);
		}

		ao2_ref(tmpfmt, -1);

		return 0;
	}
	/* Need a return here to break the bridge */
	return 0;
}

static struct ast_rtp_glue skinny_rtp_glue = {
	.type = "Skinny",
	.get_rtp_info = skinny_get_rtp_peer,
	.get_vrtp_info = skinny_get_vrtp_peer,
	.update_peer = skinny_set_rtp_peer,
};

#ifdef AST_DEVMODE
static char *skinny_debugs(void)
{
	char *ptr;
	int posn = 0;

	ptr = dbgcli_buf;
	strncpy(ptr, "\0", 1);
	if (skinnydebug & DEBUG_GENERAL) {
		strncpy(ptr, "general ", 8);
		posn += 8;
		ptr += 8;
	}
	if (skinnydebug & DEBUG_SUB) {
		strncpy(ptr, "sub ", 4);
		posn += 4;
		ptr += 4;
	}
	if (skinnydebug & DEBUG_AUDIO) {
		strncpy(ptr, "audio ", 6);
		posn += 6;
		ptr += 6;
	}
	if (skinnydebug & DEBUG_PACKET) {
		strncpy(ptr, "packet ", 7);
		posn += 7;
		ptr += 7;
	}
	if (skinnydebug & DEBUG_LOCK) {
		strncpy(ptr, "lock ", 5);
		posn += 5;
		ptr += 5;
	}
	if (skinnydebug & DEBUG_TEMPLATE) {
		strncpy(ptr, "template ", 9);
		posn += 9;
		ptr += 9;
	}
	if (skinnydebug & DEBUG_THREAD) {
		strncpy(ptr, "thread ", 7);
		posn += 7;
		ptr += 7;
	}
	if (skinnydebug & DEBUG_HINT) {
		strncpy(ptr, "hint ", 5);
		posn += 5;
		ptr += 5;
	}
	if (skinnydebug & DEBUG_KEEPALIVE) {
		strncpy(ptr, "keepalive ", 10);
		posn += 10;
		ptr += 10;
	}
	if (posn > 0) {
		strncpy(--ptr, "\0", 1);
	}
	return dbgcli_buf;
}

static char *complete_skinny_debug(const char *line, const char *word, int pos, int state)
{
	const char *debugOpts[]={ "all","audio","hint","keepalive","lock","off","packet","show","sub","template","thread",NULL };
	char *wordptr = (char *)word;
	char buf[32];
	char *bufptr = buf;
	int buflen = sizeof(buf);
	int wordlen;
	int which = 0;
	int i = 0;

	if (*word == '+' || *word == '-' || *word == '!') {
		*bufptr = *word;
		wordptr++;
		bufptr++;
		buflen--;
	}
	wordlen = strlen(wordptr);

	while (debugOpts[i]) {
		if (!strncasecmp(wordptr, debugOpts[i], wordlen) && ++which > state) {
			ast_copy_string(bufptr, debugOpts[i], buflen);
			return ast_strdup(buf);
		}
		i++;
	}

	return NULL;
}

static char *handle_skinny_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
	int i;
	int result = 0;
	const char *arg;
	int bitmask;
	int negate;

	switch (cmd) {
	case CLI_INIT:
		e->command = "skinny debug";
		e->usage =
			"Usage: skinny debug {audio|hint|keepalive|lock|off|packet|show|sub|template|thread}\n"
			"       Enables/Disables various Skinny debugging messages\n";
		return NULL;
	case CLI_GENERATE:
		return complete_skinny_debug(a->line, a->word, a->pos, a->n);

	}

	if (a->argc < 3)
		return CLI_SHOWUSAGE;

	if (a->argc == 3 && !strncasecmp(a->argv[e->args-1], "show", 4)) {
		ast_cli(a->fd, "Skinny Debugging - %s\n", skinny_debugs());
		return CLI_SUCCESS;
	}

	for(i = e->args; i < a->argc; i++) {
		result++;
		arg = a->argv[i];

		if (!strncasecmp(arg, "off", 3)) {
			skinnydebug = 0;
			continue;
		}

		if (!strncasecmp(arg, "all", 3)) {
			skinnydebug = DEBUG_GENERAL|DEBUG_SUB|DEBUG_PACKET|DEBUG_AUDIO|DEBUG_LOCK|DEBUG_TEMPLATE|DEBUG_THREAD|DEBUG_HINT|DEBUG_KEEPALIVE;
			continue;
		}

		if (!strncasecmp(arg, "-", 1) || !strncasecmp(arg, "!", 1)) {
			negate = 1;
			arg++;
		} else if (!strncasecmp(arg, "+", 1)) {
			negate = 0;
			arg++;
		} else {
			negate = 0;
		}

		if (!strncasecmp(arg, "general", 7)) {
			bitmask = DEBUG_GENERAL;
		} else if (!strncasecmp(arg, "sub", 3)) {
			bitmask = DEBUG_SUB;
		} else if (!strncasecmp(arg, "packet", 6)) {
			bitmask = DEBUG_PACKET;
		} else if (!strncasecmp(arg, "audio", 5)) {
			bitmask = DEBUG_AUDIO;
		} else if (!strncasecmp(arg, "lock", 4)) {
			bitmask = DEBUG_LOCK;
		} else if (!strncasecmp(arg, "template", 8)) {
			bitmask = DEBUG_TEMPLATE;
		} else if (!strncasecmp(arg, "thread", 6)) {
			bitmask = DEBUG_THREAD;
		} else if (!strncasecmp(arg, "hint", 4)) {
			bitmask = DEBUG_HINT;
		} else if (!strncasecmp(arg, "keepalive", 9)) {
			bitmask = DEBUG_KEEPALIVE;
		} else {
			ast_cli(a->fd, "Skinny Debugging - option '%s' unknown\n", a->argv[i]);
			result--;
			continue;
		}

		if (negate) {
			skinnydebug &= ~bitmask;
		} else {
			skinnydebug |= bitmask;
		}
	}
	if (result) {
		ast_cli(a->fd, "Skinny Debugging - %s\n", skinnydebug ? skinny_debugs() : "off");
		return CLI_SUCCESS;
	} else {
		return CLI_SHOWUSAGE;
	}
}
#endif

static char *handle_skinny_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
	switch (cmd) {
	case CLI_INIT:
		e->command = "skinny reload";
		e->usage =
			"Usage: skinny reload\n"
			"       Reloads the chan_skinny configuration\n";
		return NULL;
	case CLI_GENERATE:
		return NULL;
	}

	if (a->argc != e->args)
		return CLI_SHOWUSAGE;

	skinny_reload();
	return CLI_SUCCESS;

}

static char *complete_skinny_devices(const char *word, int state)
{
	struct skinny_device *d;
	int wordlen = strlen(word), which = 0;

	AST_LIST_TRAVERSE(&devices, d, list) {
		if (!strncasecmp(word, d->name, wordlen) && ++which > state) {
                       return ast_strdup(d->name);
               }
	}

	return NULL;
}

static char *complete_skinny_show_device(const char *line, const char *word, int pos, int state)
{
	return (pos == 3 ? complete_skinny_devices(word, state) : NULL);
}

static char *complete_skinny_reset(const char *line, const char *word, int pos, int state)
{
	return (pos == 2 ? complete_skinny_devices(word, state) : NULL);
}

static char *complete_skinny_show_line(const char *line, const char *word, int pos, int state)
{
	struct skinny_device *d;
	struct skinny_line *l;
	int wordlen = strlen(word), which = 0;

	if (pos != 3)
		return NULL;

	AST_LIST_TRAVERSE(&devices, d, list) {
		AST_LIST_TRAVERSE(&d->lines, l, list) {
			if (!strncasecmp(word, l->name, wordlen) && ++which > state) {
				return ast_strdup(l->name);
			}
		}
	}

	return NULL;
}

static char *handle_skinny_reset(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
	struct skinny_device *d;

	switch (cmd) {
	case CLI_INIT:
		e->command = "skinny reset";
		e->usage =
			"Usage: skinny reset <DeviceId|DeviceName|all> [restart]\n"
			"       Causes a Skinny device to reset itself, optionally with a full restart\n";
		return NULL;
	case CLI_GENERATE:
		return complete_skinny_reset(a->line, a->word, a->pos, a->n);
	}

	if (a->argc < 3 || a->argc > 4)
		return CLI_SHOWUSAGE;

	AST_LIST_LOCK(&devices);
	AST_LIST_TRAVERSE(&devices, d, list) {
		int resetonly = 1;
		if (!strcasecmp(a->argv[2], d->id) || !strcasecmp(a->argv[2], d->name) || !strcasecmp(a->argv[2], "all")) {
			if (!(d->session))
				continue;

			if (a->argc == 4 && !strcasecmp(a->argv[3], "restart"))
				resetonly = 0;

			transmit_reset(d, resetonly);
		}
	}
	AST_LIST_UNLOCK(&devices);
	return CLI_SUCCESS;
}

static char *device2str(int type)
{
	char *tmp;

	switch (type) {
	case SKINNY_DEVICE_NONE:
		return "No Device";
	case SKINNY_DEVICE_30SPPLUS:
		return "30SP Plus";
	case SKINNY_DEVICE_12SPPLUS:
		return "12SP Plus";
	case SKINNY_DEVICE_12SP:
		return "12SP";
	case SKINNY_DEVICE_12:
		return "12";
	case SKINNY_DEVICE_30VIP:
		return "30VIP";
	case SKINNY_DEVICE_7910:
		return "7910";
	case SKINNY_DEVICE_7960:
		return "7960";
	case SKINNY_DEVICE_7940:
		return "7940";
	case SKINNY_DEVICE_7935:
		return "7935";
	case SKINNY_DEVICE_ATA186:
		return "ATA186";
	case SKINNY_DEVICE_7941:
		return "7941";
	case SKINNY_DEVICE_7971:
		return "7971";
	case SKINNY_DEVICE_7914:
		return "7914";
	case SKINNY_DEVICE_7985:
		return "7985";
	case SKINNY_DEVICE_7911:
		return "7911";
	case SKINNY_DEVICE_7961GE:
		return "7961GE";
	case SKINNY_DEVICE_7941GE:
		return "7941GE";
	case SKINNY_DEVICE_7931:
		return "7931";
	case SKINNY_DEVICE_7921:
		return "7921";
	case SKINNY_DEVICE_7906:
		return "7906";
	case SKINNY_DEVICE_7962:
		return "7962";
	case SKINNY_DEVICE_7937:
		return "7937";
	case SKINNY_DEVICE_7942:
		return "7942";
	case SKINNY_DEVICE_7945:
		return "7945";
	case SKINNY_DEVICE_7965:
		return "7965";
	case SKINNY_DEVICE_7975:
		return "7975";
	case SKINNY_DEVICE_7905:
		return "7905";
	case SKINNY_DEVICE_7920:
		return "7920";
	case SKINNY_DEVICE_7970:
		return "7970";
	case SKINNY_DEVICE_7912:
		return "7912";
	case SKINNY_DEVICE_7902:
		return "7902";
	case SKINNY_DEVICE_CIPC:
		return "IP Communicator";
	case SKINNY_DEVICE_7961:
		return "7961";
	case SKINNY_DEVICE_7936:
		return "7936";
	case SKINNY_DEVICE_SCCPGATEWAY_AN:
		return "SCCPGATEWAY_AN";
	case SKINNY_DEVICE_SCCPGATEWAY_BRI:
		return "SCCPGATEWAY_BRI";
	case SKINNY_DEVICE_UNKNOWN:
		return "Unknown";
	default:
		if (!(tmp = ast_threadstorage_get(&device2str_threadbuf, DEVICE2STR_BUFSIZE)))
			return "Unknown";
		snprintf(tmp, DEVICE2STR_BUFSIZE, "UNKNOWN-%d", type);
		return tmp;
	}
}

static char *_skinny_show_devices(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char * const *argv)
{
	struct skinny_device *d;
	struct skinny_line *l;
	const char *id;
	char idtext[256] = "";
	int total_devices = 0;

	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 3:
		break;
	default:
		return CLI_SHOWUSAGE;
	}

	if (!s) {
		ast_cli(fd, "Name                 DeviceId         IP              Type            R NL\n");
		ast_cli(fd, "-------------------- ---------------- --------------- --------------- - --\n");
	}

	AST_LIST_LOCK(&devices);
	AST_LIST_TRAVERSE(&devices, d, list) {
		int numlines = 0;
		total_devices++;
		AST_LIST_TRAVERSE(&d->lines, l, list) {
			numlines++;
		}
		if (!s) {
			ast_cli(fd, "%-20s %-16s %-15s %-15s %c %2d\n",
				d->name,
				d->id,
				d->session?ast_inet_ntoa(d->session->sin.sin_addr):"",
				device2str(d->type),
				d->session?'Y':'N',
				numlines);
		} else {
			astman_append(s,
				"Event: DeviceEntry\r\n%s"
				"Channeltype: SKINNY\r\n"
				"ObjectName: %s\r\n"
				"ChannelObjectType: device\r\n"
				"DeviceId: %s\r\n"
				"IPaddress: %s\r\n"
				"Type: %s\r\n"
				"Devicestatus: %s\r\n"
				"NumberOfLines: %d\r\n",
				idtext,
				d->name,
				d->id,
				d->session?ast_inet_ntoa(d->session->sin.sin_addr):"-none-",
				device2str(d->type),
				d->session?"registered":"unregistered",
				numlines);
		}
	}
	AST_LIST_UNLOCK(&devices);

	if (total)
		*total = total_devices;

	return CLI_SUCCESS;
}

/*! \brief  Show SKINNY devices in the manager API */
/*    Inspired from chan_sip */
static int manager_skinny_show_devices(struct mansession *s, const struct message *m)
{
	const char *a[] = {"skinny", "show", "devices"};
	int total = 0;

	astman_send_listack(s, m, "Device status list will follow", "start");

	/* List the devices in separate manager events */
	_skinny_show_devices(-1, &total, s, m, 3, a);

	/* Send final confirmation */
	astman_send_list_complete_start(s, m, "DevicelistComplete", total);
	astman_send_list_complete_end(s);
	return 0;
}

static char *handle_skinny_show_devices(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{

	switch (cmd) {
	case CLI_INIT:
		e->command = "skinny show devices";
		e->usage =
			"Usage: skinny show devices\n"
			"       Lists all devices known to the Skinny subsystem.\n";
		return NULL;
	case CLI_GENERATE:
		return NULL;
	}

	return _skinny_show_devices(a->fd, NULL, NULL, NULL, a->argc, a->argv);
}

static char *_skinny_show_device(int type, int fd, struct mansession *s, const struct message *m, int argc, const char * const *argv)
{
	struct skinny_device *d;
	struct skinny_line *l;
	struct skinny_speeddial *sd;
	struct skinny_addon *sa;
	struct skinny_serviceurl *surl;
	struct ast_str *codec_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);

	if (argc < 4) {
		return CLI_SHOWUSAGE;
	}

	AST_LIST_LOCK(&devices);
	AST_LIST_TRAVERSE(&devices, d, list) {
		if (!strcasecmp(argv[3], d->id) || !strcasecmp(argv[3], d->name)) {
			int numlines = 0, numaddons = 0, numspeeddials = 0, numserviceurls = 0;

			AST_LIST_TRAVERSE(&d->lines, l, list){
				numlines++;
			}

			AST_LIST_TRAVERSE(&d->addons, sa, list) {
				numaddons++;
			}

			AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
				numspeeddials++;
			}

			AST_LIST_TRAVERSE(&d->serviceurls, surl, list) {
				numserviceurls++;
			}

			if (type == 0) { /* CLI */
				ast_cli(fd, "Name:        %s\n", d->name);
				ast_cli(fd, "Id:          %s\n", d->id);
				ast_cli(fd, "version:     %s\n", S_OR(d->version_id, "Unknown"));
				ast_cli(fd, "Ip address:  %s\n", (d->session ? ast_inet_ntoa(d->session->sin.sin_addr) : "Unknown"));
				ast_cli(fd, "Port:        %d\n", (d->session ? ntohs(d->session->sin.sin_port) : 0));
				ast_cli(fd, "Device Type: %s\n", device2str(d->type));
				ast_cli(fd, "Conf Codecs: %s\n", ast_format_cap_get_names(d->confcap, &codec_buf));
				ast_cli(fd, "Neg Codecs: %s\n", ast_format_cap_get_names(d->cap, &codec_buf));
				ast_cli(fd, "Registered:  %s\n", (d->session ? "Yes" : "No"));
				ast_cli(fd, "Lines:       %d\n", numlines);
				AST_LIST_TRAVERSE(&d->lines, l, list) {
					ast_cli(fd, "  %s (%s)\n", l->name, l->label);
				}
				ast_cli(fd, "Addons:      %d\n", numaddons);
				AST_LIST_TRAVERSE(&d->addons, sa, list) {
					ast_cli(fd, "  %s\n", sa->type);
				}
				ast_cli(fd, "Speeddials:  %d\n", numspeeddials);
				AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
					ast_cli(fd, "  %s (%s) ishint: %d\n", sd->exten, sd->label, sd->isHint);
				}
				ast_cli(fd, "ServiceURLs:  %d\n", numserviceurls);
				AST_LIST_TRAVERSE(&d->serviceurls, surl, list) {
					ast_cli(fd, "  %s (%s)\n", surl->displayName, surl->url);
				}
			} else { /* manager */
				astman_append(s, "Channeltype: SKINNY\r\n");
				astman_append(s, "ObjectName: %s\r\n", d->name);
				astman_append(s, "ChannelObjectType: device\r\n");
				astman_append(s, "Id: %s\r\n", d->id);
				astman_append(s, "version: %s\r\n", S_OR(d->version_id, "Unknown"));
				astman_append(s, "Ipaddress: %s\r\n", (d->session ? ast_inet_ntoa(d->session->sin.sin_addr) : "Unknown"));
				astman_append(s, "Port: %d\r\n", (d->session ? ntohs(d->session->sin.sin_port) : 0));
				astman_append(s, "DeviceType: %s\r\n", device2str(d->type));
				astman_append(s, "Codecs: %s\r\n", ast_format_cap_get_names(d->confcap, &codec_buf));
				astman_append(s, "CodecOrder: %s\r\n", ast_format_cap_get_names(d->cap, &codec_buf));
				astman_append(s, "Devicestatus: %s\r\n", (d->session?"registered":"unregistered"));
				astman_append(s, "NumberOfLines: %d\r\n", numlines);
				AST_LIST_TRAVERSE(&d->lines, l, list) {
					astman_append(s, "Line: %s (%s)\r\n", l->name, l->label);
				}
				astman_append(s, "NumberOfAddons: %d\r\n", numaddons);
				AST_LIST_TRAVERSE(&d->addons, sa, list) {
					astman_append(s, "Addon: %s\r\n", sa->type);
				}
				astman_append(s, "NumberOfSpeeddials: %d\r\n", numspeeddials);
				AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
					astman_append(s, "Speeddial: %s (%s) ishint: %d\r\n", sd->exten, sd->label, sd->isHint);
				}
				astman_append(s, "ServiceURLs:  %d\r\n", numserviceurls);
				AST_LIST_TRAVERSE(&d->serviceurls, surl, list) {
					astman_append(s, "  %s (%s)\r\n", surl->displayName, surl->url);
				}
			}
		}
	}
	AST_LIST_UNLOCK(&devices);
	return CLI_SUCCESS;
}

static int manager_skinny_show_device(struct mansession *s, const struct message *m)
{
	const char *a[4];
	const char *device;

	device = astman_get_header(m, "Device");
	if (ast_strlen_zero(device)) {
		astman_send_error(s, m, "Device: <name> missing.");
		return 0;
	}
	a[0] = "skinny";
	a[1] = "show";
	a[2] = "device";
	a[3] = device;

	_skinny_show_device(1, -1, s, m, 4, a);
	astman_append(s, "\r\n\r\n" );
	return 0;
}

/*! \brief Show device information */
static char *handle_skinny_show_device(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
	switch (cmd) {
	case CLI_INIT:
		e->command = "skinny show device";
		e->usage =
			"Usage: skinny show device <DeviceId|DeviceName>\n"
			"       Lists all deviceinformation of a specific device known to the Skinny subsystem.\n";
		return NULL;
	case CLI_GENERATE:
		return complete_skinny_show_device(a->line, a->word, a->pos, a->n);
	}

	return _skinny_show_device(0, a->fd, NULL, NULL, a->argc, a->argv);
}

static char *_skinny_show_lines(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char * const *argv)
{
	struct skinny_line *l;
	struct skinny_subchannel *sub;
	int total_lines = 0;
	int verbose = 0;
	const char *id;
	char idtext[256] = "";

	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 4:
		verbose = 1;
		break;
	case 3:
		verbose = 0;
		break;
	default:
		return CLI_SHOWUSAGE;
	}

	if (!s) {
		ast_cli(fd, "Name                 Device Name          Instance Label               \n");
		ast_cli(fd, "-------------------- -------------------- -------- --------------------\n");
	}
	AST_LIST_LOCK(&lines);
	AST_LIST_TRAVERSE(&lines, l, all) {
		total_lines++;
		if (!s) {
			ast_cli(fd, "%-20s %-20s %8d %-20s\n",
				l->name,
				(l->device ? l->device->name : "Not connected"),
				l->instance,
				l->label);
			if (verbose) {
				AST_LIST_TRAVERSE(&l->sub, sub, list) {
					RAII_VAR(struct ast_channel *, bridged, ast_channel_bridge_peer(sub->owner), ao2_cleanup);

					ast_cli(fd, "  %s> %s to %s\n",
						(sub == l->activesub?"Active  ":"Inactive"),
						ast_channel_name(sub->owner),
						bridged ? ast_channel_name(bridged) : ""
					);
				}
			}
		} else {
			astman_append(s,
				"Event: LineEntry\r\n%s"
				"Channeltype: SKINNY\r\n"
				"ObjectName: %s\r\n"
				"ChannelObjectType: line\r\n"
				"Device: %s\r\n"
				"Instance: %d\r\n"
				"Label: %s\r\n",
				idtext,
				l->name,
				(l->device ? l->device->name : "None"),
				l->instance,
				l->label);
		}
	}
	AST_LIST_UNLOCK(&lines);

	if (total) {
		*total = total_lines;
	}

	return CLI_SUCCESS;
}

/*! \brief  Show Skinny lines in the manager API */
/*    Inspired from chan_sip */
static int manager_skinny_show_lines(struct mansession *s, const struct message *m)
{
	const char *a[] = {"skinny", "show", "lines"};
	int total = 0;

	astman_send_listack(s, m, "Line status list will follow", "start");

	/* List the lines in separate manager events */
	_skinny_show_lines(-1, &total, s, m, 3, a);

	/* Send final confirmation */
	astman_send_list_complete_start(s, m, "LinelistComplete", total);
	astman_send_list_complete_end(s);
	return 0;
}

static char *handle_skinny_show_lines(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
	switch (cmd) {
	case CLI_INIT:
		e->command = "skinny show lines [verbose]";
		e->usage =
			"Usage: skinny show lines\n"
			"       Lists all lines known to the Skinny subsystem.\n"
			"       If 'verbose' is specified, the output includes\n"
			"       information about subs for each line.\n";
		return NULL;
	case CLI_GENERATE:
		return NULL;
	}

	if (a->argc == e->args) {
		if (strcasecmp(a->argv[e->args-1], "verbose")) {
			return CLI_SHOWUSAGE;
		}
	} else if (a->argc != e->args - 1) {
		return CLI_SHOWUSAGE;
	}

	return _skinny_show_lines(a->fd, NULL, NULL, NULL, a->argc, a->argv);
}

static char *_skinny_show_line(int type, int fd, struct mansession *s, const struct message *m, int argc, const char * const *argv)
{
	struct skinny_device *d;
	struct skinny_line *l;
	struct skinny_subline *subline;
	struct ast_str *codec_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
	char group_buf[256];
	char cbuf[256];

	switch (argc) {
	case 4:
		break;
	case 6:
		break;
	default:
		return CLI_SHOWUSAGE;
	}

	AST_LIST_LOCK(&devices);

	/* Show all lines matching the one supplied */
	AST_LIST_TRAVERSE(&devices, d, list) {
		if (argc == 6 && (strcasecmp(argv[5], d->id) && strcasecmp(argv[5], d->name))) {
			continue;
		}
		AST_LIST_TRAVERSE(&d->lines, l, list) {
			struct ast_str *tmp_str = ast_str_alloca(512);

			if (strcasecmp(argv[3], l->name)) {
				continue;
			}
			if (type == 0) { /* CLI */
				ast_cli(fd, "Line:             %s\n", l->name);
				ast_cli(fd, "On Device:        %s\n", d->name);
				ast_cli(fd, "Line Label:       %s\n", l->label);
				ast_cli(fd, "Extension:        %s\n", S_OR(l->exten, "<not set>"));
				ast_cli(fd, "Context:          %s\n", l->context);
				ast_cli(fd, "CallGroup:        %s\n", ast_print_group(group_buf, sizeof(group_buf), l->callgroup));
				ast_cli(fd, "PickupGroup:      %s\n", ast_print_group(group_buf, sizeof(group_buf), l->pickupgroup));
				ast_cli(fd, "NamedCallGroup:   %s\n", ast_print_namedgroups(&tmp_str, l->named_callgroups));
				ast_str_reset(tmp_str);
				ast_cli(fd, "NamedPickupGroup: %s\n", ast_print_namedgroups(&tmp_str, l->named_pickupgroups));
				ast_str_reset(tmp_str);
				ast_cli(fd, "Language:         %s\n", S_OR(l->language, "<not set>"));
				ast_cli(fd, "Accountcode:      %s\n", S_OR(l->accountcode, "<not set>"));
				ast_cli(fd, "AmaFlag:          %s\n", ast_channel_amaflags2string(l->amaflags));
				ast_cli(fd, "CallerId Number:  %s\n", S_OR(l->cid_num, "<not set>"));
				ast_cli(fd, "CallerId Name:    %s\n", S_OR(l->cid_name, "<not set>"));
				ast_cli(fd, "Hide CallerId:    %s\n", (l->hidecallerid ? "Yes" : "No"));
				ast_cli(fd, "CFwdAll:          %s\n", S_COR((l->cfwdtype & SKINNY_CFWD_ALL), l->call_forward_all, "<not set>"));
				ast_cli(fd, "CFwdBusy:         %s\n", S_COR((l->cfwdtype & SKINNY_CFWD_BUSY), l->call_forward_busy, "<not set>"));
				ast_cli(fd, "CFwdNoAnswer:     %s\n", S_COR((l->cfwdtype & SKINNY_CFWD_NOANSWER), l->call_forward_noanswer, "<not set>"));
				ast_cli(fd, "CFwdTimeout:      %dms\n", l->callfwdtimeout);
				ast_cli(fd, "VoicemailBox:     %s\n", S_OR(l->mailbox, "<not set>"));
				ast_cli(fd, "VoicemailNumber:  %s\n", S_OR(l->vmexten, "<not set>"));
				ast_cli(fd, "MWIblink:         %d\n", l->mwiblink);
				ast_cli(fd, "Regextension:     %s\n", S_OR(l->regexten, "<not set>"));
				ast_cli(fd, "Regcontext:       %s\n", S_OR(l->regcontext, "<not set>"));
				ast_cli(fd, "MoHInterpret:     %s\n", S_OR(l->mohinterpret, "<not set>"));
				ast_cli(fd, "MoHSuggest:       %s\n", S_OR(l->mohsuggest, "<not set>"));
				ast_cli(fd, "Last dialed nr:   %s\n", S_OR(l->lastnumberdialed, "<no calls made yet>"));
				ast_cli(fd, "Last CallerID:    %s\n", S_OR(l->lastcallerid, "<not set>"));
				ast_cli(fd, "Transfer enabled: %s\n", (l->transfer ? "Yes" : "No"));
				ast_cli(fd, "Callwaiting:      %s\n", (l->callwaiting ? "Yes" : "No"));
				ast_cli(fd, "3Way Calling:     %s\n", (l->threewaycalling ? "Yes" : "No"));
				ast_cli(fd, "Can forward:      %s\n", (l->cancallforward ? "Yes" : "No"));
				ast_cli(fd, "Do Not Disturb:   %s\n", (l->dnd ? "Yes" : "No"));
				ast_cli(fd, "NAT:              %s\n", (l->nat ? "Yes" : "No"));
				ast_cli(fd, "immediate:        %s\n", (l->immediate ? "Yes" : "No"));
				ast_cli(fd, "Group:            %d\n", l->group);
				ast_cli(fd, "Parkinglot:       %s\n", S_OR(l->parkinglot, "<not set>"));
				ast_cli(fd, "Conf Codecs:      %s\n", ast_format_cap_get_names(l->confcap, &codec_buf));
				ast_cli(fd, "Neg Codecs:       %s\n", ast_format_cap_get_names(l->cap, &codec_buf));
				if  (AST_LIST_FIRST(&l->sublines)) {
					ast_cli(fd, "Sublines:\n");
					AST_LIST_TRAVERSE(&l->sublines, subline, list) {
						ast_cli(fd, "     %s, %s@%s\n", subline->name, subline->exten, subline->context);
					}
				}
				ast_cli(fd, "\n");
			} else { /* manager */
				astman_append(s, "Channeltype: SKINNY\r\n");
				astman_append(s, "ObjectName: %s\r\n", l->name);
				astman_append(s, "ChannelObjectType: line\r\n");
				astman_append(s, "Device: %s\r\n", d->name);
				astman_append(s, "LineLabel: %s\r\n", l->label);
				astman_append(s, "Extension: %s\r\n", S_OR(l->exten, "<not set>"));
				astman_append(s, "Context: %s\r\n", l->context);
				astman_append(s, "CallGroup: %s\r\n", ast_print_group(group_buf, sizeof(group_buf), l->callgroup));
				astman_append(s, "PickupGroup: %s\r\n", ast_print_group(group_buf, sizeof(group_buf), l->pickupgroup));
				astman_append(s, "NamedCallGroup: %s\r\n", ast_print_namedgroups(&tmp_str, l->named_callgroups));
				ast_str_reset(tmp_str);
				astman_append(s, "NamedPickupGroup: %s\r\n", ast_print_namedgroups(&tmp_str, l->named_pickupgroups));
				ast_str_reset(tmp_str);
				astman_append(s, "Language: %s\r\n", S_OR(l->language, "<not set>"));
				astman_append(s, "Accountcode: %s\r\n", S_OR(l->accountcode, "<not set>"));
				astman_append(s, "AMAflags: %s\r\n", ast_channel_amaflags2string(l->amaflags));
				astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), l->cid_name, l->cid_num, ""));
				astman_append(s, "HideCallerId: %s\r\n", (l->hidecallerid ? "Yes" : "No"));
				astman_append(s, "CFwdAll: %s\r\n", S_COR((l->cfwdtype & SKINNY_CFWD_ALL), l->call_forward_all, "<not set>"));
				astman_append(s, "CFwdBusy: %s\r\n", S_COR((l->cfwdtype & SKINNY_CFWD_BUSY), l->call_forward_busy, "<not set>"));
				astman_append(s, "CFwdNoAnswer: %s\r\n", S_COR((l->cfwdtype & SKINNY_CFWD_NOANSWER), l->call_forward_noanswer, "<not set>"));
				astman_append(s, "VoicemailBox: %s\r\n", S_OR(l->mailbox, "<not set>"));
				astman_append(s, "VoicemailNumber: %s\r\n", S_OR(l->vmexten, "<not set>"));
				astman_append(s, "MWIblink: %d\r\n", l->mwiblink);
				astman_append(s, "RegExtension: %s\r\n", S_OR(l->regexten, "<not set>"));
				astman_append(s, "Regcontext: %s\r\n", S_OR(l->regcontext, "<not set>"));
				astman_append(s, "MoHInterpret: %s\r\n", S_OR(l->mohinterpret, "<not set>"));
				astman_append(s, "MoHSuggest: %s\r\n", S_OR(l->mohsuggest, "<not set>"));
				astman_append(s, "LastDialedNr: %s\r\n", S_OR(l->lastnumberdialed, "<no calls made yet>"));
				astman_append(s, "LastCallerID: %s\r\n", S_OR(l->lastcallerid, "<not set>"));
				astman_append(s, "Transfer: %s\r\n", (l->transfer ? "Yes" : "No"));
				astman_append(s, "Callwaiting: %s\r\n", (l->callwaiting ? "Yes" : "No"));
				astman_append(s, "3WayCalling: %s\r\n", (l->threewaycalling ? "Yes" : "No"));
				astman_append(s, "CanForward: %s\r\n", (l->cancallforward ? "Yes" : "No"));
				astman_append(s, "DoNotDisturb: %s\r\n", (l->dnd ? "Yes" : "No"));
				astman_append(s, "NAT: %s\r\n", (l->nat ? "Yes" : "No"));
				astman_append(s, "immediate: %s\r\n", (l->immediate ? "Yes" : "No"));
				astman_append(s, "Group: %d\r\n", l->group);
				astman_append(s, "Parkinglot: %s\r\n", S_OR(l->parkinglot, "<not set>"));
				astman_append(s, "Codecs: %s\r\n", ast_format_cap_get_names(l->confcap, &codec_buf));
				astman_append(s, "\r\n");
			}
		}
	}

	AST_LIST_UNLOCK(&devices);
	return CLI_SUCCESS;
}

static int manager_skinny_show_line(struct mansession *s, const struct message *m)
{
	const char *a[4];
	const char *line;

	line = astman_get_header(m, "Line");
	if (ast_strlen_zero(line)) {
		astman_send_error(s, m, "Line: <name> missing.");
		return 0;
	}
	a[0] = "skinny";
	a[1] = "show";
	a[2] = "line";
	a[3] = line;

	_skinny_show_line(1, -1, s, m, 4, a);
	astman_append(s, "\r\n\r\n" );
	return 0;
}

/*! \brief List line information. */
static char *handle_skinny_show_line(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
	switch (cmd) {
	case CLI_INIT:
		e->command = "skinny show line";
		e->usage =
			"Usage: skinny show line <Line> [ on <DeviceID|DeviceName> ]\n"
			"       List all lineinformation of a specific line known to the Skinny subsystem.\n";
		return NULL;
	case CLI_GENERATE:
		return complete_skinny_show_line(a->line, a->word, a->pos, a->n);
	}

	return _skinny_show_line(0, a->fd, NULL, NULL, a->argc, a->argv);
}

/*! \brief List global settings for the Skinny subsystem. */
static char *handle_skinny_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
	char immed_str[2] = {immed_dialchar, '\0'};

	switch (cmd) {
	case CLI_INIT:
		e->command = "skinny show settings";
		e->usage =
			"Usage: skinny show settings\n"
			"       Lists all global configuration settings of the Skinny subsystem.\n";
		return NULL;
	case CLI_GENERATE:
		return NULL;
	}

	if (a->argc != 3)
		return CLI_SHOWUSAGE;

	ast_cli(a->fd, "\nGlobal Settings:\n");
	ast_cli(a->fd, "  Skinny Port:            %d\n", ntohs(bindaddr.sin_port));
	ast_cli(a->fd, "  Bindaddress:            %s\n", ast_inet_ntoa(bindaddr.sin_addr));
	ast_cli(a->fd, "  KeepAlive:              %d\n", keep_alive);
	ast_cli(a->fd, "  Date Format:            %s\n", date_format);
	ast_cli(a->fd, "  Voice Mail Extension:   %s\n", S_OR(vmexten, "(not set)"));
	ast_cli(a->fd, "  Reg. context:           %s\n", S_OR(regcontext, "(not set)"));
	ast_cli(a->fd, "  Immed. Dial Key:        %s\n", S_OR(immed_str, "(not set)"));
	ast_cli(a->fd, "  Jitterbuffer enabled:   %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_ENABLED)));
	 if (ast_test_flag(&global_jbconf, AST_JB_ENABLED)) {
		ast_cli(a->fd, "  Jitterbuffer forced:    %s\n", AST_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);
		if (!strcasecmp(global_jbconf.impl, "adaptive")) {
			ast_cli(a->fd, "  Jitterbuffer tgt extra: %ld\n", global_jbconf.target_extra);
		}
		ast_cli(a->fd, "  Jitterbuffer log:       %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_LOG)));
	}

	return CLI_SUCCESS;
}

static char *_skinny_message_set(int type, int fd, struct mansession *s, const struct message *m, int argc, const char * const *argv)
{
	struct skinny_device *d;
	char text_buf[32];

	if (argc < 7) {
		return CLI_SHOWUSAGE;
	}

	AST_LIST_LOCK(&devices);
	AST_LIST_TRAVERSE(&devices, d, list) {
		if (!strcasecmp(argv[3], d->name)) {
			int i;
			char *strp = text_buf;
			int charleft = sizeof(text_buf);
			int priority = atoi(argv[4]);
			int timeout = atoi(argv[5]);
			ast_copy_string(strp, argv[6], charleft);
			charleft -= strlen(strp);
			strp += strlen(strp);
			for(i=7; i<argc; i++) {
				ast_copy_string(strp++, " ", charleft--);
				ast_copy_string(strp, argv[i], charleft);
				charleft -= strlen(strp);
				strp += strlen(strp);
			}
			send_displayprinotify(d, text_buf, "", timeout, priority);
		}
	}
	AST_LIST_UNLOCK(&devices);
	return CLI_SUCCESS;
}

/*! \brief Handle sending messages to devices. */
static char *handle_skinny_message_set(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
	switch (cmd) {
	case CLI_INIT:
		e->command = "skinny message set";
		e->usage =
			"Usage: skinny message set <device> <priority> <timeout> <message>\n"
			"       Set the current priority level message on a device.\n";
		return NULL;
	case CLI_GENERATE:
		return complete_skinny_show_device(a->line, a->word, a->pos, a->n);
	}

	return _skinny_message_set(0, a->fd, NULL, NULL, a->argc, a->argv);
}

static char *_skinny_message_clear(int type, int fd, struct mansession *s, const struct message *m, int argc, const char * const *argv)
{
	struct skinny_device *d;

	if (argc != 5) {
		return CLI_SHOWUSAGE;
	}

	AST_LIST_LOCK(&devices);
	AST_LIST_TRAVERSE(&devices, d, list) {
		if (!strcasecmp(argv[3], d->name)) {
			int priority = atoi(argv[4]);
			transmit_clearprinotify(d, priority);
		}
	}
	AST_LIST_UNLOCK(&devices);
	return CLI_SUCCESS;
}

/*! \brief Handle clearing messages to devices. */
static char *handle_skinny_message_clear(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
	switch (cmd) {
	case CLI_INIT:
		e->command = "skinny message clear";
		e->usage =
			"Usage: skinny message clear <device> <priority>\n"
			"       Clear the current priority level message on device.\n";
		return NULL;
	case CLI_GENERATE:
		return complete_skinny_show_device(a->line, a->word, a->pos, a->n);
	}

	return _skinny_message_clear(0, a->fd, NULL, NULL, a->argc, a->argv);
}

static struct ast_cli_entry cli_skinny[] = {
	AST_CLI_DEFINE(handle_skinny_show_devices, "List defined Skinny devices"),
	AST_CLI_DEFINE(handle_skinny_show_device, "List Skinny device information"),
	AST_CLI_DEFINE(handle_skinny_show_lines, "List defined Skinny lines per device"),
	AST_CLI_DEFINE(handle_skinny_show_line, "List Skinny line information"),
	AST_CLI_DEFINE(handle_skinny_show_settings, "List global Skinny settings"),
#ifdef AST_DEVMODE
	AST_CLI_DEFINE(handle_skinny_set_debug, "Enable/Disable Skinny debugging"),
#endif
	AST_CLI_DEFINE(handle_skinny_reset, "Reset Skinny device(s)"),
	AST_CLI_DEFINE(handle_skinny_reload, "Reload Skinny config"),
	AST_CLI_DEFINE(handle_skinny_message_set, "Send message to devices"),
	AST_CLI_DEFINE(handle_skinny_message_clear, "Clear message to devices"),
};

static void start_rtp(struct skinny_subchannel *sub)
{
	struct skinny_line *l = sub->line;
	struct skinny_device *d = l->device;
	int hasvideo = 0;
	struct ast_sockaddr bindaddr_tmp;

	skinny_locksub(sub);
	SKINNY_DEBUG(DEBUG_AUDIO, 3, "Sub %u - Starting RTP\n", sub->callid);
	ast_sockaddr_from_sin(&bindaddr_tmp, &bindaddr);
	sub->rtp = ast_rtp_instance_new("asterisk", sched, &bindaddr_tmp, NULL);
	if (hasvideo)
		sub->vrtp = ast_rtp_instance_new("asterisk", sched, &bindaddr_tmp, NULL);

	if (sub->rtp) {
		ast_rtp_instance_set_prop(sub->rtp, AST_RTP_PROPERTY_RTCP, 1);
	}
	if (sub->vrtp) {
		ast_rtp_instance_set_prop(sub->vrtp, AST_RTP_PROPERTY_RTCP, 1);
	}

	if (sub->rtp && sub->owner) {
		ast_rtp_instance_set_channel_id(sub->rtp, ast_channel_uniqueid(sub->owner));
		ast_channel_set_fd(sub->owner, 0, ast_rtp_instance_fd(sub->rtp, 0));
		ast_channel_set_fd(sub->owner, 1, ast_rtp_instance_fd(sub->rtp, 1));
	}
	if (hasvideo && sub->vrtp && sub->owner) {
		ast_rtp_instance_set_channel_id(sub->vrtp, ast_channel_uniqueid(sub->owner));
		ast_channel_set_fd(sub->owner, 2, ast_rtp_instance_fd(sub->vrtp, 0));
		ast_channel_set_fd(sub->owner, 3, ast_rtp_instance_fd(sub->vrtp, 1));
	}
	if (sub->rtp) {
		ast_rtp_instance_set_qos(sub->rtp, qos.tos_audio, qos.cos_audio, "Skinny RTP");
		ast_rtp_instance_set_prop(sub->rtp, AST_RTP_PROPERTY_NAT, l->nat);
		/* Set frame packetization */
		ast_rtp_codecs_set_framing(ast_rtp_instance_get_codecs(sub->rtp),
			ast_format_cap_get_framing(l->cap));
	}
	if (sub->vrtp) {
		ast_rtp_instance_set_qos(sub->vrtp, qos.tos_video, qos.cos_video, "Skinny VRTP");
		ast_rtp_instance_set_prop(sub->vrtp, AST_RTP_PROPERTY_NAT, l->nat);
	}

	/* Create the RTP connection */
	transmit_connect(d, sub);
	skinny_unlocksub(sub);
}

static void destroy_rtp(struct skinny_subchannel *sub)
{
	if (sub->rtp) {
		SKINNY_DEBUG(DEBUG_AUDIO, 3, "Sub %u - Destroying RTP\n", sub->callid);
		ast_rtp_instance_stop(sub->rtp);
		ast_rtp_instance_destroy(sub->rtp);
		sub->rtp = NULL;
	}
	if (sub->vrtp) {
		SKINNY_DEBUG(DEBUG_AUDIO, 3, "Sub %u - Destroying VRTP\n", sub->callid);
		ast_rtp_instance_stop(sub->vrtp);
		ast_rtp_instance_destroy(sub->vrtp);
		sub->vrtp = NULL;
	}
}

static void *skinny_newcall(void *data)
{
	struct ast_channel *c = data;
	struct skinny_subchannel *sub = ast_channel_tech_pvt(c);
	struct skinny_line *l = sub->line;
	struct skinny_device *d = l->device;
	int res = 0;

	ast_channel_lock(c);
	ast_set_callerid(c,
		l->hidecallerid ? "" : l->cid_num,
		l->hidecallerid ? "" : l->cid_name,
		ast_channel_caller(c)->ani.number.valid ? NULL : l->cid_num);
#if 1	/* XXX This code is probably not necessary */
	ast_party_number_free(&ast_channel_connected(c)->id.number);
	ast_party_number_init(&ast_channel_connected(c)->id.number);
	ast_channel_connected(c)->id.number.valid = 1;
	ast_channel_connected(c)->id.number.str = ast_strdup(ast_channel_exten(c));
	ast_party_name_free(&ast_channel_connected(c)->id.name);
	ast_party_name_init(&ast_channel_connected(c)->id.name);
#endif
	ast_setstate(c, AST_STATE_RING);
	ast_channel_unlock(c);
	if (!sub->rtp) {
		start_rtp(sub);
	}
	ast_verb(3, "Sub %u - Calling %s@%s\n", sub->callid, ast_channel_exten(c), ast_channel_context(c));
	res = ast_pbx_run(c);
	if (res) {
		ast_log(LOG_WARNING, "PBX exited non-zero\n");
		transmit_start_tone(d, SKINNY_REORDER, l->instance, sub->callid);
	}
	return NULL;
}

static void skinny_dialer(struct skinny_subchannel *sub, int timedout)
{
	struct ast_channel *c = sub->owner;
	struct skinny_line *l = sub->line;
	struct skinny_device *d = l->device;

	if (timedout || !ast_matchmore_extension(c, ast_channel_context(c), sub->exten, 1, l->cid_num)) {
		SKINNY_DEBUG(DEBUG_SUB, 3, "Sub %u - Force dialing '%s' because of %s\n", sub->callid, sub->exten, (timedout ? "timeout" : "exactmatch"));
		if (ast_exists_extension(c, ast_channel_context(c), sub->exten, 1, l->cid_num)) {
			if (sub->substate == SUBSTATE_OFFHOOK) {
				dialandactivatesub(sub, sub->exten);
			}
		} else {
			if (d->hookstate == SKINNY_OFFHOOK) {
				// FIXME: redundant because below will onhook before the sound plays, but it correct to send it.
				transmit_start_tone(d, SKINNY_REORDER, l->instance, sub->callid);
			}
			dumpsub(sub, 0);
		}
	} else {
		SKINNY_DEBUG(DEBUG_SUB, 3, "Sub %u - Wait for more digits\n", sub->callid);
		if (ast_exists_extension(c, ast_channel_context(c), sub->exten, 1, l->cid_num)) {
			transmit_selectsoftkeys(d, l->instance, sub->callid, KEYDEF_DADFD, KEYMASK_ALL);
			sub->dialer_sched = skinny_sched_add(matchdigittimeout, skinny_dialer_cb, sub);
		} else {
			sub->dialer_sched = skinny_sched_add(gendigittimeout, skinny_dialer_cb, sub);
		}
	}
}

static int skinny_dialer_cb(const void *data)
{
	struct skinny_subchannel *sub = (struct skinny_subchannel *)data;
	SKINNY_DEBUG(DEBUG_SUB, 3, "Sub %u - Dialer called from SCHED %d\n", sub->callid, sub->dialer_sched);
	sub->dialer_sched = -1;
	skinny_dialer(sub, 1);
	return 0;
}

static int skinny_autoanswer_cb(const void *data)
{
	struct skinny_subchannel *sub = (struct skinny_subchannel *)data;
	skinny_locksub(sub);
	sub->aa_sched = -1;
	setsubstate(sub, SKINNY_CONNECTED);
	skinny_unlocksub(sub);
	return 0;
}

static int skinny_cfwd_cb(const void *data)
{
	struct skinny_subchannel *sub = (struct skinny_subchannel *)data;
	struct skinny_line *l = sub->line;
	sub->cfwd_sched = -1;
	SKINNY_DEBUG(DEBUG_SUB, 3, "Sub %u - CFWDNOANS to %s.\n", sub->callid, l->call_forward_noanswer);
	ast_channel_call_forward_set(sub->owner, l->call_forward_noanswer);
	ast_queue_control(sub->owner, AST_CONTROL_REDIRECTING);
	return 0;
}

static int skinny_call(struct ast_channel *ast, const char *dest, int timeout)
{
	int res = 0;
	struct skinny_subchannel *sub = ast_channel_tech_pvt(ast);
	struct skinny_line *l = sub->line;
	struct skinny_device *d = l->device;
	struct ast_var_t *current;
	int doautoanswer = 0;

	if (!d || !d->session) {
		ast_log(LOG_WARNING, "Device not registered, cannot call %s\n", dest);
		return -1;
	}

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

	SKINNY_DEBUG(DEBUG_SUB, 3, "Skinny Call (%s) - Sub %u\n",
		ast_channel_name(ast), sub->callid);

	if (l->dnd) {
		ast_queue_control(ast, AST_CONTROL_BUSY);
		return -1;
	}

	if (AST_LIST_NEXT(sub,list) && !l->callwaiting) {
		ast_queue_control(ast, AST_CONTROL_BUSY);
		return -1;
	}

	skinny_locksub(sub);
	AST_LIST_TRAVERSE(ast_channel_varshead(ast), current, entries) {
		if (!(strcmp(ast_var_name(current), "SKINNY_AUTOANSWER"))) {
			if (d->hookstate == SKINNY_ONHOOK && sub->aa_sched < 0) {
				char buf[24];
				int aatime;
				char *stringp = buf, *curstr;
				ast_copy_string(buf, ast_var_value(current), sizeof(buf));
				curstr = strsep(&stringp, ":");
				aatime = atoi(curstr);
				while ((curstr = strsep(&stringp, ":"))) {
					if (!(strcasecmp(curstr,"BEEP"))) {
						sub->aa_beep = 1;
					} else if (!(strcasecmp(curstr,"MUTE"))) {
						sub->aa_mute = 1;
					}
				}
				SKINNY_DEBUG(DEBUG_SUB, 3, "Sub %u - setting autoanswer time=%dms %s%s\n",
					sub->callid, aatime, sub->aa_beep ? "BEEP " : "", sub->aa_mute ? "MUTE" : "");
				if (aatime) {
					//sub->aa_sched = ast_sched_add(sched, aatime, skinny_autoanswer_cb, sub);
					sub->aa_sched = skinny_sched_add(aatime, skinny_autoanswer_cb, sub);
				} else {
					doautoanswer = 1;
				}
			}
		}
	}

	setsubstate(sub, SUBSTATE_RINGIN);
	if (doautoanswer) {
		setsubstate(sub, SUBSTATE_CONNECTED);
	}
	skinny_unlocksub(sub);
	return res;
}

static int skinny_hangup(struct ast_channel *ast)
{
	struct skinny_subchannel *sub = ast_channel_tech_pvt(ast);

	if (!sub) {
		ast_debug(1, "Asked to hangup channel not connected\n");
		return 0;
	}

	dumpsub(sub, 1);

	SKINNY_DEBUG(DEBUG_SUB, 3, "Sub %u - Destroying\n", sub->callid);

	skinny_set_owner(sub, NULL);
	ast_channel_tech_pvt_set(ast, NULL);
	destroy_rtp(sub);
	ast_free(sub->origtonum);
	ast_free(sub->origtoname);
	ast_free(sub);
	ast_module_unref(ast_module_info->self);
	return 0;
}

static int skinny_answer(struct ast_channel *ast)
{
	int res = 0;
	struct skinny_subchannel *sub = ast_channel_tech_pvt(ast);

	sub->cxmode = SKINNY_CX_SENDRECV;

	SKINNY_DEBUG(DEBUG_SUB, 3, "skinny_answer(%s) on %s@%s-%u\n",
		ast_channel_name(ast), sub->line->name, sub->line->device->name, sub->callid);

	setsubstate(sub, SUBSTATE_CONNECTED);

	return res;
}

/* Retrieve audio/etc from channel.  Assumes sub->lock is already held. */
static struct ast_frame *skinny_rtp_read(struct skinny_subchannel *sub)
{
	struct ast_channel *ast = sub->owner;
	struct ast_frame *f;

	if (!sub->rtp) {
		/* We have no RTP allocated for this channel */
		return &ast_null_frame;
	}

	switch(ast_channel_fdno(ast)) {
	case 0:
		f = ast_rtp_instance_read(sub->rtp, 0); /* RTP Audio */
		break;
	case 1:
		f = ast_rtp_instance_read(sub->rtp, 1); /* RTCP Control Channel */
		break;
	case 2:
		f = ast_rtp_instance_read(sub->vrtp, 0); /* RTP Video */
		break;
	case 3:
		f = ast_rtp_instance_read(sub->vrtp, 1); /* RTCP Control Channel for video */
		break;
#if 0
	case 5:
		/* Not yet supported */
		f = ast_udptl_read(sub->udptl); /* UDPTL for T.38 */
		break;
#endif
	default:
		f = &ast_null_frame;
	}

	if (ast) {
		/* We already hold the channel lock */
		if (f->frametype == AST_FRAME_VOICE) {
			if (ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), f->subclass.format) == AST_FORMAT_CMP_NOT_EQUAL) {
				struct ast_format_cap *caps;

				ast_debug(1, "Oooh, format changed to %s\n", ast_format_get_name(f->subclass.format));

				caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
				if (caps) {
					ast_format_cap_append(caps, f->subclass.format, 0);
					ast_channel_nativeformats_set(ast, caps);
					ao2_ref(caps, -1);
				}
				ast_set_read_format(ast, ast_channel_readformat(ast));
				ast_set_write_format(ast, ast_channel_writeformat(ast));
			}
		}
	}
	return f;
}

static struct ast_frame *skinny_read(struct ast_channel *ast)
{
	struct ast_frame *fr;
	struct skinny_subchannel *sub = ast_channel_tech_pvt(ast);
	skinny_locksub(sub);
	fr = skinny_rtp_read(sub);
	skinny_unlocksub(sub);
	return fr;
}

static int skinny_write(struct ast_channel *ast, struct ast_frame *frame)
{
	struct skinny_subchannel *sub = ast_channel_tech_pvt(ast);
	int res = 0;
	if (frame->frametype != AST_FRAME_VOICE) {
		if (frame->frametype == AST_FRAME_IMAGE) {
			return 0;
		} else {
			ast_log(LOG_WARNING, "Can't send %u type frames with skinny_write\n", frame->frametype);
			return 0;
		}
	} else {
		if (ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), frame->subclass.format) == AST_FORMAT_CMP_NOT_EQUAL) {
			struct ast_str *codec_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
			ast_log(LOG_WARNING, "Asked to transmit frame type %s, while native formats is %s (read/write = %s/%s)\n",
				ast_format_get_name(frame->subclass.format),
				ast_format_cap_get_names(ast_channel_nativeformats(ast), &codec_buf),
				ast_format_get_name(ast_channel_readformat(ast)),
				ast_format_get_name(ast_channel_writeformat(ast)));
			return -1;
		}
	}
	if (sub) {
		skinny_locksub(sub);
		if (sub->rtp) {
			res = ast_rtp_instance_write(sub->rtp, frame);
		}
		skinny_unlocksub(sub);
	}
	return res;
}

static int skinny_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
{
	struct skinny_subchannel *sub = ast_channel_tech_pvt(newchan);
	ast_log(LOG_NOTICE, "skinny_fixup(%s, %s)\n", ast_channel_name(oldchan), ast_channel_name(newchan));
	if (sub->owner != oldchan) {
		ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, sub->owner);
		return -1;
	}
	skinny_set_owner(sub, newchan);
	return 0;
}

static int skinny_senddigit_begin(struct ast_channel *ast, char digit)
{
	return -1; /* Start inband indications */
}

static int skinny_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
{
#if 0
	struct skinny_subchannel *sub = ast->tech_pvt;
	struct skinny_line *l = sub->line;
	struct skinny_device *d = l->device;
	int tmp;
	/* not right */
	sprintf(tmp, "%d", digit);
	//transmit_tone(d, digit, l->instance, sub->callid);
#endif
	return -1; /* Stop inband indications */
}

static int get_devicestate(struct skinny_line *l)
{
	struct skinny_subchannel *sub;
	int res = AST_DEVICE_UNKNOWN;

	if (!l)
		res = AST_DEVICE_INVALID;
	else if (!l->device || !l->device->session)
		res = AST_DEVICE_UNAVAILABLE;
	else if (l->dnd)
		res = AST_DEVICE_BUSY;
	else {
		if (l->device->hookstate == SKINNY_ONHOOK) {
			res = AST_DEVICE_NOT_INUSE;
		} else {
			res = AST_DEVICE_INUSE;
		}

		AST_LIST_TRAVERSE(&l->sub, sub, list) {
			if (sub->substate == SUBSTATE_HOLD) {
				res = AST_DEVICE_ONHOLD;
				break;
			}
		}
	}

	return res;
}

static char *control2str(int ind) {
	char *tmp;

	switch (ind) {
	case AST_CONTROL_HANGUP:
		return "Other end has hungup";
	case AST_CONTROL_RING:
		return "Local ring";
	case AST_CONTROL_RINGING:
		return "Remote end is ringing";
	case AST_CONTROL_ANSWER:
		return "Remote end has answered";
	case AST_CONTROL_BUSY:
		return "Remote end is busy";
	case AST_CONTROL_TAKEOFFHOOK:
		return "Make it go off hook";
	case AST_CONTROL_OFFHOOK:
		return "Line is off hook";
	case AST_CONTROL_CONGESTION:
		return "Congestion (circuits busy)";
	case AST_CONTROL_FLASH:
		return "Flash hook";
	case AST_CONTROL_WINK:
		return "Wink";
	case AST_CONTROL_OPTION:
		return "Set a low-level option";
	case AST_CONTROL_RADIO_KEY:
		return "Key Radio";
	case AST_CONTROL_RADIO_UNKEY:
		return "Un-Key Radio";
	case AST_CONTROL_PROGRESS:
		return "Remote end is making Progress";
	case AST_CONTROL_PROCEEDING:
		return "Remote end is proceeding";
	case AST_CONTROL_HOLD:
		return "Hold";
	case AST_CONTROL_UNHOLD:
		return "Unhold";
	case AST_CONTROL_VIDUPDATE:
		return "VidUpdate";
	case AST_CONTROL_SRCUPDATE:
		return "Media Source Update";
	case AST_CONTROL_TRANSFER:
		return "Transfer";
	case AST_CONTROL_CONNECTED_LINE:
		return "Connected Line";
	case AST_CONTROL_REDIRECTING:
		return "Redirecting";
	case AST_CONTROL_T38_PARAMETERS:
		return "T38_Parameters";
	case AST_CONTROL_CC:
		return "CC Not Possible";
	case AST_CONTROL_SRCCHANGE:
		return "Media Source Change";
	case AST_CONTROL_INCOMPLETE:
		return "Incomplete";
	case -1:
		return "Stop tone";
	default:
		if (!(tmp = ast_threadstorage_get(&control2str_threadbuf, CONTROL2STR_BUFSIZE)))
                        return "Unknown";
		snprintf(tmp, CONTROL2STR_BUFSIZE, "UNKNOWN-%d", ind);
		return tmp;
	}
}

static void skinny_transfer_attended(struct skinny_subchannel *sub)
{
	struct skinny_subchannel *xferee;
	struct skinny_subchannel *xferor;
	enum ast_transfer_result res;

	if (sub->xferor) {
		xferor = sub;
		xferee = sub->related;
	} else {
		xferor = sub;
		xferee = sub->related;
	}

	ast_queue_control(xferee->owner, AST_CONTROL_UNHOLD);
	if (ast_channel_state(xferor->owner) == AST_STATE_RINGING) {
		ast_queue_control(xferee->owner, AST_CONTROL_RINGING);
	}
	res = ast_bridge_transfer_attended(xferee->owner, xferor->owner);

	if (res != AST_BRIDGE_TRANSFER_SUCCESS) {
		SKINNY_DEBUG(DEBUG_SUB, 3, "Sub %u failed to transfer %u to '%s'@'%s' - %u\n",
			xferor->callid, xferee->callid, xferor->exten, xferor->line->context, res);
		send_displayprinotify(xferor->line->device, "Transfer failed", NULL, 10, 5);
		ast_queue_control(xferee->owner, AST_CONTROL_HOLD);
	}
}

static void skinny_transfer_blind(struct skinny_subchannel *sub)
{
	struct skinny_subchannel *xferee = sub->related;
	enum ast_transfer_result res;

	sub->related = NULL;
	xferee->related = NULL;

	ast_queue_control(xferee->owner, AST_CONTROL_UNHOLD);
	res = ast_bridge_transfer_blind(1, xferee->owner, sub->exten, sub->line->context, NULL, NULL);

	if (res != AST_BRIDGE_TRANSFER_SUCCESS) {
		SKINNY_DEBUG(DEBUG_SUB, 3, "Sub %u failed to blind transfer %u to '%s'@'%s' - %u\n",
			sub->callid, xferee->callid, sub->exten, sub->line->context, res);
		send_displayprinotify(sub->line->device, "Transfer failed", NULL, 10, 5);
		ast_queue_control(xferee->owner, AST_CONTROL_HOLD);
	}
	dumpsub(sub, 1);
}

static int skinny_indicate(struct ast_channel *ast, int ind, const void *data, size_t datalen)
{
	struct skinny_subchannel *sub = ast_channel_tech_pvt(ast);
	struct skinny_line *l = sub->line;
	struct skinny_device *d = l->device;
	struct skinnysession *s = d->session;

	if (!s) {
		ast_log(LOG_NOTICE, "Asked to indicate '%s' condition on channel %s, but session does not exist.\n", control2str(ind), ast_channel_name(ast));
		return -1;
	}

	SKINNY_DEBUG(DEBUG_SUB, 3, "Asked to indicate '%s' condition on channel %s (Sub %u)\n",
		control2str(ind), ast_channel_name(ast), sub->callid);
	switch(ind) {
	case AST_CONTROL_RINGING:
		setsubstate(sub, SUBSTATE_RINGOUT);
		return (d->earlyrtp ? -1 : 0); /* Tell asterisk to provide inband signalling if rtp started */
	case AST_CONTROL_BUSY:
		setsubstate(sub, SUBSTATE_BUSY);
		return (d->earlyrtp ? -1 : 0); /* Tell asterisk to provide inband signalling if rtp started */
	case AST_CONTROL_INCOMPLETE:
		/* Support for incomplete not supported for chan_skinny; treat as congestion */
	case AST_CONTROL_CONGESTION:
		setsubstate(sub, SUBSTATE_CONGESTION);
		return (d->earlyrtp ? -1 : 0); /* Tell asterisk to provide inband signalling if rtp started */
	case AST_CONTROL_PROGRESS:
		setsubstate(sub, SUBSTATE_PROGRESS);
		return (d->earlyrtp ? -1 : 0); /* Tell asterisk to provide inband signalling if rtp started */
	case -1:  /* STOP_TONE */
		transmit_stop_tone(d, l->instance, sub->callid);
		break;
	case AST_CONTROL_HOLD:
		ast_moh_start(ast, data, l->mohinterpret);
		break;
	case AST_CONTROL_UNHOLD:
		ast_moh_stop(ast);
		break;
	case AST_CONTROL_PROCEEDING:
		break;
	case AST_CONTROL_SRCUPDATE:
		if (sub->rtp) {
			ast_rtp_instance_update_source(sub->rtp);
		}
		break;
	case AST_CONTROL_SRCCHANGE:
		if (sub->rtp) {
			ast_rtp_instance_change_source(sub->rtp);
		}
		break;
	case AST_CONTROL_CONNECTED_LINE:
		update_connectedline(sub, data, datalen);
		break;
	default:
		ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", ind);
		/* fallthrough */
	case AST_CONTROL_PVT_CAUSE_CODE:
	case AST_CONTROL_MASQUERADE_NOTIFY:
		return -1; /* Tell asterisk to provide inband signalling */
	}
	return 0;
}

static void skinny_set_owner(struct skinny_subchannel* sub, struct ast_channel* chan)
{
	sub->owner = chan;
	if (sub->rtp) {
		ast_rtp_instance_set_channel_id(sub->rtp, sub->owner ? ast_channel_uniqueid(sub->owner) : "");
	}
	if (sub->vrtp) {
		ast_rtp_instance_set_channel_id(sub->vrtp, sub->owner ? ast_channel_uniqueid(sub->owner) : "");
	}
}

static struct ast_channel *skinny_new(struct skinny_line *l, struct skinny_subline *subline, int state, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, int direction)
{
	struct ast_channel *tmp;
	struct skinny_subchannel *sub;
	struct skinny_device *d = l->device;
	struct ast_variable *v = NULL;
	struct ast_format *tmpfmt;
	struct ast_format_cap *caps;
#ifdef AST_DEVMODE
	struct ast_str *codec_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
#endif

	if (!l->device || !l->device->session) {
		ast_log(LOG_WARNING, "Device for line %s is not registered.\n", l->name);
		return NULL;
	}

	caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
	if (!caps) {
		return NULL;
	}

	tmp = ast_channel_alloc(1, state, l->cid_num, l->cid_name, l->accountcode, l->exten, l->context, assignedids, requestor, l->amaflags, "Skinny/%s@%s-%d", l->name, d->name, callnums);
	if (!tmp) {
		ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
		ao2_ref(caps, -1);
		return NULL;
	} else {
		sub = ast_calloc(1, sizeof(*sub));
		if (!sub) {
			ast_log(LOG_WARNING, "Unable to allocate Skinny subchannel\n");
			ast_channel_unlock(tmp);
			ast_channel_unref(tmp);
			ao2_ref(caps, -1);
			return NULL;
		} else {
			skinny_set_owner(sub, tmp);
			sub->callid = callnums++;
			d->lastlineinstance = l->instance;
			d->lastcallreference = sub->callid;
			sub->cxmode = SKINNY_CX_INACTIVE;
			sub->nat = l->nat;
			sub->line = l;
			sub->blindxfer = 0;
			sub->xferor = 0;
			sub->related = NULL;
			sub->calldirection = direction;
			sub->aa_sched = -1;
			sub->dialer_sched = -1;
			sub->cfwd_sched = -1;
			sub->dialType = DIALTYPE_NORMAL;
			sub->getforward = 0;

			if (subline) {
				sub->subline = subline;
				subline->sub = sub;
			} else {
				sub->subline = NULL;
			}

			AST_LIST_INSERT_HEAD(&l->sub, sub, list);
			//l->activesub = sub;
		}
		ast_channel_stage_snapshot(tmp);
		ast_channel_tech_set(tmp, &skinny_tech);
		ast_channel_tech_pvt_set(tmp, sub);
		if (!ast_format_cap_count(l->cap)) {
			ast_format_cap_append_from_cap(caps, l->cap, AST_MEDIA_TYPE_UNKNOWN);
		} else {
			ast_format_cap_append_from_cap(caps, default_cap, AST_MEDIA_TYPE_UNKNOWN);
		}
		ast_channel_nativeformats_set(tmp, caps);
		ao2_ref(caps, -1);
		tmpfmt = ast_format_cap_get_format(ast_channel_nativeformats(tmp), 0);
		SKINNY_DEBUG(DEBUG_SUB, 3, "skinny_new: tmp->nativeformats=%s fmt=%s\n",
			ast_format_cap_get_names(ast_channel_nativeformats(tmp), &codec_buf),
			ast_format_get_name(tmpfmt));
		if (sub->rtp) {
			ast_channel_set_fd(tmp, 0, ast_rtp_instance_fd(sub->rtp, 0));
		}
		if (state == AST_STATE_RING) {
			ast_channel_rings_set(tmp, 1);
		}
		ast_channel_set_writeformat(tmp, tmpfmt);
		ast_channel_set_rawwriteformat(tmp, tmpfmt);
		ast_channel_set_readformat(tmp, tmpfmt);
		ast_channel_set_rawreadformat(tmp, tmpfmt);
		ao2_ref(tmpfmt, -1);

		if (!ast_strlen_zero(l->language))
			ast_channel_language_set(tmp, l->language);
		if (!ast_strlen_zero(l->accountcode))
			ast_channel_accountcode_set(tmp, l->accountcode);
		if (!ast_strlen_zero(l->parkinglot))
			ast_channel_parkinglot_set(tmp, l->parkinglot);
		if (l->amaflags)
			ast_channel_amaflags_set(tmp, l->amaflags);

		ast_module_ref(ast_module_info->self);
		ast_channel_callgroup_set(tmp, l->callgroup);
		ast_channel_pickupgroup_set(tmp, l->pickupgroup);

		ast_channel_named_callgroups_set(tmp, l->named_callgroups);
		ast_channel_named_pickupgroups_set(tmp, l->named_pickupgroups);

		if (l->cfwdtype & SKINNY_CFWD_ALL) {
			SKINNY_DEBUG(DEBUG_SUB, 3, "Sub %u - CFWDALL to %s.\n", sub->callid, l->call_forward_all);
			ast_channel_call_forward_set(tmp, l->call_forward_all);
		} else if ((l->cfwdtype & SKINNY_CFWD_BUSY) && (get_devicestate(l) != AST_DEVICE_NOT_INUSE)) {
			SKINNY_DEBUG(DEBUG_SUB, 3, "Sub %u - CFWDBUSY to %s.\n", sub->callid, l->call_forward_busy);
			ast_channel_call_forward_set(tmp, l->call_forward_busy);
		} else if (l->cfwdtype & SKINNY_CFWD_NOANSWER) {
			SKINNY_DEBUG(DEBUG_SUB, 3, "Sub %u - CFWDNOANS Scheduling for %d seconds.\n", sub->callid, l->callfwdtimeout/1000);
			sub->cfwd_sched = skinny_sched_add(l->callfwdtimeout, skinny_cfwd_cb, sub);
		}

		if (subline) {
			ast_channel_context_set(tmp, subline->context);
		} else {
			ast_channel_context_set(tmp, l->context);
		}
		ast_channel_exten_set(tmp, l->exten);

		/* Don't use ast_set_callerid() here because it will
		 * generate a needless NewCallerID event */
		if (!ast_strlen_zero(l->cid_num)) {
			ast_channel_caller(tmp)->ani.number.valid = 1;
			ast_channel_caller(tmp)->ani.number.str = ast_strdup(l->cid_num);
		}

		ast_channel_priority_set(tmp, 1);
		ast_channel_adsicpe_set(tmp, AST_ADSI_UNAVAILABLE);

		if (sub->rtp)
			ast_jb_configure(tmp, &global_jbconf);

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

		ast_channel_stage_snapshot_done(tmp);
		ast_channel_unlock(tmp);

		if (state != AST_STATE_DOWN) {
			if (ast_pbx_start(tmp)) {
				ast_log(LOG_WARNING, "Unable to start PBX on %s\n", ast_channel_name(tmp));
				ast_hangup(tmp);
				tmp = NULL;
			}
		}
	}
	return tmp;
}
static char *substate2str(int ind) {
	char *tmp;

	switch (ind) {
	case SUBSTATE_UNSET:
		return "SUBSTATE_UNSET";
	case SUBSTATE_OFFHOOK:
		return "SUBSTATE_OFFHOOK";
	case SUBSTATE_ONHOOK:
		return "SUBSTATE_ONHOOK";
	case SUBSTATE_RINGOUT:
		return "SUBSTATE_RINGOUT";
	case SUBSTATE_RINGIN:
		return "SUBSTATE_RINGIN";
	case SUBSTATE_CONNECTED:
		return "SUBSTATE_CONNECTED";
	case SUBSTATE_BUSY:
		return "SUBSTATE_BUSY";
	case SUBSTATE_CONGESTION:
		return "SUBSTATE_CONGESTION";
	case SUBSTATE_PROGRESS:
		return "SUBSTATE_PROGRESS";
	case SUBSTATE_HOLD:
		return "SUBSTATE_HOLD";
	case SUBSTATE_CALLWAIT:
		return "SUBSTATE_CALLWAIT";
	case SUBSTATE_DIALING:
		return "SUBSTATE_DIALING";
	default:
		if (!(tmp = ast_threadstorage_get(&substate2str_threadbuf, SUBSTATE2STR_BUFSIZE)))
                        return "Unknown";
		snprintf(tmp, SUBSTATE2STR_BUFSIZE, "UNKNOWN-%d", ind);
		return tmp;
	}
}

static void setsubstate(struct skinny_subchannel *sub, int state)
{
	struct skinny_line *l = sub->line;
	struct skinny_subline *subline = sub->subline;
	struct skinny_device *d = l->device;
	struct ast_channel *c = sub->owner;
	struct ast_party_id connected_id;
	pthread_t t;
	int actualstate = state;
	char *fromnum;

	if (sub->substate == SUBSTATE_ONHOOK) {
		return;
	}

	skinny_locksub(sub);

	if (-1 < sub->dialer_sched) {
		skinny_sched_del(sub->dialer_sched, sub);
		sub->dialer_sched = -1;
	}

	if (state != SUBSTATE_RINGIN && -1 < sub->aa_sched) {
		skinny_sched_del(sub->aa_sched, sub);
		sub->aa_sched = -1;
		sub->aa_beep = 0;
		sub->aa_mute = 0;
	}

	if (sub->cfwd_sched > -1) {
		if (state == SUBSTATE_CONNECTED) {
			if (skinny_sched_del(sub->cfwd_sched, sub)) {
				SKINNY_DEBUG(DEBUG_SUB, 3, "Sub %u - trying to change state from %s to %s, but already forwarded because no answer.\n",
					sub->callid, substate2str(sub->substate), substate2str(actualstate));
				skinny_unlocksub(sub);
				return;
			}
			sub->cfwd_sched = -1;
		} else if (state == SUBSTATE_ONHOOK) {
			skinny_sched_del(sub->cfwd_sched, sub);
			sub->cfwd_sched = -1;
		}
	}

	if ((state == SUBSTATE_RINGIN) && ((d->hookstate == SKINNY_OFFHOOK) || (AST_LIST_NEXT(AST_LIST_FIRST(&l->sub), list)))) {
		actualstate = SUBSTATE_CALLWAIT;
	}

	if (sub->substate == SUBSTATE_RINGIN && state != SUBSTATE_RINGIN) {
		transmit_clearprinotify(d, 5);
	}

	if ((state == SUBSTATE_CONNECTED) && (!subline) && (AST_LIST_FIRST(&l->sublines))) {
		const char *slastation;
		struct skinny_subline *tmpsubline;
		slastation = pbx_builtin_getvar_helper(c, "SLASTATION");
		ast_verb(3, "Connecting %s to subline\n", slastation);
		if (slastation) {
			AST_LIST_TRAVERSE(&l->sublines, tmpsubline, list) {
				if (!strcasecmp(tmpsubline->stname, slastation)) {
					subline = tmpsubline;
					break;
				}
			}
			if (subline) {
				struct skinny_line *tmpline;
				subline->sub = sub;
				sub->subline = subline;
				subline->callid = sub->callid;
				send_callinfo(sub);
				AST_LIST_TRAVERSE(&lines, tmpline, all) {
					AST_LIST_TRAVERSE(&tmpline->sublines, tmpsubline, list) {
						if (!(subline == tmpsubline)) {
							if (!strcasecmp(subline->lnname, tmpsubline->lnname)) {
								struct ast_state_cb_info info = {
									.exten_state = tmpsubline->extenstate,
								};
								tmpsubline->callid = callnums++;
								transmit_callstate(tmpsubline->line->device, tmpsubline->line->instance, tmpsubline->callid, SKINNY_OFFHOOK);
								push_callinfo(tmpsubline, sub);
								skinny_extensionstate_cb(NULL, NULL, &info, tmpsubline->container);
							}
						}
					}
				}
			}
		}
	}

	if (subline) { /* Different handling for subs under a subline, indications come through hints */
		switch (actualstate) {
		case SUBSTATE_ONHOOK:
			AST_LIST_REMOVE(&l->sub, sub, list);
			if (sub->related) {
				sub->related->related = NULL;
			}

			if (sub == l->activesub) {
				l->activesub = NULL;
				transmit_closereceivechannel(d, sub);
				transmit_stopmediatransmission(d, sub);
			}

			if (subline->callid) {
				transmit_stop_tone(d, l->instance, sub->callid);
				transmit_callstate(d, l->instance, subline->callid, SKINNY_CALLREMOTEMULTILINE);
				transmit_selectsoftkeys(d, l->instance, subline->callid, KEYDEF_SLACONNECTEDNOTACTIVE, KEYMASK_ALL);
				send_displaypromptstatus(d, "In Use", "", 0, l->instance, subline->callid);
			}

			sub->cxmode = SKINNY_CX_RECVONLY;
			sub->substate = SUBSTATE_ONHOOK;
			sub->substate = SUBSTATE_ONHOOK;
			if (sub->owner) {
				ast_queue_hangup(sub->owner);
			}
			break;
		case SUBSTATE_CONNECTED:
			transmit_activatecallplane(d, l);
			transmit_stop_tone(d, l->instance, sub->callid);
			transmit_selectsoftkeys(d, l->instance, subline->callid, KEYDEF_CONNECTED, KEYMASK_ALL);
			transmit_callstate(d, l->instance, subline->callid, SKINNY_CONNECTED);
			if (!sub->rtp) {
				start_rtp(sub);
			}
			if (sub->substate == SUBSTATE_RINGIN || sub->substate == SUBSTATE_CALLWAIT) {
				ast_queue_control(sub->owner, AST_CONTROL_ANSWER);
			}
			if (sub->substate == SUBSTATE_DIALING || sub->substate == SUBSTATE_RINGOUT) {
				transmit_dialednumber(d, sub->exten, l->instance, sub->callid);
			}
			if (ast_channel_state(sub->owner) != AST_STATE_UP) {
				ast_setstate(sub->owner, AST_STATE_UP);
			}
			sub->substate = SUBSTATE_CONNECTED;
			l->activesub = sub;
			break;
		case SUBSTATE_HOLD:
			if (sub->substate != SUBSTATE_CONNECTED) {
				ast_log(LOG_WARNING, "Cannot set substate to SUBSTATE_HOLD from %s (on call-%u)\n", substate2str(sub->substate), sub->callid);
				return;
			}
			transmit_activatecallplane(d, l);
			transmit_closereceivechannel(d, sub);
			transmit_stopmediatransmission(d, sub);

			transmit_callstate(d, l->instance, subline->callid, SKINNY_CALLREMOTEMULTILINE);
			transmit_selectsoftkeys(d, l->instance, subline->callid, KEYDEF_SLACONNECTEDNOTACTIVE, KEYMASK_ALL);
			send_displaypromptstatus(d, "In Use", "", 0, l->instance, subline->callid);

			sub->substate = SUBSTATE_HOLD;

			ast_queue_hold(sub->owner, l->mohsuggest);

			break;
		default:
			ast_log(LOG_WARNING, "Substate handling under subline for state %d not implemented on Sub-%u\n", state, sub->callid);
		}
		skinny_unlocksub(sub);
		return;
	}

	if ((d->hookstate == SKINNY_ONHOOK) && ((actualstate == SUBSTATE_OFFHOOK) || (actualstate == SUBSTATE_DIALING)
		|| (actualstate == SUBSTATE_RINGOUT) || (actualstate == SUBSTATE_CONNECTED) || (actualstate == SUBSTATE_BUSY)
		|| (actualstate == SUBSTATE_CONGESTION) || (actualstate == SUBSTATE_PROGRESS))) {
			d->hookstate = SKINNY_OFFHOOK;
			transmit_speaker_mode(d, SKINNY_SPEAKERON);
	}

	SKINNY_DEBUG(DEBUG_SUB, 3, "Sub %u - change state from %s to %s\n",
		sub->callid, substate2str(sub->substate), substate2str(actualstate));

	if (actualstate == sub->substate) {
		skinny_unlocksub(sub);
		return;
	}

	switch (actualstate) {
	case SUBSTATE_OFFHOOK:
		ast_verb(1, "Call-id: %u\n", sub->callid);
		l->activesub = sub;
		transmit_callstate(d, l->instance, sub->callid, SKINNY_OFFHOOK);
		transmit_activatecallplane(d, l);
		transmit_clear_display_message(d, l->instance, sub->callid);
		transmit_start_tone(d, SKINNY_DIALTONE, l->instance, sub->callid);
		transmit_selectsoftkeys(d, l->instance, sub->callid, KEYDEF_OFFHOOK, KEYMASK_ALL);
		send_displaypromptstatus(d, OCTAL_ENTRNUM, "", 0, l->instance, sub->callid);

		sub->substate = SUBSTATE_OFFHOOK;
		sub->dialer_sched = skinny_sched_add(firstdigittimeout, skinny_dialer_cb, sub);
		break;
	case SUBSTATE_ONHOOK:
		AST_LIST_REMOVE(&l->sub, sub, list);
		if (sub->related) {
			sub->related->related = NULL;
		}

		if ((sub->substate == SUBSTATE_RINGIN || sub->substate == SUBSTATE_CALLWAIT) && ast_channel_hangupcause(sub->owner) == AST_CAUSE_ANSWERED_ELSEWHERE) {
			transmit_callstate(d, l->instance, sub->callid, SKINNY_CONNECTED);
		}

		if (sub == l->activesub) {
			l->activesub = NULL;
			transmit_closereceivechannel(d, sub);
			transmit_stopmediatransmission(d, sub);
			transmit_stop_tone(d, l->instance, sub->callid);
			transmit_callstate(d, l->instance, sub->callid, SKINNY_ONHOOK);
			transmit_clearpromptmessage(d, l->instance, sub->callid);
			transmit_ringer_mode(d, SKINNY_RING_OFF);
			transmit_definetimedate(d);
			transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_OFF);
		} else {
			transmit_stop_tone(d, l->instance, sub->callid);
			transmit_callstate(d, l->instance, sub->callid, SKINNY_ONHOOK);
			transmit_clearpromptmessage(d, l->instance, sub->callid);
		}

		sub->cxmode = SKINNY_CX_RECVONLY;
		if (sub->owner) {
			if (sub->substate == SUBSTATE_OFFHOOK) {
				sub->substate = SUBSTATE_ONHOOK;
				skinny_unlocksub(sub);
				ast_hangup(sub->owner);
				return;
			} else {
				sub->substate = SUBSTATE_ONHOOK;
				ast_queue_hangup(sub->owner);
			}
		} else {
			sub->substate = SUBSTATE_ONHOOK;
		}
		break;
	case SUBSTATE_DIALING:
		if (ast_strlen_zero(sub->exten) || !ast_exists_extension(c, ast_channel_context(c), sub->exten, 1, l->cid_num)) {
			ast_log(LOG_WARNING, "Exten (%s)@(%s) does not exist, unable to set substate DIALING on sub %u\n", sub->exten, ast_channel_context(c), sub->callid);
			break;
		}

		if (d->hookstate == SKINNY_ONHOOK) {
			d->hookstate = SKINNY_OFFHOOK;
			transmit_speaker_mode(d, SKINNY_SPEAKERON);
			transmit_activatecallplane(d, l);
		}

		if (!sub->subline) {
			transmit_callstate(d, l->instance, sub->callid, SKINNY_OFFHOOK);
			transmit_stop_tone(d, l->instance, sub->callid);
			transmit_clear_display_message(d, l->instance, sub->callid);
			transmit_selectsoftkeys(d, l->instance, sub->callid, KEYDEF_RINGOUT, KEYMASK_ALL);
			send_displaypromptstatus(d, "Dialing", "", 0, l->instance, sub->callid);
		}

		if  (AST_LIST_FIRST(&l->sublines)) {
			if (subline) {
				ast_channel_exten_set(c, subline->exten);
				ast_channel_context_set(c, "sla_stations");
			} else {
				pbx_builtin_setvar_helper(c, "_DESTEXTEN", sub->exten);
				pbx_builtin_setvar_helper(c, "_DESTCONTEXT", ast_channel_context(c));
				ast_channel_exten_set(c, l->dialoutexten);
				ast_channel_context_set(c, l->dialoutcontext);
				ast_copy_string(l->lastnumberdialed, sub->exten, sizeof(l->lastnumberdialed));
			}
		} else {
			ast_channel_exten_set(c, sub->exten);
			ast_copy_string(l->lastnumberdialed, sub->exten, sizeof(l->lastnumberdialed));
		}

		sub->substate = SUBSTATE_DIALING;

		if (ast_pthread_create(&t, NULL, skinny_newcall, c)) {
			ast_log(LOG_WARNING, "Unable to create new call thread: %s\n", strerror(errno));
			ast_hangup(c);
		}
		break;
	case SUBSTATE_RINGOUT:
		if (!(sub->substate == SUBSTATE_DIALING || sub->substate == SUBSTATE_PROGRESS)) {
			ast_log(LOG_WARNING, "Cannot set substate to SUBSTATE_RINGOUT from %s (on call-%u)\n", substate2str(sub->substate), sub->callid);
			break;
		}
		if (sub->substate != SUBSTATE_PROGRESS) {
			transmit_callstate(d, l->instance, sub->callid, SKINNY_PROGRESS);
		}

		if (!d->earlyrtp) {
			transmit_start_tone(d, SKINNY_ALERT, l->instance, sub->callid);
		}
		transmit_callstate(d, l->instance, sub->callid, SKINNY_RINGOUT);
		if (sub->related) {
			transmit_selectsoftkeys(d, l->instance, sub->callid, KEYDEF_RINGOUTWITHTRANS, KEYMASK_ALL);
		} else {
			transmit_selectsoftkeys(d, l->instance, sub->callid, KEYDEF_RINGOUT, KEYMASK_ALL);
		}
		transmit_dialednumber(d, sub->exten, l->instance, sub->callid);
		send_displaypromptstatus(d, OCTAL_RINGOUT, "", 0, l->instance, sub->callid);
		send_callinfo(sub);
		sub->substate = SUBSTATE_RINGOUT;
		break;
	case SUBSTATE_RINGIN:
		connected_id = ast_channel_connected_effective_id(c);
		if ((ast_party_id_presentation(&connected_id) & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED) {
			fromnum = S_COR(connected_id.number.valid, connected_id.number.str, "Unknown");
		} else {
			fromnum = "Unknown";
		}
		transmit_callstate(d, l->instance, sub->callid, SKINNY_RINGIN);
		transmit_selectsoftkeys(d, l->instance, sub->callid, KEYDEF_RINGIN, KEYMASK_ALL);
		send_displaypromptstatus(d, OCTAL_FROM, fromnum, 0, l->instance, sub->callid);
		send_displayprinotify(d, OCTAL_FROM, fromnum, 10, 5);
		send_callinfo(sub);
		transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_BLINK);
		transmit_ringer_mode(d, SKINNY_RING_INSIDE);
		transmit_activatecallplane(d, l);

		if (d->hookstate == SKINNY_ONHOOK) {
			l->activesub = sub;
		}

		if (sub->substate != SUBSTATE_RINGIN || sub->substate != SUBSTATE_CALLWAIT) {
			ast_setstate(c, AST_STATE_RINGING);
			ast_queue_control(c, AST_CONTROL_RINGING);
		}
		sub->substate = SUBSTATE_RINGIN;
		break;
	case SUBSTATE_CALLWAIT:
		transmit_callstate(d, l->instance, sub->callid, SKINNY_RINGIN);
		transmit_callstate(d, l->instance, sub->callid, SKINNY_CALLWAIT);
		transmit_selectsoftkeys(d, l->instance, sub->callid, KEYDEF_RINGIN, KEYMASK_ALL);
		send_displaypromptstatus(d, OCTAL_CALLWAITING, "", 0, l->instance, sub->callid);
		send_callinfo(sub);
		transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_BLINK);
		transmit_start_tone(d, SKINNY_CALLWAITTONE, l->instance, sub->callid);

		ast_setstate(c, AST_STATE_RINGING);
		ast_queue_control(c, AST_CONTROL_RINGING);
		sub->substate = SUBSTATE_CALLWAIT;
		break;
	case SUBSTATE_CONNECTED:
		if (sub->substate == SUBSTATE_RINGIN) {
			transmit_callstate(d, l->instance, sub->callid, SKINNY_OFFHOOK);
		}
		if (sub->substate == SUBSTATE_HOLD) {
			ast_queue_unhold(sub->owner);
			transmit_connect(d, sub);
		}
		transmit_ringer_mode(d, SKINNY_RING_OFF);
		transmit_activatecallplane(d, l);
		transmit_stop_tone(d, l->instance, sub->callid);
		send_callinfo(sub);
		transmit_callstate(d, l->instance, sub->callid, SKINNY_CONNECTED);
		send_displaypromptstatus(d, OCTAL_CONNECTED, "", 0, l->instance, sub->callid);
		transmit_selectsoftkeys(d, l->instance, sub->callid, KEYDEF_CONNECTED, KEYMASK_ALL);
		if (!sub->rtp) {
			start_rtp(sub);
		}
		if (sub->aa_beep) {
			transmit_start_tone(d, SKINNY_ZIP, l->instance, sub->callid);
		}
		if (sub->aa_mute) {
			transmit_microphone_mode(d, SKINNY_MICOFF);
		}
		if (sub->substate == SUBSTATE_RINGIN || sub->substate == SUBSTATE_CALLWAIT) {
			ast_queue_control(sub->owner, AST_CONTROL_ANSWER);
		}
		if (sub->substate == SUBSTATE_DIALING || sub->substate == SUBSTATE_RINGOUT) {
			transmit_dialednumber(d, sub->exten, l->instance, sub->callid);
		}
		if (ast_channel_state(sub->owner) != AST_STATE_UP) {
			ast_setstate(sub->owner, AST_STATE_UP);
		}
		sub->substate = SUBSTATE_CONNECTED;
		l->activesub = sub;
		break;
	case SUBSTATE_BUSY:
		if (!(sub->substate == SUBSTATE_DIALING || sub->substate == SUBSTATE_PROGRESS || sub->substate == SUBSTATE_RINGOUT)) {
			ast_log(LOG_WARNING, "Cannot set substate to SUBSTATE_BUSY from %s (on call-%u)\n", substate2str(sub->substate), sub->callid);
			break;
		}

		if (!d->earlyrtp) {
			transmit_start_tone(d, SKINNY_BUSYTONE, l->instance, sub->callid);
		}
		send_callinfo(sub);
		transmit_callstate(d, l->instance, sub->callid, SKINNY_BUSY);
		send_displaypromptstatus(d, OCTAL_BUSY, "", 0, l->instance, sub->callid);
		sub->substate = SUBSTATE_BUSY;
		break;
	case SUBSTATE_CONGESTION:
		if (!(sub->substate == SUBSTATE_DIALING || sub->substate == SUBSTATE_PROGRESS || sub->substate == SUBSTATE_RINGOUT)) {
			ast_log(LOG_WARNING, "Cannot set substate to SUBSTATE_CONGESTION from %s (on call-%u)\n", substate2str(sub->substate), sub->callid);
			break;
		}

		if (!d->earlyrtp) {
			transmit_start_tone(d, SKINNY_REORDER, l->instance, sub->callid);
		}
		send_callinfo(sub);
		transmit_callstate(d, l->instance, sub->callid, SKINNY_CONGESTION);
		send_displaypromptstatus(d, "Congestion", "", 0, l->instance, sub->callid);
		sub->substate = SUBSTATE_CONGESTION;
		break;
	case SUBSTATE_PROGRESS:
		if (sub->substate != SUBSTATE_DIALING) {
			ast_log(LOG_WARNING, "Cannot set substate to SUBSTATE_PROGRESS from %s (on call-%u)\n", substate2str(sub->substate), sub->callid);
			break;
		}

		if (!d->earlyrtp) {
			transmit_start_tone(d, SKINNY_ALERT, l->instance, sub->callid);
		}
		send_callinfo(sub);
		transmit_callstate(d, l->instance, sub->callid, SKINNY_PROGRESS);
		send_displaypromptstatus(d, "Call Progress", "", 0, l->instance, sub->callid);
		sub->substate = SUBSTATE_PROGRESS;
		break;
	case SUBSTATE_HOLD:
		if (sub->substate != SUBSTATE_CONNECTED) {
			ast_log(LOG_WARNING, "Cannot set substate to SUBSTATE_HOLD from %s (on call-%u)\n", substate2str(sub->substate), sub->callid);
			break;
		}
		ast_queue_hold(sub->owner, l->mohsuggest);

		transmit_activatecallplane(d, l);
		transmit_closereceivechannel(d, sub);
		transmit_stopmediatransmission(d, sub);

		transmit_callstate(d, l->instance, sub->callid, SKINNY_HOLD);
		transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_WINK);
		transmit_selectsoftkeys(d, l->instance, sub->callid, KEYDEF_ONHOLD, KEYMASK_ALL);
		sub->substate = SUBSTATE_HOLD;
		break;
	default:
		ast_log(LOG_WARNING, "Was asked to change to nonexistant substate %d on Sub-%u\n", state, sub->callid);
	}
	skinny_unlocksub(sub);
}

static void dumpsub(struct skinny_subchannel *sub, int forcehangup)
{
	struct skinny_line *l = sub->line;
	struct skinny_device *d = l->device;
	struct skinny_subchannel *activate_sub = NULL;
	struct skinny_subchannel *tsub;

	SKINNY_DEBUG(DEBUG_SUB, 3, "Sub %u - Dumping\n", sub->callid);

	if (!forcehangup && sub->substate == SUBSTATE_HOLD) {
		l->activesub = NULL;
		return;
	}

	if (sub == l->activesub) {
		d->hookstate = SKINNY_ONHOOK;
		transmit_speaker_mode(d, SKINNY_SPEAKEROFF);
		if (sub->related) {
			activate_sub = sub->related;
			setsubstate(sub, SUBSTATE_ONHOOK);
			l->activesub = activate_sub;
			if (l->activesub->substate != SUBSTATE_HOLD) {
				ast_log(LOG_WARNING, "Sub-%u was related but not at SUBSTATE_HOLD\n", sub->callid);
				return;
			}
			setsubstate(l->activesub, SUBSTATE_HOLD);
		} else {
			setsubstate(sub, SUBSTATE_ONHOOK);
			AST_LIST_TRAVERSE(&l->sub, tsub, list) {
				if (tsub->substate == SUBSTATE_CALLWAIT) {
					activate_sub = tsub;
				}
			}
			if (activate_sub) {
				setsubstate(activate_sub, SUBSTATE_RINGIN);
				return;
			}
			AST_LIST_TRAVERSE(&l->sub, tsub, list) {
				if (tsub->substate == SUBSTATE_HOLD) {
					activate_sub = tsub;
				}
			}
			if (activate_sub) {
				setsubstate(activate_sub, SUBSTATE_HOLD);
				return;
			}
		}
	} else {
		setsubstate(sub, SUBSTATE_ONHOOK);
	}
}

static void activatesub(struct skinny_subchannel *sub, int state)
{
	struct skinny_line *l = sub->line;

	SKINNY_DEBUG(DEBUG_SUB, 3, "Sub %u - Activating, and deactivating sub %u\n",
		sub->callid, l->activesub ? l->activesub->callid : 0);

	if (sub == l->activesub) {
		setsubstate(sub, state);
	} else {
		if (l->activesub) {
			if (l->activesub->substate == SUBSTATE_RINGIN) {
				setsubstate(l->activesub, SUBSTATE_CALLWAIT);
			} else if (l->activesub->substate != SUBSTATE_HOLD) {
				setsubstate(l->activesub, SUBSTATE_ONHOOK);
			}
		}
		l->activesub = sub;
		setsubstate(sub, state);
	}
}

static void dialandactivatesub(struct skinny_subchannel *sub, char exten[AST_MAX_EXTENSION])
{
	struct skinny_line *l = sub->line;
	struct skinny_device *d = l->device;

	if (sub->dialType == DIALTYPE_NORMAL) {
		SKINNY_DEBUG(DEBUG_SUB, 3, "Sub %u - Dial %s and Activate\n", sub->callid, exten);
		ast_copy_string(sub->exten, exten, sizeof(sub->exten));
		activatesub(sub, SUBSTATE_DIALING);
	} else if (sub->dialType == DIALTYPE_CFWD) {
		SKINNY_DEBUG(DEBUG_SUB, 3, "Sub %u - Set callforward(%d) to %s\n", sub->callid, sub->getforward, exten);
		set_callforwards(l, sub->exten, sub->getforward);
		dumpsub(sub, 1);
		transmit_cfwdstate(d, l);
		transmit_displaynotify(d, "CFwd enabled", 10);
	} else if (sub->dialType == DIALTYPE_XFER) {
		ast_copy_string(sub->exten, exten, sizeof(sub->exten));
		skinny_transfer_blind(sub);
	}
}

static int handle_hold_button(struct skinny_subchannel *sub)
{
	if (!sub)
		return -1;
	if (sub->related) {
		setsubstate(sub, SUBSTATE_HOLD);
		activatesub(sub->related, SUBSTATE_CONNECTED);
	} else {
		if (sub->substate == SUBSTATE_HOLD) {
			activatesub(sub, SUBSTATE_CONNECTED);
		} else {
			setsubstate(sub, SUBSTATE_HOLD);
		}
	}
	return 1;
}

static int handle_transfer_button(struct skinny_subchannel *sub)
{
	struct skinny_line *l;
	struct skinny_device *d;
	struct skinny_subchannel *newsub;
	struct ast_channel *c;

	if (!sub) {
		ast_verbose("Transfer: No subchannel to transfer\n");
		return -1;
	}

	l = sub->line;
	d = l->device;

	if (!d->session) {
		ast_log(LOG_WARNING, "Device for line %s is not registered.\n", l->name);
		return -1;
	}

	if (!sub->related) {
		/* Another sub has not been created so this must be first XFER press */
		if (!(sub->substate == SUBSTATE_HOLD)) {
			setsubstate(sub, SUBSTATE_HOLD);
		}
		c = skinny_new(l, NULL, AST_STATE_DOWN, NULL, NULL, SKINNY_OUTGOING);
		if (c) {
			newsub = ast_channel_tech_pvt(c);
			/* point the sub and newsub at each other so we know they are related */
			newsub->related = sub;
			sub->related = newsub;
			newsub->xferor = 1;
			setsubstate(newsub, SUBSTATE_OFFHOOK);
		} else {
			ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", l->name, d->name);
		}
	} else {
		/* We already have a related sub so we can either complete XFER or go into BLINDXFER (or cancel BLINDXFER */
		if (sub->substate == SUBSTATE_OFFHOOK) {
			if (sub->dialType == DIALTYPE_XFER) {
				sub->dialType = DIALTYPE_NORMAL;
			} else {
				sub->dialType = DIALTYPE_XFER;
			}
		} else {
			skinny_transfer_attended(sub);
		}
	}
	return 0;
}

static void handle_callforward_button(struct skinny_line *l, struct skinny_subchannel *sub, int cfwdtype)
{
	struct skinny_device *d = l->device;
	struct ast_channel *c;

	if (!d->session) {
		ast_log(LOG_WARNING, "Device for line %s is not registered.\n", l->name);
		return;
	}

	if (!sub && (l->cfwdtype & cfwdtype)) {
		set_callforwards(l, NULL, cfwdtype);
		if (sub) {
			dumpsub(sub, 1);
		}
		transmit_cfwdstate(d, l);
		transmit_displaynotify(d, "CFwd disabled", 10);
	} else {
		if (!sub || !sub->owner) {
			if (!(c = skinny_new(l, NULL, AST_STATE_DOWN, NULL, NULL, SKINNY_OUTGOING))) {
				ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", l->name, d->name);
				return;
			}
			sub = ast_channel_tech_pvt(c);
			l->activesub = sub;
			setsubstate(sub, SUBSTATE_OFFHOOK);
		}
		sub->getforward |= cfwdtype;
		sub->dialType = DIALTYPE_CFWD;
	}
}

static int handle_ip_port_message(struct skinny_req *req, struct skinnysession *s)
{
	/* no response necessary */
	return 1;
}

static void handle_keepalive_message(struct skinny_req *req, struct skinnysession *s)
{
	not_used = ast_sched_del(sched, s->keepalive_timeout_sched);

#ifdef AST_DEVMODE
	{
		long keepalive_diff;
		keepalive_diff = (long) ast_tvdiff_ms(ast_tvnow(), ast_tvadd(s->last_keepalive, ast_tv(keep_alive, 0)));
		SKINNY_DEBUG(DEBUG_PACKET|DEBUG_KEEPALIVE, 3,
			"Keep_alive %d on %s, %.3fs %s\n",
				++s->keepalive_count,
				(s->device ? s->device->name : "unregistered"),
				(float) labs(keepalive_diff) / 1000,
				(keepalive_diff > 0 ? "late" : "early"));
	}
#endif

	s->keepalive_timeout_sched = ast_sched_add(sched, keep_alive*3000, skinny_nokeepalive_cb, s);
	s->last_keepalive = ast_tvnow();
	transmit_keepaliveack(s);
}

static int handle_keypad_button_message(struct skinny_req *req, struct skinnysession *s)
{
	struct skinny_subchannel *sub = NULL;
	struct skinny_line *l;
	struct skinny_device *d = s->device;
	struct ast_frame f = { 0, };
	char dgt;
	int digit;
	int lineInstance;
	int callReference;
	size_t len;

	digit = letohl(req->data.keypad.button);
	lineInstance = letohl(req->data.keypad.lineInstance);
	callReference = letohl(req->data.keypad.callReference);

	if (lineInstance && callReference) {
		sub = find_subchannel_by_instance_reference(d, lineInstance, callReference);
	} else {
		sub = d->activeline->activesub;
	}

	if (!sub)
		return 0;

	l = sub->line;

	if (digit == 14) {
		dgt = '*';
	} else if (digit == 15) {
		dgt = '#';
	} else if (digit >= 0 && digit <= 9) {
		dgt = '0' + digit;
	} else {
		/* digit=10-13 (A,B,C,D ?), or
		 * digit is bad value
		 *
		 * probably should not end up here, but set
		 * value for backward compatibility, and log
		 * a warning.
		 */
		dgt = '0' + digit;
		ast_log(LOG_WARNING, "Unsupported digit %d\n", digit);
	}

	if ((sub->owner && ast_channel_state(sub->owner) <  AST_STATE_UP)) {
		if (-1 < sub->dialer_sched && !skinny_sched_del(sub->dialer_sched, sub)) {
			SKINNY_DEBUG(DEBUG_SUB, 3, "Sub %u - Got a digit and not timed out, so try dialing\n", sub->callid);
			sub->dialer_sched = -1;
			len = strlen(sub->exten);
			if (len == 0) {
				transmit_stop_tone(d, l->instance, sub->callid);
				transmit_selectsoftkeys(d, l->instance, sub->callid, KEYDEF_DADFD, KEYMASK_ALL&~KEYMASK_FORCEDIAL);
			}
			if (len < sizeof(sub->exten) - 1 && dgt != immed_dialchar) {
				sub->exten[len] = dgt;
				sub->exten[len + 1] = '\0';
			}
			if (len == sizeof(sub->exten) - 1 || dgt == immed_dialchar) {
				skinny_dialer(sub, 1);
			} else {
				skinny_dialer(sub, 0);
			}
		} else {
			SKINNY_DEBUG(DEBUG_SUB, 3, "Sub %u  Got a digit already timedout, ignore\n", sub->callid);
			/* Timed out so the call is being progressed elsewhere, to late for digits */
			return 0;
		}
	} else {
		SKINNY_DEBUG(DEBUG_SUB, 3, "Sub %u - Got a digit and sending as DTMF\n", sub->callid);
		f.subclass.integer = dgt;
		f.src = "skinny";
		if (sub->owner) {
			if (ast_channel_state(sub->owner) == 0) {
				f.frametype = AST_FRAME_DTMF_BEGIN;
				ast_queue_frame(sub->owner, &f);
			}
			/* XXX MUST queue this frame to all lines in threeway call if threeway call is active */
			f.frametype = AST_FRAME_DTMF_END;
			ast_queue_frame(sub->owner, &f);
			/* XXX This seriously needs to be fixed */
			if (AST_LIST_NEXT(sub, list) && AST_LIST_NEXT(sub, list)->owner) {
				if (ast_channel_state(sub->owner) == 0) {
					f.frametype = AST_FRAME_DTMF_BEGIN;
					ast_queue_frame(AST_LIST_NEXT(sub, list)->owner, &f);
				}
				f.frametype = AST_FRAME_DTMF_END;
				ast_queue_frame(AST_LIST_NEXT(sub, list)->owner, &f);
			}
		} else {
			ast_log(LOG_WARNING, "Got digit on %s, but not associated with channel\n", l->name);
		}
	}
	return 1;
}

static int handle_stimulus_message(struct skinny_req *req, struct skinnysession *s)
{
	struct skinny_device *d = s->device;
	struct skinny_line *l;
	struct skinny_subchannel *sub;
	/*struct skinny_speeddial *sd;*/
	struct ast_channel *c;
	int event;
	int instance;
#ifdef AST_DEVMODE
	int callreference;
	/* This is only used in AST_DEVMODE, as an argument to SKINNY_DEBUG */
	callreference = letohl(req->data.stimulus.callreference);
#endif

	event = letohl(req->data.stimulus.stimulus);
	instance = letohl(req->data.stimulus.stimulusInstance);

	/*  Note that this call should be using the passed in instance and callreference */
	sub = find_subchannel_by_instance_reference(d, d->lastlineinstance, d->lastcallreference);

	if (!sub) {
		l = find_line_by_instance(d, d->lastlineinstance);
		if (!l) {
			return 0;
		}
		sub = l->activesub;
	} else {
		l = sub->line;
	}

	switch(event) {
	case STIMULUS_REDIAL:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received STIMULUS_REDIAL from %s, inst %d, callref %d\n",
			d->name, instance, callreference);

		if (ast_strlen_zero(l->lastnumberdialed)) {
			ast_log(LOG_WARNING, "Attempted redial, but no previously dialed number found. Ignoring button.\n");
			break;
		}

		c = skinny_new(l, NULL, AST_STATE_DOWN, NULL, NULL, SKINNY_OUTGOING);
		if (!c) {
			ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", l->name, d->name);
		} else {
			sub = ast_channel_tech_pvt(c);
			l = sub->line;
			dialandactivatesub(sub, l->lastnumberdialed);
		}
		break;
	case STIMULUS_SPEEDDIAL:
	    {
		struct skinny_speeddial *sd;

		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received STIMULUS_SPEEDDIAL from %s, inst %d, callref %d\n",
			d->name, instance, callreference);

		if (!(sd = find_speeddial_by_instance(d, instance, 0))) {
			return 0;
		}

		if (!sub || !sub->owner)
			c = skinny_new(l, NULL, AST_STATE_DOWN, NULL, NULL, SKINNY_OUTGOING);
		else
			c = sub->owner;

		if (!c) {
			ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", l->name, d->name);
		} else {
			sub = ast_channel_tech_pvt(c);
			dialandactivatesub(sub, sd->exten);
		}
	    }
		break;
	case STIMULUS_HOLD:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received STIMULUS_HOLD from %s, inst %d, callref %d\n",
			d->name, instance, callreference);
		handle_hold_button(sub);
		break;
	case STIMULUS_TRANSFER:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received STIMULUS_TRANSFER from %s, inst %d, callref %d\n",
			d->name, instance, callreference);
		if (l->transfer)
			handle_transfer_button(sub);
		else
			transmit_displaynotify(d, "Transfer disabled", 10);
		break;
	case STIMULUS_CONFERENCE:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received STIMULUS_CONFERENCE from %s, inst %d, callref %d\n",
			d->name, instance, callreference);
		/* XXX determine the best way to pull off a conference.  Meetme? */
		break;
	case STIMULUS_VOICEMAIL:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received STIMULUS_VOICEMAIL from %s, inst %d, callref %d\n",
			d->name, instance, callreference);

		if (!sub || !sub->owner) {
			c = skinny_new(l, NULL, AST_STATE_DOWN, NULL, NULL, SKINNY_OUTGOING);
		} else {
			c = sub->owner;
		}

		if (!c) {
			ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", l->name, d->name);
			break;
		}

		sub = ast_channel_tech_pvt(c);
		if (sub->substate == SUBSTATE_UNSET || sub->substate == SUBSTATE_OFFHOOK){
			dialandactivatesub(sub, l->vmexten);
		}
		break;
	case STIMULUS_CALLPARK:
		{
		char extout[AST_MAX_EXTENSION];
		char message[32];
		RAII_VAR(struct ast_bridge_channel *, bridge_channel, NULL, ao2_cleanup);
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received STIMULUS_CALLPARK from %s, inst %d, callref %d\n",
			d->name, instance, callreference);

		if (!ast_parking_provider_registered()) {
			transmit_displaynotify(d, "Call Park not available", 10);
			break;
		}

		if ((sub && sub->owner) && (ast_channel_state(sub->owner) ==  AST_STATE_UP)) {
			c = sub->owner;
			ast_channel_lock(c);
			bridge_channel = ast_channel_get_bridge_channel(c);
			ast_channel_unlock(c);

			if (!bridge_channel) {
				transmit_displaynotify(d, "Call Park failed", 10);
				break;
			}

			if (!ast_parking_park_call(bridge_channel, extout, sizeof(extout))) {
				snprintf(message, sizeof(message), "Call Parked at: %s", extout);
				transmit_displaynotify(d, message, 10);
				break;
			}
			transmit_displaynotify(d, "Call Park failed", 10);
		} else {
			transmit_displaynotify(d, "Call Park not available", 10);
		}
		break;
		}
	case STIMULUS_DND:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received STIMULUS_DND from %s, inst %d, callref %d\n",
			d->name, instance, callreference);

		/* Do not disturb */
		if (l->dnd != 0){
			ast_verb(3, "Disabling DND on %s@%s\n", l->name, d->name);
			l->dnd = 0;
			transmit_lamp_indication(d, STIMULUS_DND, 1, SKINNY_LAMP_ON);
			transmit_displaynotify(d, "DnD disabled", 10);
		} else {
			ast_verb(3, "Enabling DND on %s@%s\n", l->name, d->name);
			l->dnd = 1;
			transmit_lamp_indication(d, STIMULUS_DND, 1, SKINNY_LAMP_OFF);
			transmit_displaynotify(d, "DnD enabled", 10);
		}
		break;
	case STIMULUS_FORWARDALL:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received STIMULUS_FORWARDALL from %s, inst %d, callref %d\n",
			d->name, instance, callreference);
		handle_callforward_button(l, sub, SKINNY_CFWD_ALL);
		break;
	case STIMULUS_FORWARDBUSY:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received STIMULUS_FORWARDBUSY from %s, inst %d, callref %d\n",
			d->name, instance, callreference);
		handle_callforward_button(l, sub, SKINNY_CFWD_BUSY);
		break;
	case STIMULUS_FORWARDNOANSWER:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received STIMULUS_FORWARDNOANSWER from %s, inst %d, callref %d\n",
			d->name, instance, callreference);
		handle_callforward_button(l, sub, SKINNY_CFWD_NOANSWER);
		break;
	case STIMULUS_DISPLAY:
		/* Not sure what this is */
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received STIMULUS_DISPLAY from %s, inst %d, callref %d\n",
			d->name, instance, callreference);
		break;
	case STIMULUS_LINE:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received STIMULUS_LINE from %s, inst %d, callref %d\n",
			d->name, instance, callreference);

		l = find_line_by_instance(d, instance);

		if (!l) {
			return 0;
		}

		d->activeline = l;

		/* turn the speaker on */
		transmit_speaker_mode(d, SKINNY_SPEAKERON);
		transmit_ringer_mode(d, SKINNY_RING_OFF);
		transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_ON);

		d->hookstate = SKINNY_OFFHOOK;

		if (sub && sub->calldirection == SKINNY_INCOMING) {
			setsubstate(sub, SUBSTATE_CONNECTED);
		} else {
			if (sub && sub->owner) {
				ast_debug(1, "Current subchannel [%s] already has owner\n", ast_channel_name(sub->owner));
			} else {
				c = skinny_new(l, NULL, AST_STATE_DOWN, NULL, NULL, SKINNY_OUTGOING);
				if (c) {
					setsubstate(ast_channel_tech_pvt(c), SUBSTATE_OFFHOOK);
				} else {
					ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", l->name, d->name);
				}
			}
		}
		break;
	default:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received UNKNOWN_STIMULUS(%d) from %s, inst %d, callref %d\n",
			event, d->name, instance, callreference);
		break;
	}
	ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "Skinny/%s", l->name);

	return 1;
}

static int handle_offhook_message(struct skinny_req *req, struct skinnysession *s)
{
	struct skinny_device *d = s->device;
	struct skinny_line *l = NULL;
	struct skinny_subchannel *sub = NULL;
	struct ast_channel *c;
	int instance;
	int reference;

	instance = letohl(req->data.offhook.instance);
	reference = letohl(req->data.offhook.reference);

	if (d->hookstate == SKINNY_OFFHOOK) {
		ast_verb(3, "Got offhook message when device (%s) already offhook\n", d->name);
		return 0;
	}

	if (reference) {
		sub = find_subchannel_by_instance_reference(d, instance, reference);
		if (sub) {
			l = sub->line;
		}
	}
	if (!sub) {
		if (instance) {
			l = find_line_by_instance(d, instance);
		} else {
			l = d->activeline;
		}
		sub = l->activesub;
	}

	transmit_ringer_mode(d, SKINNY_RING_OFF);
	d->hookstate = SKINNY_OFFHOOK;

	ast_devstate_changed(AST_DEVICE_INUSE, AST_DEVSTATE_CACHABLE, "Skinny/%s", l->name);

	if (sub && sub->substate == SUBSTATE_HOLD) {
		return 1;
	}

	transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_ON);

	if (sub && sub->calldirection == SKINNY_INCOMING) {
		setsubstate(sub, SUBSTATE_CONNECTED);
	} else {
		/* Not ideal, but let's send updated time at onhook and offhook, as it clears the display */
		transmit_definetimedate(d);

		if (sub && sub->owner) {
			ast_debug(1, "Current sub [%s] already has owner\n", ast_channel_name(sub->owner));
		} else {
			c = skinny_new(l, NULL, AST_STATE_DOWN, NULL, NULL, SKINNY_OUTGOING);
			if (c) {
				setsubstate(ast_channel_tech_pvt(c), SUBSTATE_OFFHOOK);
			} else {
				ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", l->name, d->name);
			}
		}
	}
	return 1;
}

static int handle_onhook_message(struct skinny_req *req, struct skinnysession *s)
{
	struct skinny_device *d = s->device;
	struct skinny_line *l;
	struct skinny_subchannel *sub;
	int instance;
	int reference;

	instance = letohl(req->data.onhook.instance);
	reference = letohl(req->data.onhook.reference);

	if (instance && reference) {
		sub = find_subchannel_by_instance_reference(d, instance, reference);
		if (!sub) {
			return 0;
		}
		l = sub->line;
	} else {
		l = d->activeline;
		sub = l->activesub;
		if (!sub) {
			return 0;
		}
	}

	if (d->hookstate == SKINNY_ONHOOK) {
		/* Something else already put us back on hook */
		/* Not ideal, but let's send updated time anyway, as it clears the display */
		transmit_definetimedate(d);
		return 0;
	}

	if (l->transfer && sub->xferor && ast_channel_state(sub->owner) >= AST_STATE_RING) {
		/* We're allowed to transfer, we have two active calls and
		   we made at least one of the calls.  Let's try and transfer */
		handle_transfer_button(sub);
		return 0;
	}

	ast_devstate_changed(AST_DEVICE_NOT_INUSE, AST_DEVSTATE_CACHABLE, "Skinny/%s", l->name);

	dumpsub(sub, 0);

	d->hookstate = SKINNY_ONHOOK;

	/* Not ideal, but let's send updated time at onhook and offhook, as it clears the display */
	transmit_definetimedate(d);

	return 1;
}

static int handle_capabilities_res_message(struct skinny_req *req, struct skinnysession *s)
{
	struct skinny_device *d = s->device;
	struct skinny_line *l;
	uint32_t count = 0;
	struct ast_format_cap *codecs = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
	int i;
#ifdef AST_DEVMODE
	struct ast_str *codec_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
#endif


	if (!codecs) {
		return 0;
	}

	count = letohl(req->data.caps.count);
	if (count > SKINNY_MAX_CAPABILITIES) {
		count = SKINNY_MAX_CAPABILITIES;
		ast_log(LOG_WARNING, "Received more capabilities than we can handle (%d).  Ignoring the rest.\n", SKINNY_MAX_CAPABILITIES);
	}

	for (i = 0; i < count; i++) {
		struct ast_format *acodec;
		int scodec = 0;
		scodec = letohl(req->data.caps.caps[i].codec);
		acodec = codec_skinny2ast(scodec);
		SKINNY_DEBUG(DEBUG_AUDIO, 4, "Adding codec capability %s (%d)\n", ast_format_get_name(acodec), scodec);
		ast_format_cap_append(codecs, acodec, 0);
	}

	ast_format_cap_get_compatible(d->confcap, codecs, d->cap);
	SKINNY_DEBUG(DEBUG_AUDIO, 4, "Device capability set to '%s'\n", ast_format_cap_get_names(d->cap, &codec_buf));
	AST_LIST_TRAVERSE(&d->lines, l, list) {
		ast_mutex_lock(&l->lock);
		ast_format_cap_get_compatible(l->confcap, d->cap, l->cap);
		ast_mutex_unlock(&l->lock);
	}

	ao2_ref(codecs, -1);
	return 1;
}

static int handle_button_template_req_message(struct skinny_req *req, struct skinnysession *s)
{
	struct skinny_device *d = s->device;
	struct skinny_line *l;
	int i;
	struct skinny_speeddial *sd;
	struct skinny_serviceurl *surl;
	struct button_definition_template btn[42];
	int lineInstance = 1;
	int speeddialInstance = 1;
	int serviceurlInstance = 1;
	int buttonCount = 0;

	if (!(req = req_alloc(sizeof(struct button_template_res_message), BUTTON_TEMPLATE_RES_MESSAGE)))
		return -1;

	SKINNY_DEBUG(DEBUG_TEMPLATE, 3, "Creating Button Template\n");

	memset(&btn, 0, sizeof(btn));
	get_button_template(s, btn);

	for (i=0; i<42; i++) {
		int btnSet = 0;
		switch (btn[i].buttonDefinition) {
			case BT_CUST_LINE:
				/* assume failure */
				req->data.buttontemplate.definition[i].buttonDefinition = BT_NONE;
				req->data.buttontemplate.definition[i].instanceNumber = 0;

				AST_LIST_TRAVERSE(&d->lines, l, list) {
					if (l->instance == lineInstance) {
						SKINNY_DEBUG(DEBUG_TEMPLATE, 4, "Adding button: %d, %d\n", BT_LINE, lineInstance);
						req->data.buttontemplate.definition[i].buttonDefinition = BT_LINE;
						req->data.buttontemplate.definition[i].instanceNumber = lineInstance;
						lineInstance++;
						buttonCount++;
						btnSet = 1;
						break;
					}
				}

				if (!btnSet) {
					AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
						if (sd->isHint && sd->instance == lineInstance) {
							SKINNY_DEBUG(DEBUG_TEMPLATE, 4, "Adding button: %d, %d\n", BT_LINE, lineInstance);
							req->data.buttontemplate.definition[i].buttonDefinition = BT_LINE;
							req->data.buttontemplate.definition[i].instanceNumber = lineInstance;
							lineInstance++;
							buttonCount++;
							btnSet = 1;
							break;
						}
					}
				}
				break;
			case BT_CUST_LINESPEEDDIAL:
				/* assume failure */
				req->data.buttontemplate.definition[i].buttonDefinition = BT_NONE;
				req->data.buttontemplate.definition[i].instanceNumber = 0;

				AST_LIST_TRAVERSE(&d->lines, l, list) {
					if (l->instance == lineInstance) {
						SKINNY_DEBUG(DEBUG_TEMPLATE, 4, "Adding button: %d, %d\n", BT_LINE, lineInstance);
						req->data.buttontemplate.definition[i].buttonDefinition = BT_LINE;
						req->data.buttontemplate.definition[i].instanceNumber = lineInstance;
						lineInstance++;
						buttonCount++;
						btnSet = 1;
						break;
					}
				}

				if (!btnSet) {
					AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
						if (sd->isHint && sd->instance == lineInstance) {
							SKINNY_DEBUG(DEBUG_TEMPLATE, 4, "Adding button: %d, %d\n", BT_LINE, lineInstance);
							req->data.buttontemplate.definition[i].buttonDefinition = BT_LINE;
							req->data.buttontemplate.definition[i].instanceNumber = lineInstance;
							lineInstance++;
							buttonCount++;
							btnSet = 1;
							break;
						} else if (!sd->isHint && sd->instance == speeddialInstance) {
							SKINNY_DEBUG(DEBUG_TEMPLATE, 4, "Adding button: %d, %d\n", BT_SPEEDDIAL, speeddialInstance);
							req->data.buttontemplate.definition[i].buttonDefinition = BT_SPEEDDIAL;
							req->data.buttontemplate.definition[i].instanceNumber = speeddialInstance;
							speeddialInstance++;
							buttonCount++;
							btnSet = 1;
							break;
						}
					}
				}

				if (!btnSet) {
					AST_LIST_TRAVERSE(&d->serviceurls, surl, list) {
						if (surl->instance == serviceurlInstance) {
							SKINNY_DEBUG(DEBUG_TEMPLATE, 4, "Adding button: %d, %d\n", BT_SERVICEURL, serviceurlInstance);
							req->data.buttontemplate.definition[i].buttonDefinition = BT_SERVICEURL;
							req->data.buttontemplate.definition[i].instanceNumber = serviceurlInstance;
							serviceurlInstance++;
							buttonCount++;
							btnSet = 1;
							break;
						}
					}
				}
				break;
			case BT_LINE:
				req->data.buttontemplate.definition[i].buttonDefinition = htolel(BT_NONE);
				req->data.buttontemplate.definition[i].instanceNumber = htolel(0);

				AST_LIST_TRAVERSE(&d->lines, l, list) {
					if (l->instance == lineInstance) {
						SKINNY_DEBUG(DEBUG_TEMPLATE, 4, "Adding button: %d, %d\n", BT_LINE, lineInstance);
						req->data.buttontemplate.definition[i].buttonDefinition = BT_LINE;
						req->data.buttontemplate.definition[i].instanceNumber = lineInstance;
						lineInstance++;
						buttonCount++;
						btnSet = 1;
						break;
					}
				}
				break;
			case BT_SPEEDDIAL:
				req->data.buttontemplate.definition[i].buttonDefinition = BT_NONE;
				req->data.buttontemplate.definition[i].instanceNumber = 0;

				AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
					if (!sd->isHint && sd->instance == speeddialInstance) {
						SKINNY_DEBUG(DEBUG_TEMPLATE, 4, "Adding button: %d, %d\n", BT_SPEEDDIAL, speeddialInstance);
						req->data.buttontemplate.definition[i].buttonDefinition = BT_SPEEDDIAL;
						req->data.buttontemplate.definition[i].instanceNumber = speeddialInstance - 1;
						speeddialInstance++;
						buttonCount++;
						btnSet = 1;
						break;
					}
				}
				break;
			case BT_NONE:
				break;
			default:
				SKINNY_DEBUG(DEBUG_TEMPLATE, 4, "Adding button: %d, %d\n", btn[i].buttonDefinition, 0);
				req->data.buttontemplate.definition[i].buttonDefinition = htolel(btn[i].buttonDefinition);
				req->data.buttontemplate.definition[i].instanceNumber = 0;
				buttonCount++;
				btnSet = 1;
				break;
		}
	}

	req->data.buttontemplate.buttonOffset = 0;
	req->data.buttontemplate.buttonCount = htolel(buttonCount);
	req->data.buttontemplate.totalButtonCount = htolel(buttonCount);

	SKINNY_DEBUG(DEBUG_PACKET | DEBUG_TEMPLATE, 3, "Transmitting BUTTON_TEMPLATE_RES_MESSAGE to %s, type %d\n",
		d->name, d->type);
	transmit_response(d, req);
	return 1;
}

static int handle_open_receive_channel_ack_message(struct skinny_req *req, struct skinnysession *s)
{
	struct skinny_device *d = s->device;
	struct skinny_line *l;
	struct skinny_subchannel *sub;
	struct sockaddr_in sin = { 0, };
	struct sockaddr_in us = { 0, };
	struct ast_sockaddr sin_tmp;
	struct ast_sockaddr us_tmp;
	struct ast_format *tmpfmt;
	uint32_t addr;
	int port;
	int status;
	int callid;
	unsigned int framing;

	status = (d->protocolversion<17) ? letohl(req->data.openreceivechannelack_ip4.status) : letohl(req->data.openreceivechannelack_ip6.status);

	if (status) {
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received OPEN_RECEIVE_CHANNEL_ACK_MESSAGE from %s, status %d\n",
			d->name, status);
		ast_log(LOG_ERROR, "Open Receive Channel Failure\n");
		return 0;
	}

	if (d->protocolversion<17) {
		addr = req->data.openreceivechannelack_ip4.ipAddr;
		port = letohl(req->data.openreceivechannelack_ip4.port);
		callid = letohl(req->data.openreceivechannelack_ip4.callReference);
	} else {
		memcpy(&addr, &req->data.openreceivechannelack_ip6.ipAddr, sizeof(addr));
		port = letohl(req->data.openreceivechannelack_ip6.port);
		callid = letohl(req->data.openreceivechannelack_ip6.callReference);
	}

	sin.sin_family = AF_INET;
	sin.sin_addr.s_addr = addr;
	sin.sin_port = htons(port);

	SKINNY_DEBUG(DEBUG_PACKET, 3, "Received OPEN_RECEIVE_CHANNEL_ACK_MESSAGE from %s, status %d, callid %d, ip %s:%d\n",
		d->name, status, callid, ast_inet_ntoa(sin.sin_addr), port);

	sub = find_subchannel_by_reference(d, callid);

	if (!sub) {
		ast_log(LOG_ERROR, "Open Receive Channel Failure - can't find sub for %d\n", callid);
		return 0;
	}

	l = sub->line;

	if (sub->rtp) {
		ast_sockaddr_from_sin(&sin_tmp, &sin);
		ast_rtp_instance_set_remote_address(sub->rtp, &sin_tmp);
		ast_rtp_instance_get_local_address(sub->rtp, &us_tmp);
		ast_sockaddr_to_sin(&us_tmp, &us);
		us.sin_addr.s_addr = us.sin_addr.s_addr ? us.sin_addr.s_addr : d->ourip.s_addr;
	} else {
		ast_log(LOG_ERROR, "No RTP structure, this is very bad\n");
		return 0;
	}

	SKINNY_DEBUG(DEBUG_PACKET, 4, "device ipaddr = %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
	SKINNY_DEBUG(DEBUG_PACKET, 4, "asterisk ipaddr = %s:%d\n", ast_inet_ntoa(us.sin_addr), ntohs(us.sin_port));

	tmpfmt = ast_format_cap_get_format(l->cap, 0);
	framing = ast_format_cap_get_format_framing(l->cap, tmpfmt);

	SKINNY_DEBUG(DEBUG_PACKET, 4, "Setting payloadType to '%s' (%u ms)\n", ast_format_get_name(tmpfmt), framing);

	transmit_startmediatransmission(d, sub, us, tmpfmt, framing);

	ao2_ref(tmpfmt, -1);

	return 1;
}

static int handle_enbloc_call_message(struct skinny_req *req, struct skinnysession *s)
{
	struct skinny_device *d = s->device;
	struct skinny_line *l;
	struct skinny_subchannel *sub = NULL;
	struct ast_channel *c;

	sub = find_subchannel_by_instance_reference(d, d->lastlineinstance, d->lastcallreference);

	if (!sub) {
		l = find_line_by_instance(d, d->lastlineinstance);
		if (!l) {
			return 0;
		}
	} else {
		l = sub->line;
	}

	c = skinny_new(l, NULL, AST_STATE_DOWN, NULL, NULL, SKINNY_OUTGOING);

	if(!c) {
		ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", l->name, d->name);
	} else {
		d->hookstate = SKINNY_OFFHOOK;

		sub = ast_channel_tech_pvt(c);
		dialandactivatesub(sub, req->data.enbloccallmessage.calledParty);
	}

	return 1;
}

static int handle_soft_key_event_message(struct skinny_req *req, struct skinnysession *s)
{
	struct skinny_device *d = s->device;
	struct skinny_line *l;
	struct skinny_subchannel *sub = NULL;
	struct ast_channel *c;
	int event;
	int instance;
	int callreference;

	event = letohl(req->data.softkeyeventmessage.softKeyEvent);
	instance = letohl(req->data.softkeyeventmessage.instance);
	callreference = letohl(req->data.softkeyeventmessage.callreference);

	if (instance) {
		l = find_line_by_instance(d, instance);
		if (callreference) {
			sub = find_subchannel_by_instance_reference(d, instance, callreference);
		} else {
			sub = find_subchannel_by_instance_reference(d, instance, d->lastcallreference);
		}
	} else {
		l = find_line_by_instance(d, d->lastlineinstance);
	}

	if (!l) {
		ast_log(LOG_WARNING,  "Received Softkey Event: %d(%d/%d) but can't find line\n", event, instance, callreference);
		return 0;
	}

	ast_devstate_changed(AST_DEVICE_INUSE, AST_DEVSTATE_CACHABLE, "Skinny/%s", l->name);

	switch(event) {
	case SOFTKEY_NONE:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received SOFTKEY_NONE from %s, inst %d, callref %d\n",
			d->name, instance, callreference);
		break;
	case SOFTKEY_REDIAL:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received SOFTKEY_REDIAL from %s, inst %d, callref %d\n",
			d->name, instance, callreference);

		if (ast_strlen_zero(l->lastnumberdialed)) {
			ast_log(LOG_WARNING, "Attempted redial, but no previously dialed number found. Ignoring button.\n");
			break;
		}

		if (!sub || !sub->owner) {
			c = skinny_new(l, NULL, AST_STATE_DOWN, NULL, NULL, SKINNY_OUTGOING);
		} else {
			c = sub->owner;
		}

		if (!c) {
			ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", l->name, d->name);
		} else {
			sub = ast_channel_tech_pvt(c);
			dialandactivatesub(sub, l->lastnumberdialed);
		}
		break;
	case SOFTKEY_NEWCALL:  /* Actually the DIAL softkey */
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received SOFTKEY_NEWCALL from %s, inst %d, callref %d\n",
			d->name, instance, callreference);

		/* New Call ALWAYS gets a new sub-channel */
		c = skinny_new(l, NULL, AST_STATE_DOWN, NULL, NULL, SKINNY_OUTGOING);
		sub = ast_channel_tech_pvt(c);

		if (!c) {
			ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", l->name, d->name);
		} else {
			activatesub(sub, SUBSTATE_OFFHOOK);
		}
		break;
	case SOFTKEY_HOLD:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received SOFTKEY_HOLD from %s, inst %d, callref %d\n",
			d->name, instance, callreference);

		if (sub) {
			setsubstate(sub, SUBSTATE_HOLD);
		} else { /* No sub, maybe an SLA call */
			struct skinny_subline *subline;
			if ((subline = find_subline_by_callid(d, callreference))) {
				setsubstate(subline->sub, SUBSTATE_HOLD);
			}
		}

		break;
	case SOFTKEY_TRNSFER:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received SOFTKEY_TRNSFER from %s, inst %d, callref %d\n",
			d->name, instance, callreference);
		if (l->transfer)
			handle_transfer_button(sub);
		else
			transmit_displaynotify(d, "Transfer disabled", 10);

		break;
	case SOFTKEY_DND:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received SOFTKEY_DND from %s, inst %d, callref %d\n",
			d->name, instance, callreference);

		/* Do not disturb */
		if (l->dnd != 0){
			ast_verb(3, "Disabling DND on %s@%s\n", l->name, d->name);
			l->dnd = 0;
			transmit_lamp_indication(d, STIMULUS_DND, 1, SKINNY_LAMP_ON);
			transmit_displaynotify(d, "DnD disabled", 10);
		} else {
			ast_verb(3, "Enabling DND on %s@%s\n", l->name, d->name);
			l->dnd = 1;
			transmit_lamp_indication(d, STIMULUS_DND, 1, SKINNY_LAMP_OFF);
			transmit_displaynotify(d, "DnD enabled", 10);
		}
		break;
	case SOFTKEY_CFWDALL:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received SOFTKEY_CFWDALL from %s, inst %d, callref %d\n",
			d->name, instance, callreference);
		handle_callforward_button(l, sub, SKINNY_CFWD_ALL);
		break;
	case SOFTKEY_CFWDBUSY:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received SOFTKEY_CFWDBUSY from %s, inst %d, callref %d\n",
			d->name, instance, callreference);
		handle_callforward_button(l, sub, SKINNY_CFWD_BUSY);
		break;
	case SOFTKEY_CFWDNOANSWER:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received SOFTKEY_CFWDNOANSWER from %s, inst %d, callref %d\n",
			d->name, instance, callreference);
		handle_callforward_button(l, sub, SKINNY_CFWD_NOANSWER);
		break;
	case SOFTKEY_BKSPC:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received SOFTKEY_BKSPC from %s, inst %d, callref %d\n",
			d->name, instance, callreference);
		if (-1 < sub->dialer_sched && !skinny_sched_del(sub->dialer_sched, sub)) {
			size_t len;
			sub->dialer_sched = -1;
			len = strlen(sub->exten);
			if (len > 0) {
				sub->exten[len-1] = '\0';
				if (len == 1) {
					transmit_start_tone(d, SKINNY_DIALTONE, l->instance, sub->callid);
					transmit_selectsoftkeys(d, l->instance, sub->callid, KEYDEF_OFFHOOK, KEYMASK_ALL);
				}
				transmit_backspace(d, l->instance, sub->callid);
			}
			sub->dialer_sched = skinny_sched_add(gendigittimeout, skinny_dialer_cb, sub);
		}
		break;
	case SOFTKEY_ENDCALL:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received SOFTKEY_ENDCALL from %s, inst %d, callref %d\n",
			d->name, instance, callreference);

		ast_devstate_changed(AST_DEVICE_NOT_INUSE, AST_DEVSTATE_CACHABLE, "Skinny/%s", l->name);

		if (sub) {
			dumpsub(sub, 1);
		} else { /* No sub, maybe an SLA call */
			struct skinny_subline *subline;
			if ((subline = find_subline_by_callid(d, callreference))) {
				dumpsub(subline->sub, 1);
			}
		}

		d->hookstate = SKINNY_ONHOOK;

		/* Not ideal, but let's send updated time at onhook and offhook, as it clears the display */
		transmit_definetimedate(d);

		break;
	case SOFTKEY_RESUME:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received SOFTKEY_RESUME from %s, inst %d, callref %d\n",
			d->name, instance, callreference);

		if (sub) {
			activatesub(sub, SUBSTATE_CONNECTED);
		} else { /* No sub, maybe an inactive SLA call */
			struct skinny_subline *subline;
			subline = find_subline_by_callid(d, callreference);
			c = skinny_new(l, subline, AST_STATE_DOWN, NULL, NULL, SKINNY_OUTGOING);
			if (!c) {
				ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", l->name, d->name);
			} else {
				sub = ast_channel_tech_pvt(c);
				dialandactivatesub(sub, subline->exten);
			}
		}
		break;
	case SOFTKEY_ANSWER:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received SOFTKEY_ANSWER from %s, inst %d, callref %d\n",
			d->name, instance, callreference);

		transmit_ringer_mode(d, SKINNY_RING_OFF);
		transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_ON);
		if (d->hookstate == SKINNY_ONHOOK) {
			transmit_speaker_mode(d, SKINNY_SPEAKERON);
			d->hookstate = SKINNY_OFFHOOK;
		}

		if (sub && sub->calldirection == SKINNY_INCOMING) {
			activatesub(sub, SUBSTATE_CONNECTED);
		}
		break;
	case SOFTKEY_INFO:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received SOFTKEY_INFO from %s, inst %d, callref %d\n",
			d->name, instance, callreference);
		break;
	case SOFTKEY_CONFRN:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received SOFTKEY_CONFRN from %s, inst %d, callref %d\n",
			d->name, instance, callreference);
		/* XXX determine the best way to pull off a conference.  Meetme? */
		break;
	case SOFTKEY_PARK:
		{
		char extout[AST_MAX_EXTENSION];
		char message[32];
		RAII_VAR(struct ast_bridge_channel *, bridge_channel, NULL, ao2_cleanup);
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received SOFTKEY_PARK from %s, inst %d, callref %d\n",
			d->name, instance, callreference);

		if (!ast_parking_provider_registered()) {
			transmit_displaynotify(d, "Call Park not available", 10);
			break;
		}

		if ((sub && sub->owner) && (ast_channel_state(sub->owner) ==  AST_STATE_UP)) {
			c = sub->owner;
			ast_channel_lock(c);
			bridge_channel = ast_channel_get_bridge_channel(c);
			ast_channel_unlock(c);

			if (!bridge_channel) {
				transmit_displaynotify(d, "Call Park failed", 10);
				break;
			}

			if (!ast_parking_park_call(bridge_channel, extout, sizeof(extout))) {
				snprintf(message, sizeof(message), "Call Parked at: %s", extout);
				transmit_displaynotify(d, message, 10);
				break;
			}
			transmit_displaynotify(d, "Call Park failed", 10);
		} else {
			transmit_displaynotify(d, "Call Park not available", 10);
		}
		break;
		}
	case SOFTKEY_JOIN:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received SOFTKEY_JOIN from %s, inst %d, callref %d\n",
			d->name, instance, callreference);
		/* this is SLA territory, should not get here unless there is a meetme at subline */
		{
			struct skinny_subline *subline;
			subline = find_subline_by_callid(d, callreference);
			c = skinny_new(l, subline, AST_STATE_DOWN, NULL, NULL, SKINNY_OUTGOING);
			if (!c) {
				ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", l->name, d->name);
			} else {
				sub = ast_channel_tech_pvt(c);
				dialandactivatesub(sub, subline->exten);
			}
		}
		break;
	case SOFTKEY_MEETME:
		/* XXX How is this different from CONFRN? */
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received SOFTKEY_MEETME from %s, inst %d, callref %d\n",
			d->name, instance, callreference);
		break;
	case SOFTKEY_PICKUP:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received SOFTKEY_PICKUP from %s, inst %d, callref %d\n",
			d->name, instance, callreference);
		break;
	case SOFTKEY_GPICKUP:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received SOFTKEY_GPICKUP from %s, inst %d, callref %d\n",
			d->name, instance, callreference);
		if (!sub || !sub->owner) {
			c = skinny_new(l, NULL, AST_STATE_DOWN, NULL, NULL, SKINNY_INCOMING);
		} else {
			c = sub->owner;
		}

		if (!c) {
			ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", l->name, d->name);
		} else {
			ast_channel_ref(c);
			sub = ast_channel_tech_pvt(c);
			ast_pickup_call(c);
			if (sub->owner == c) {
				ast_channel_unref(c);
				dumpsub(sub, 1);
			} else {
				ast_hangup(c);
				setsubstate(sub, SUBSTATE_CONNECTED);
				ast_channel_unref(c);
			}
		}
		break;
	case SOFTKEY_FORCEDIAL:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received SOFTKEY_FORCEDIAL from %s, inst %d, callref %d\n",
			d->name, instance, callreference);
		skinny_dialer(sub, 1);

		break;
	default:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received SOFTKEY_UNKNOWN(%d) from %s, inst %d, callref %d\n",
			event, d->name, instance, callreference);
		break;
	}

	return 1;
}

static int handle_message(struct skinny_req *req, struct skinnysession *s)
{
	int res = 0;
	struct skinny_speeddial *sd;
	struct skinny_device *d = s->device;

	if (!d && !(letohl(req->e) == REGISTER_MESSAGE || letohl(req->e) == ALARM_MESSAGE || letohl(req->e) == KEEP_ALIVE_MESSAGE)) {
		ast_log(LOG_WARNING, "Client sent message #%u without first registering.\n", req->e);
		return 0;
	}

	switch(letohl(req->e)) {
	case KEEP_ALIVE_MESSAGE:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received KEEP_ALIVE_MESSAGE from %s\n", (d ? d->name : "unregistered"));
		handle_keepalive_message(req, s);
		break;
	case REGISTER_MESSAGE:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received REGISTER_MESSAGE from %s, name %s, type %u, protovers %d\n",
			d->name, req->data.reg.name, letohl(req->data.reg.type), letohl(req->data.reg.protocolVersion));
		res = skinny_register(req, s);
		if (!res) {
			sleep(2);
			res = skinny_register(req, s);
		}
		if (res != 1) {
			transmit_registerrej(s);
			return -1;
		}
		ast_atomic_fetchadd_int(&unauth_sessions, -1);
		ast_verb(3, "Device '%s' successfully registered (protoVers %d)\n", s->device->name, s->device->protocolversion);
		transmit_registerack(s->device);
		transmit_capabilitiesreq(s->device);
		res = 0;
		break;
	case IP_PORT_MESSAGE:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received IP_PORT_MESSAGE from %s\n", d->name);
		res = handle_ip_port_message(req, s);
		break;
	case KEYPAD_BUTTON_MESSAGE:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received KEYPAD_BUTTON_MESSAGE from %s, digit %u, inst %u, callref %u\n",
			d->name, letohl(req->data.keypad.button), letohl(req->data.keypad.lineInstance), letohl(req->data.keypad.callReference));
		res = handle_keypad_button_message(req, s);
		break;
	case ENBLOC_CALL_MESSAGE:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received ENBLOC_CALL_MESSAGE from %s, calledParty %s\n",
			d->name, req->data.enbloccallmessage.calledParty);
		res = handle_enbloc_call_message(req, s);
		break;
	case STIMULUS_MESSAGE:
		/* SKINNY_PACKETDEBUG handled in handle_stimulus_message */
		res = handle_stimulus_message(req, s);
		break;
	case OFFHOOK_MESSAGE:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received OFFHOOK_MESSAGE from %s, inst %u, ref %u\n",
			d->name, letohl(req->data.offhook.instance), letohl(req->data.offhook.reference));
		res = handle_offhook_message(req, s);
		break;
	case ONHOOK_MESSAGE:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received ONHOOK_MESSAGE from %s, inst %u, ref %u\n",
			d->name, letohl(req->data.offhook.instance), letohl(req->data.offhook.reference));
		res = handle_onhook_message(req, s);
		break;
	case CAPABILITIES_RES_MESSAGE:
		SKINNY_DEBUG(DEBUG_PACKET | DEBUG_AUDIO, 3, "Received CAPABILITIES_RES_MESSAGE from %s, count %u, codec data\n",
			d->name, letohl(req->data.caps.count));
		res = handle_capabilities_res_message(req, s);
		break;
	case SPEED_DIAL_STAT_REQ_MESSAGE:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received SPEED_DIAL_STAT_REQ_MESSAGE from %s, sdNum %u\n",
			d->name, letohl(req->data.speeddialreq.speedDialNumber));
		if ( (sd = find_speeddial_by_instance(s->device, letohl(req->data.speeddialreq.speedDialNumber), 0)) ) {
			transmit_speeddialstatres(d, sd);
		}
		break;
	case LINE_STATE_REQ_MESSAGE:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received LINE_STATE_REQ_MESSAGE from %s, lineNum %u\n",
			d->name, letohl(req->data.line.lineNumber));
		transmit_linestatres(d, letohl(req->data.line.lineNumber));
		break;
	case TIME_DATE_REQ_MESSAGE:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received TIME_DATE_REQ_MESSAGE from %s\n", d->name);
		transmit_definetimedate(d);
		break;
	case BUTTON_TEMPLATE_REQ_MESSAGE:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received BUTTON_TEMPLATE_REQ_MESSAGE from %s\n", d->name);
		res = handle_button_template_req_message(req, s);
		break;
	case VERSION_REQ_MESSAGE:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received VERSION_REQ_MESSAGE from %s\n", d->name);
		transmit_versionres(d);
		break;
	case SERVER_REQUEST_MESSAGE:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received SERVER_REQUEST_MESSAGE from %s\n", d->name);
		transmit_serverres(d);
		break;
	case ALARM_MESSAGE:
		/* no response necessary */
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received ALARM_MESSAGE from %s, alarm %s\n",
			d->name, req->data.alarm.displayMessage);
		break;
	case OPEN_RECEIVE_CHANNEL_ACK_MESSAGE:
		/* SKINNY_PACKETDEBUG handled in handle_open_receive_channel_ack_message */
		res = handle_open_receive_channel_ack_message(req, s);
		break;
	case SOFT_KEY_SET_REQ_MESSAGE:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received SOFT_KEY_SET_REQ_MESSAGE from %s\n", d->name);
		transmit_softkeysetres(d);
		transmit_selectsoftkeys(d, 0, 0, KEYDEF_ONHOOK, KEYMASK_ALL);
		break;
	case SOFT_KEY_EVENT_MESSAGE:
		/* SKINNY_PACKETDEBUG handled in handle_soft_key_event_message */
		res = handle_soft_key_event_message(req, s);
		break;
	case UNREGISTER_MESSAGE:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received UNREGISTER_MESSAGE from %s\n", d->name);
		ast_log(LOG_NOTICE, "Received UNREGISTER_MESSAGE from %s\n", d->name);
		end_session(s);
		break;
	case SOFT_KEY_TEMPLATE_REQ_MESSAGE:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received SOFT_KEY_TEMPLATE_REQ_MESSAGE from %s\n", d->name);
		transmit_softkeytemplateres(d);
		break;
	case HEADSET_STATUS_MESSAGE:
		/* XXX umm...okay?  Why do I care? */
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received HEADSET_STATUS_MESSAGE from %s\n", d->name);
		break;
	case REGISTER_AVAILABLE_LINES_MESSAGE:
		/* XXX I have no clue what this is for, but my phone was sending it, so... */
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received REGISTER_AVAILABLE_LINES_MESSAGE from %s\n", d->name);
		break;
	case SERVICEURL_STATREQ_MESSAGE:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "SERVICEURL_STATREQ_MESSAGE from %s\n", d->name);
		transmit_serviceurlstat(d, letohl(req->data.serviceurlmessage.instance));
		break;
	default:
		SKINNY_DEBUG(DEBUG_PACKET, 3, "Received UNKNOWN_MESSAGE(%x) from %s\n", (unsigned)letohl(req->e), d->name);
		break;
	}
	return res;
}

static void destroy_session(struct skinnysession *s)
{
	ast_mutex_lock(&s->lock);
	if (s->fd > -1) {
		close(s->fd);
	}

	if (s->device) {
		s->device->session = NULL;
	} else {
		ast_atomic_fetchadd_int(&unauth_sessions, -1);
	}
	ast_mutex_unlock(&s->lock);
	ast_mutex_destroy(&s->lock);

	if (s->t != AST_PTHREADT_NULL) {
		pthread_detach(s->t);
	}

	ast_free(s);
}

static int skinny_noauth_cb(const void *data)
{
	struct skinnysession *s = (struct skinnysession *)data;
	ast_log(LOG_WARNING, "Skinny Client failed to authenticate in %d seconds (SCHED %d)\n", auth_timeout, s->auth_timeout_sched);
	s->auth_timeout_sched = -1;
	end_session(s);
	return 0;
}

static int skinny_nokeepalive_cb(const void *data)
{
	struct skinnysession *s = (struct skinnysession *)data;
	ast_log(LOG_WARNING, "Skinny Client failed to send keepalive in last %d seconds (SCHED %d)\n", keep_alive*3, s->keepalive_timeout_sched);
	s->keepalive_timeout_sched = -1;
	end_session(s);
	return 0;
}

static void skinny_session_cleanup(void *data)
{
	struct skinnysession *s = (struct skinnysession *)data;
	struct skinny_device *d = s->device;
	struct skinny_line *l;
	struct skinny_speeddial *sd;

	ast_log(LOG_NOTICE, "Ending Skinny session from %s at %s\n", d ? d->name : "unknown", ast_inet_ntoa(s->sin.sin_addr));

	if (s->lockstate) {
		ast_mutex_unlock(&s->lock);
	}

	if (-1 < s->auth_timeout_sched) {
		not_used = ast_sched_del(sched, s->auth_timeout_sched);
		s->auth_timeout_sched = -1;
	}
	if (-1 < s->keepalive_timeout_sched) {
		not_used = ast_sched_del(sched, s->keepalive_timeout_sched);
		s->keepalive_timeout_sched = -1;
	}

	if (d) {
		RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
		d->session = NULL;

		AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
			if (sd->stateid > -1)
				ast_extension_state_del(sd->stateid, NULL);
		}
		AST_LIST_TRAVERSE(&d->lines, l, list) {
			if (l->device != d) {
				continue;
			}
			ast_format_cap_remove_by_type(l->cap, AST_MEDIA_TYPE_UNKNOWN);
			ast_format_cap_update_by_allow_disallow(l->cap, "all", 0);
			l->instance = 0;
			unregister_exten(l);
			ast_devstate_changed(AST_DEVICE_UNAVAILABLE, AST_DEVSTATE_CACHABLE, "Skinny/%s", l->name);
		}
		ast_endpoint_set_state(d->endpoint, AST_ENDPOINT_OFFLINE);
		blob = ast_json_pack("{s: s}", "peer_status", "Unregistered");
		ast_endpoint_blob_publish(d->endpoint, ast_endpoint_state_type(), blob);
	}

	AST_LIST_LOCK(&sessions);
	AST_LIST_REMOVE(&sessions, s, list);
	AST_LIST_UNLOCK(&sessions);

	destroy_session(s);
}

#define PACKET_TIMEOUT 10000

static void *skinny_session(void *data)
{
	int res;
	int bytesread;
	struct skinny_req *req = NULL;
	struct skinnysession *s = data;

	int dlen = 0;
	int eventmessage = 0;
	struct pollfd fds[1];

	ast_log(LOG_NOTICE, "Starting Skinny session from %s\n", ast_inet_ntoa(s->sin.sin_addr));

	pthread_cleanup_push(skinny_session_cleanup, s);

	s->start = ast_tvnow();
	s->last_keepalive = ast_tvnow();
	s->keepalive_count = 0;
	s->lockstate = 0;

	AST_LIST_LOCK(&sessions);
	AST_LIST_INSERT_HEAD(&sessions, s, list);
	AST_LIST_UNLOCK(&sessions);

	s->auth_timeout_sched = ast_sched_add(sched, auth_timeout*1000, skinny_noauth_cb, s);
	s->keepalive_timeout_sched = ast_sched_add(sched, keep_alive*3000, skinny_nokeepalive_cb, s);

	for (;;) {

		fds[0].fd = s->fd;
		fds[0].events = POLLIN;
		fds[0].revents = 0;
		res = ast_poll(fds, 1, -1); /* block */
		if (res < 0) {
			if (errno != EINTR) {
				ast_log(LOG_WARNING, "Select returned error: %s\n", strerror(errno));
				ast_verb(3, "Ending Skinny session from %s (bad input)\n", ast_inet_ntoa(s->sin.sin_addr));
				break;
			}
		}

		if (!fds[0].revents) {
			continue;
		}
		ast_debug(1, "Reading header\n");

		if (!(req = ast_calloc(1, SKINNY_MAX_PACKET))) {
			ast_log(LOG_WARNING, "Unable to allocated memorey for skinny_req.\n");
			break;
		}

		ast_mutex_lock(&s->lock);
		s->lockstate = 1;

		if ((res = read(s->fd, req, skinny_header_size)) != skinny_header_size) {
			if (res < 0) {
				ast_log(LOG_WARNING, "Header read() returned error: %s\n", strerror(errno));
			} else {
				ast_log(LOG_WARNING, "Unable to read header. Only found %d bytes.\n", res);
			}
			break;
		}

		eventmessage = letohl(req->e);
		if (eventmessage < 0) {
			ast_log(LOG_ERROR, "Event Message is NULL from socket %d, This is bad\n", s->fd);
			break;
		}

		dlen = letohl(req->len) - 4;
		if (dlen < 0) {
			ast_log(LOG_WARNING, "Skinny Client sent invalid data.\n");
			break;
		}
		if (dlen > (SKINNY_MAX_PACKET - skinny_header_size)) {
			ast_log(LOG_WARNING, "Skinny packet too large (%d bytes), max length(%d bytes)\n", dlen+8, SKINNY_MAX_PACKET);
			break;
		}

		ast_debug(1, "Read header: Message ID: 0x%04x,  %d bytes in packet\n", eventmessage, dlen);

		bytesread = 0;
		while (bytesread < dlen) {
			ast_debug(1, "Waiting %dms for %d bytes of %d\n", PACKET_TIMEOUT, dlen - bytesread, dlen);
			fds[0].revents = 0;
			res = ast_poll(fds, 1, PACKET_TIMEOUT);
			if (res <= 0) {
				if (res == 0) {
					ast_debug(1, "Poll timed out waiting for %d bytes\n", dlen - bytesread);
				} else {
					ast_log(LOG_WARNING, "Poll failed waiting for %d bytes: %s\n",
						dlen - bytesread, strerror(errno));
				}
				ast_verb(3, "Ending Skinny session from %s (bad input)\n", ast_inet_ntoa(s->sin.sin_addr));
				res = -1;

				break;
			}
			if (!fds[0].revents) {
				continue;
			}

			res = read(s->fd, ((char*)&req->data)+bytesread, dlen-bytesread);
			if (res < 0) {
				ast_log(LOG_WARNING, "Data read() returned error: %s\n", strerror(errno));
				break;
			}
			bytesread += res;
			ast_debug(1, "Read %d bytes.  %d of %d now read\n", res, bytesread, dlen);
		}

		s->lockstate = 0;
		ast_mutex_unlock(&s->lock);
		if (res < 0) {
			break;
		}

		pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
		res = handle_message(req, s);
		pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);

		if (req) {
			ast_free(req);
			req = NULL;
		}
	}

	ast_log(LOG_NOTICE, "Skinny Session returned: %s\n", strerror(errno));
	if (req) {
		ast_free(req);
	}

	pthread_cleanup_pop(1);

	return 0;
}

static void *accept_thread(void *ignore)
{
	int as;
	struct sockaddr_in sin;
	socklen_t sinlen;
	struct skinnysession *s;
	struct protoent *p;
	int arg = 1;

	for (;;) {
		sinlen = sizeof(sin);
		as = accept(skinnysock, (struct sockaddr *)&sin, &sinlen);
		if (as < 0) {
			ast_log(LOG_NOTICE, "Accept returned -1: %s\n", strerror(errno));
			continue;
		}

		if (ast_atomic_fetchadd_int(&unauth_sessions, +1) >= auth_limit) {
			close(as);
			ast_atomic_fetchadd_int(&unauth_sessions, -1);
			continue;
		}

		p = getprotobyname("tcp");
		if(p) {
			if( setsockopt(as, p->p_proto, TCP_NODELAY, (char *)&arg, sizeof(arg) ) < 0 ) {
				ast_log(LOG_WARNING, "Failed to set Skinny tcp connection to TCP_NODELAY mode: %s\n", strerror(errno));
			}
		}
		if (!(s = ast_calloc(1, sizeof(struct skinnysession)))) {
			close(as);
			ast_atomic_fetchadd_int(&unauth_sessions, -1);
			continue;
		}

		ast_mutex_init(&s->lock);
		memcpy(&s->sin, &sin, sizeof(sin));
		s->fd = as;
		s->auth_timeout_sched = -1;
		s->keepalive_timeout_sched = -1;

		if (ast_pthread_create(&s->t, NULL, skinny_session, s)) {
			s->t = AST_PTHREADT_NULL;
			destroy_session(s);
		}
	}
	SKINNY_DEBUG(DEBUG_THREAD, 3, "Killing accept thread\n");
	close(as);
	return 0;
}

static int skinny_devicestate(const char *data)
{
	struct skinny_line *l;
	char *tmp;

	tmp = ast_strdupa(data);

	l = find_line_by_name(tmp);

	return get_devicestate(l);
}

static struct ast_channel *skinny_request(const char *type, struct ast_format_cap *cap, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *dest, int *cause)
{
	struct skinny_line *l;
	struct skinny_subline *subline = NULL;
	struct ast_channel *tmpc = NULL;
	char tmp[256];

	if (!(ast_format_cap_has_type(cap, AST_MEDIA_TYPE_AUDIO))) {
		struct ast_str *codec_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
		ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format '%s'\n", ast_format_cap_get_names(cap, &codec_buf));
		return NULL;
	}

	ast_copy_string(tmp, dest, sizeof(tmp));
	if (ast_strlen_zero(tmp)) {
		ast_log(LOG_NOTICE, "Skinny channels require a device\n");
		return NULL;
	}
	l = find_line_by_name(tmp);
	if (!l) {
		subline = find_subline_by_name(tmp);
		if (!subline) {
			ast_log(LOG_NOTICE, "No available lines on: %s\n", dest);
			return NULL;
		}
		l = subline->line;
	}
	ast_verb(3, "skinny_request(%s)\n", tmp);
	tmpc = skinny_new(l, subline, AST_STATE_DOWN, assignedids, requestor, SKINNY_INCOMING);
	if (!tmpc) {
		ast_log(LOG_WARNING, "Unable to make channel for '%s'\n", tmp);
	} else if (subline) {
		struct skinny_subchannel *sub = ast_channel_tech_pvt(tmpc);
		subline->sub = sub;
		subline->calldirection = SKINNY_INCOMING;
		subline->substate = SUBSTATE_UNSET;
		subline->callid = sub->callid;
		sub->subline = subline;
	}
	return tmpc;
}

#define TYPE_GENERAL	1
#define TYPE_DEF_DEVICE 2
#define TYPE_DEF_LINE	4
#define TYPE_DEVICE	8
#define TYPE_LINE	16

#define CLINE_OPTS	((struct skinny_line_options *)item)
#define CLINE		((struct skinny_line *)item)
#define CDEV_OPTS	((struct skinny_device_options *)item)
#define CDEV		((struct skinny_device *)item)

static void config_parse_variables(int type, void *item, struct ast_variable *vptr)
{
	struct ast_variable *v;
	int lineInstance = 1;
	int speeddialInstance = 1;
	int serviceUrlInstance = 1;

	while(vptr) {
		v = vptr;
		vptr = vptr->next;

		if (type & (TYPE_GENERAL)) {
			char newcontexts[AST_MAX_CONTEXT];
			char oldcontexts[AST_MAX_CONTEXT];
			char *stringp, *context, *oldregcontext;
			if (!ast_jb_read_conf(&global_jbconf, v->name, v->value)) {
				v = v->next;
				continue;
			}
			if (!strcasecmp(v->name, "bindaddr")) {
				if (!(hp = ast_gethostbyname(v->value, &ahp))) {
					ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
				} else {
					memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
				}
				continue;
			} else if (!strcasecmp(v->name, "keepalive")) {
				keep_alive = atoi(v->value);
				continue;
			} else if (!strcasecmp(v->name, "authtimeout")) {
				int timeout = atoi(v->value);

				if (timeout < 1) {
					ast_log(LOG_WARNING, "Invalid authtimeout value '%s', using default value\n", v->value);
					auth_timeout = DEFAULT_AUTH_TIMEOUT;
				} else {
					auth_timeout = timeout;
				}
				continue;
			} else if (!strcasecmp(v->name, "authlimit")) {
				int limit = atoi(v->value);

				if (limit < 1) {
					ast_log(LOG_WARNING, "Invalid authlimit value '%s', using default value\n", v->value);
					auth_limit = DEFAULT_AUTH_LIMIT;
				} else {
					auth_limit = limit;
				}
				continue;
			} else if (!strcasecmp(v->name, "regcontext")) {
				ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
				stringp = newcontexts;
				/* Initialize copy of current global_regcontext for later use in removing stale contexts */
				ast_copy_string(oldcontexts, regcontext, sizeof(oldcontexts));
				oldregcontext = oldcontexts;
				/* 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, "Skinny");
				}
				ast_copy_string(regcontext, v->value, sizeof(regcontext));
				continue;
			} else if (!strcasecmp(v->name, "vmexten")) {
				ast_copy_string(vmexten, v->value, sizeof(vmexten));
				continue;
			} else if (!strcasecmp(v->name, "immeddialkey")) {
				if (!strcmp(v->value,"#")) {
					immed_dialchar = '#';
				} else if (!strcmp(v->value,"*")) {
					immed_dialchar = '*';
				} else {
					ast_log(LOG_WARNING, "Invalid immeddialkey '%s' at line %d, only # or * accepted. Immeddial key disabled\n", v->value, v->lineno);
				}

				continue;
			} else if (!strcasecmp(v->name, "dateformat")) {
				memcpy(date_format, v->value, sizeof(date_format));
				continue;
			} else if (!strcasecmp(v->name, "tos")) {
				if (ast_str2tos(v->value, &qos.tos))
					ast_log(LOG_WARNING, "Invalid tos value at line %d, refer to QoS documentation\n", v->lineno);
				continue;
			} else if (!strcasecmp(v->name, "tos_audio")) {
				if (ast_str2tos(v->value, &qos.tos_audio))
					ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, refer to QoS documentation\n", v->lineno);
				continue;
			} else if (!strcasecmp(v->name, "tos_video")) {
				if (ast_str2tos(v->value, &qos.tos_video))
					ast_log(LOG_WARNING, "Invalid tos_video value at line %d, refer to QoS documentation\n", v->lineno);
				continue;
			} else if (!strcasecmp(v->name, "cos")) {
				if (ast_str2cos(v->value, &qos.cos))
					ast_log(LOG_WARNING, "Invalid cos value at line %d, refer to QoS documentation\n", v->lineno);
				continue;
			} else if (!strcasecmp(v->name, "cos_audio")) {
				if (ast_str2cos(v->value, &qos.cos_audio))
					ast_log(LOG_WARNING, "Invalid cos_audio value at line %d, refer to QoS documentation\n", v->lineno);
				continue;
			} else if (!strcasecmp(v->name, "cos_video")) {
				if (ast_str2cos(v->value, &qos.cos_video))
					ast_log(LOG_WARNING, "Invalid cos_video value at line %d, refer to QoS documentation\n", v->lineno);
				continue;
			} else if (!strcasecmp(v->name, "bindport")) {
				if (sscanf(v->value, "%5d", &ourport) == 1) {
					bindaddr.sin_port = htons(ourport);
				} else {
					ast_log(LOG_WARNING, "Invalid bindport '%s' at line %d of %s\n", v->value, v->lineno, config);
				}
				continue;
			} else if (!strcasecmp(v->name, "allow")) {
				ast_format_cap_update_by_allow_disallow(default_cap, v->value, 1);
				continue;
			} else if (!strcasecmp(v->name, "disallow")) {
				ast_format_cap_update_by_allow_disallow(default_cap, v->value, 0);
				continue;
			}
		}

		if (!strcasecmp(v->name, "transfer")) {
			if (type & (TYPE_DEF_DEVICE | TYPE_DEVICE)) {
				CDEV_OPTS->transfer = ast_true(v->value);
				continue;
			} else if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
				CLINE_OPTS->transfer = ast_true(v->value);
				continue;
			}
		} else if (!strcasecmp(v->name, "callwaiting")) {
			if (type & (TYPE_DEF_DEVICE | TYPE_DEVICE)) {
				CDEV_OPTS->callwaiting = ast_true(v->value);
				continue;
			} else if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
				CLINE_OPTS->callwaiting = ast_true(v->value);
				continue;
			}
		} else if (!strcasecmp(v->name, "directmedia") || !strcasecmp(v->name, "canreinvite")) {
			if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
				CLINE_OPTS->directmedia = ast_true(v->value);
				continue;
			}
		} else if (!strcasecmp(v->name, "nat")) {
			if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
				CLINE_OPTS->nat = ast_true(v->value);
				continue;
			}
		} else if (!strcasecmp(v->name, "context")) {
			if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
				ast_copy_string(CLINE_OPTS->context, v->value, sizeof(CLINE_OPTS->context));
				continue;
			}
		}else if (!strcasecmp(v->name, "vmexten")) {
			if (type & (TYPE_DEF_DEVICE | TYPE_DEVICE)) {
				ast_copy_string(CDEV_OPTS->vmexten, v->value, sizeof(CDEV_OPTS->vmexten));
				continue;
			} else if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
				ast_copy_string(CLINE_OPTS->vmexten, v->value, sizeof(CLINE_OPTS->vmexten));
				continue;
			}
		} else if (!strcasecmp(v->name, "mwiblink")) {
			if (type & (TYPE_DEF_DEVICE | TYPE_DEVICE)) {
				CDEV_OPTS->mwiblink = ast_true(v->value);
				continue;
			} else if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
				CLINE_OPTS->mwiblink = ast_true(v->value);
				continue;
			}
		} else if (!strcasecmp(v->name, "linelabel")) {
			if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
				ast_copy_string(CLINE_OPTS->label, v->value, sizeof(CLINE_OPTS->label));
				continue;
			}
		} else if (!strcasecmp(v->name, "callerid")) {
			if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
				if (!strcasecmp(v->value, "asreceived")) {
					CLINE_OPTS->cid_num[0] = '\0';
					CLINE_OPTS->cid_name[0] = '\0';
				} else {
					ast_callerid_split(v->value, CLINE_OPTS->cid_name, sizeof(CLINE_OPTS->cid_name), CLINE_OPTS->cid_num, sizeof(CLINE_OPTS->cid_num));
				}
				continue;
			}
		} else if (!strcasecmp(v->name, "amaflags")) {
			if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
				int tempamaflags = ast_channel_string2amaflag(v->value);
				if (tempamaflags < 0) {
					ast_log(LOG_WARNING, "Invalid AMA flags: %s at line %d\n", v->value, v->lineno);
				} else {
					CLINE_OPTS->amaflags = tempamaflags;
				}
				continue;
			}
		} else if (!strcasecmp(v->name, "regexten")) {
			if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
				ast_copy_string(CLINE_OPTS->regexten, v->value, sizeof(CLINE_OPTS->regexten));
				continue;
			}
		} else if (!strcasecmp(v->name, "language")) {
			if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
				ast_copy_string(CLINE_OPTS->language, v->value, sizeof(CLINE_OPTS->language));
				continue;
			}
		} else if (!strcasecmp(v->name, "accountcode")) {
			if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
				ast_copy_string(CLINE_OPTS->accountcode, v->value, sizeof(CLINE_OPTS->accountcode));
				continue;
			}
		} else if (!strcasecmp(v->name, "mohinterpret") || !strcasecmp(v->name, "musiconhold")) {
			if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
				ast_copy_string(CLINE_OPTS->mohinterpret, v->value, sizeof(CLINE_OPTS->mohinterpret));
				continue;
			}
		} else if (!strcasecmp(v->name, "mohsuggest")) {
			if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
				ast_copy_string(CLINE_OPTS->mohsuggest, v->value, sizeof(CLINE_OPTS->mohsuggest));
				continue;
			}
		} else if (!strcasecmp(v->name, "callgroup")) {
			if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
				CLINE_OPTS->callgroup = ast_get_group(v->value);
				continue;
			}
		} else if (!strcasecmp(v->name, "pickupgroup")) {
			if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
				CLINE_OPTS->pickupgroup = ast_get_group(v->value);
				continue;
			}
		} else if (!strcasecmp(v->name, "namedcallgroup")) {
			if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
				CLINE_OPTS->named_callgroups = ast_get_namedgroups(v->value);
				continue;
			}
		} else if (!strcasecmp(v->name, "namedpickupgroup")) {
			if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
				CLINE_OPTS->named_pickupgroups = ast_get_namedgroups(v->value);
				continue;
			}
		} else if (!strcasecmp(v->name, "immediate")) {
			if (type & (TYPE_DEF_DEVICE | TYPE_DEVICE | TYPE_DEF_LINE | TYPE_LINE)) {
				CLINE_OPTS->immediate = ast_true(v->value);
				continue;
			}
		} else if (!strcasecmp(v->name, "cancallforward")) {
			if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
				CLINE_OPTS->cancallforward = ast_true(v->value);
				continue;
			}
		} else if (!strcasecmp(v->name, "callfwdtimeout")) {
			if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
				CLINE_OPTS->callfwdtimeout = atoi(v->value);
				continue;
			}
		} else if (!strcasecmp(v->name, "mailbox")) {
			if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
				ast_copy_string(CLINE_OPTS->mailbox, v->value, sizeof(CLINE_OPTS->mailbox));
				continue;
			}
		} else if ( !strcasecmp(v->name, "parkinglot")) {
			if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
				ast_copy_string(CLINE_OPTS->parkinglot, v->value, sizeof(CLINE_OPTS->parkinglot));
				continue;
			}
		} else if (!strcasecmp(v->name, "hasvoicemail")) {
			if (type & (TYPE_LINE)) {
				if (ast_true(v->value) && ast_strlen_zero(CLINE->mailbox)) {
					/*
					 * hasvoicemail is a users.conf legacy voicemail enable method.
					 * hasvoicemail is only going to work for app_voicemail mailboxes.
					 */
					if (strchr(CLINE->name, '@')) {
						ast_copy_string(CLINE->mailbox, CLINE->name, sizeof(CLINE->mailbox));
					} else {
						snprintf(CLINE->mailbox, sizeof(CLINE->mailbox), "%s@default",
							CLINE->name);
					}
				}
				continue;
			}
		} else if (!strcasecmp(v->name, "threewaycalling")) {
			if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
				CLINE_OPTS->threewaycalling = ast_true(v->value);
				continue;
			}
		} else if (!strcasecmp(v->name, "setvar")) {
			if (type & (TYPE_LINE)) {
				CLINE->chanvars = add_var(v->value, CLINE->chanvars);
				continue;
			}
		} else if (!strcasecmp(v->name, "earlyrtp")) {
			if (type & (TYPE_DEF_DEVICE | TYPE_DEVICE)) {
				CDEV_OPTS->earlyrtp = ast_true(v->value);
				continue;
			}
		} else if (!strcasecmp(v->name, "host")) {
			if (type & (TYPE_DEVICE)) {
				struct ast_sockaddr CDEV_addr_tmp;

				CDEV_addr_tmp.ss.ss_family = AF_INET;
				if (ast_get_ip(&CDEV_addr_tmp, v->value)) {
					ast_log(LOG_WARNING, "Bad IP '%s' at line %d.\n", v->value, v->lineno);
				}
				ast_sockaddr_to_sin(&CDEV_addr_tmp,
						    &CDEV->addr);
				continue;
			}
		} else if (!strcasecmp(v->name, "port")) {
			if (type & (TYPE_DEF_DEVICE)) {
				CDEV->addr.sin_port = htons(atoi(v->value));
				continue;
			}
		} else if (!strcasecmp(v->name, "device")) {
			if (type & (TYPE_DEVICE)) {
				ast_copy_string(CDEV_OPTS->id, v->value, sizeof(CDEV_OPTS->id));
				continue;
			}
		} else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
			if (type & (TYPE_DEVICE)) {
				CDEV->ha = ast_append_ha(v->name, v->value, CDEV->ha, NULL);
				continue;
			}
		} else if (!strcasecmp(v->name, "allow")) {
			if (type & (TYPE_DEF_DEVICE | TYPE_DEVICE)) {
				ast_format_cap_update_by_allow_disallow(CDEV->confcap, v->value, 1);
				continue;
			}
			if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
				ast_format_cap_update_by_allow_disallow(CLINE->confcap, v->value, 1);
				continue;
			}
		} else if (!strcasecmp(v->name, "disallow")) {
			if (type & (TYPE_DEF_DEVICE | TYPE_DEVICE)) {
				ast_format_cap_update_by_allow_disallow(CDEV->confcap, v->value, 0);
				continue;
			}
			if (type & (TYPE_DEF_LINE | TYPE_LINE)) {
				ast_format_cap_update_by_allow_disallow(CLINE->confcap, v->value, 0);
				continue;
			}
		} else if (!strcasecmp(v->name, "version")) {
			if (type & (TYPE_DEF_DEVICE | TYPE_DEVICE)) {
				ast_copy_string(CDEV_OPTS->version_id, v->value, sizeof(CDEV_OPTS->version_id));
				continue;
			}
		} else if (!strcasecmp(v->name, "line")) {
			if (type & (TYPE_DEVICE)) {
				struct skinny_line *l;
				AST_LIST_TRAVERSE(&lines, l, all) {
					if (!strcasecmp(v->value, l->name) && !l->prune) {

						/* FIXME: temp solution about line conflicts */
						struct skinny_device *d;
						struct skinny_line *l2;
						int lineinuse = 0;
						AST_LIST_TRAVERSE(&devices, d, list) {
							AST_LIST_TRAVERSE(&d->lines, l2, list) {
								if (l2 == l && strcasecmp(d->id, CDEV->id)) {
									ast_log(LOG_WARNING, "Line %s already used by %s. Not connecting to %s.\n", l->name, d->name, CDEV->name);
									lineinuse++;
								}
							}
						}
						if (!lineinuse) {
							if (!AST_LIST_FIRST(&CDEV->lines)) {
								CDEV->activeline = l;
							}
							lineInstance++;
							AST_LIST_INSERT_HEAD(&CDEV->lines, l, list);
							l->device = CDEV;
						}
						break;
					}
				}
				continue;
			}
		} else if (!strcasecmp(v->name, "subline")) {
			if (type & (TYPE_LINE)) {
				struct skinny_subline *subline;
				struct skinny_container *container;
				char buf[256];
				char *stringp = buf, *exten, *stname, *context;

				if (!(subline = ast_calloc(1, sizeof(*subline)))) {
					ast_log(LOG_WARNING, "Unable to allocate memory for subline %s. Ignoring subline.\n", v->value);
					continue;
				}
				if (!(container = ast_calloc(1, sizeof(*container)))) {
					ast_log(LOG_WARNING, "Unable to allocate memory for subline %s container. Ignoring subline.\n", v->value);
					ast_free(subline);
					continue;
				}

				ast_copy_string(buf, v->value, sizeof(buf));
				exten = strsep(&stringp, "@");
				ast_copy_string(subline->exten, ast_strip(exten), sizeof(subline->exten));
				stname = strsep(&exten, "_");
				ast_copy_string(subline->stname, ast_strip(stname), sizeof(subline->stname));
				ast_copy_string(subline->lnname, ast_strip(exten), sizeof(subline->lnname));
				context = strsep(&stringp, ",");
				ast_copy_string(subline->name, ast_strip(stringp), sizeof(subline->name));
				ast_copy_string(subline->context, ast_strip(context), sizeof(subline->context));

				subline->line = CLINE;
				subline->sub = NULL;

				container->type = SKINNY_SUBLINECONTAINER;
				container->data = subline;
				subline->container = container;
				AST_LIST_INSERT_HEAD(&CLINE->sublines, subline, list);
				continue;
			}
		} else if (!strcasecmp(v->name, "dialoutcontext")) {
			if (type & (TYPE_LINE)) {
				ast_copy_string(CLINE_OPTS->dialoutcontext, v->value, sizeof(CLINE_OPTS->dialoutcontext));
				continue;
			}
		} else if (!strcasecmp(v->name, "dialoutexten")) {
			if (type & (TYPE_LINE)) {
				ast_copy_string(CLINE_OPTS->dialoutexten, v->value, sizeof(CLINE_OPTS->dialoutexten));
				continue;
			}
		} else if (!strcasecmp(v->name, "speeddial")) {
			if (type & (TYPE_DEVICE)) {
				struct skinny_speeddial *sd;
				struct skinny_container *container;
				char buf[256];
				char *stringp = buf, *exten, *context, *label;

				if (!(sd = ast_calloc(1, sizeof(*sd)))) {
					ast_log(LOG_WARNING, "Unable to allocate memory for speeddial %s. Ignoring speeddial.\n", v->name);
					continue;
				}
				if (!(container = ast_calloc(1, sizeof(*container)))) {
					ast_log(LOG_WARNING, "Unable to allocate memory for speeddial %s container. Ignoring speeddial.\n", v->name);
					ast_free(sd);
					continue;
				}

				ast_copy_string(buf, v->value, sizeof(buf));
				exten = strsep(&stringp, ",");
				if ((context = strchr(exten, '@'))) {
					*context++ = '\0';
				}
				label = stringp;
				ast_mutex_init(&sd->lock);
				ast_copy_string(sd->exten, exten, sizeof(sd->exten));
				if (!ast_strlen_zero(context)) {
					sd->isHint = 1;
					sd->instance = lineInstance++;
					ast_copy_string(sd->context, context, sizeof(sd->context));
				} else {
					sd->isHint = 0;
					sd->instance = speeddialInstance++;
					sd->context[0] = '\0';
				}
				ast_copy_string(sd->label, S_OR(label, exten), sizeof(sd->label));
				sd->parent = CDEV;
				container->type = SKINNY_SDCONTAINER;
				container->data = sd;
				sd->container = container;
				AST_LIST_INSERT_HEAD(&CDEV->speeddials, sd, list);
				continue;
			}
		} else if (!strcasecmp(v->name, "serviceurl")) {
			if (type & (TYPE_DEVICE)) {
				struct skinny_serviceurl *surl;
				char buf[256];
				char *stringp = buf, *serviceUrl, *displayName;
				if (!(surl = ast_calloc(1, sizeof(*surl)))) {
					ast_log(LOG_WARNING, "Unable to allocate memory for serviceurl %s. Ignoring service URL.\n", v->name);
					continue;
				}
				ast_copy_string(buf, v->value, sizeof(buf));
				displayName = strsep(&stringp, ",");
				if (stringp) {
					serviceUrl = stringp;
					ast_copy_string(surl->url, ast_strip(serviceUrl), sizeof(surl->url));
					ast_copy_string(surl->displayName, displayName, sizeof(surl->displayName));
					surl->instance = serviceUrlInstance++;
					surl->device = CDEV;
					AST_LIST_INSERT_HEAD(&CDEV->serviceurls, surl, list);
				} else {
					ast_free(surl);
					ast_log(LOG_WARNING, "Badly formed option for service URL in %s. Ignoring service URL.\n", v->name);
				}
				continue;
			}
		} else if (!strcasecmp(v->name, "addon")) {
			if (type & (TYPE_DEVICE)) {
				struct skinny_addon *a;
				if (!(a = ast_calloc(1, sizeof(*a)))) {
					ast_log(LOG_WARNING, "Unable to allocate memory for addon %s. Ignoring addon.\n", v->name);
					continue;
				} else {
					ast_mutex_init(&a->lock);
					ast_copy_string(a->type, v->value, sizeof(a->type));
					AST_LIST_INSERT_HEAD(&CDEV->addons, a, list);
				}
				continue;
			}

		} else {
			ast_log(LOG_WARNING, "Don't know keyword '%s' at line %d\n", v->name, v->lineno);
			continue;
		}
		ast_log(LOG_WARNING, "Invalid category used: %s at line %d\n", v->name, v->lineno);
	}
}

static struct skinny_line *config_line(const char *lname, struct ast_variable *v)
{
	struct skinny_line *l, *temp;
	int update = 0;
	struct skinny_container *container;

	ast_log(LOG_NOTICE, "Configuring skinny line %s.\n", lname);

	/* We find the old line and remove it just before the new
	   line is created */
	AST_LIST_LOCK(&lines);
	AST_LIST_TRAVERSE(&lines, temp, all) {
		if (!strcasecmp(lname, temp->name) && temp->prune) {
			update = 1;
			break;
		}
	}

	if (!(l = skinny_line_alloc())) {
		ast_verb(1, "Unable to allocate memory for line %s.\n", lname);
		AST_LIST_UNLOCK(&lines);
		return NULL;
	}
	if (!(container = ast_calloc(1, sizeof(*container)))) {
		ast_log(LOG_WARNING, "Unable to allocate memory for line %s container.\n", lname);
		skinny_line_destroy(l);
		AST_LIST_UNLOCK(&lines);
		return NULL;
	}

	container->type = SKINNY_LINECONTAINER;
	container->data = l;
	l->container = container;

	memcpy(l, default_line, sizeof(*default_line));
	ast_mutex_init(&l->lock);
	ast_copy_string(l->name, lname, sizeof(l->name));
	ast_format_cap_append_from_cap(l->confcap, default_cap, AST_MEDIA_TYPE_UNKNOWN);
	AST_LIST_INSERT_TAIL(&lines, l, all);

	ast_mutex_lock(&l->lock);
	AST_LIST_UNLOCK(&lines);

	config_parse_variables(TYPE_LINE, l, v);

	if (!ast_strlen_zero(l->mailbox)) {
		struct stasis_topic *mailbox_specific_topic;

		ast_verb(3, "Setting mailbox '%s' on line %s\n", l->mailbox, l->name);

		mailbox_specific_topic = ast_mwi_topic(l->mailbox);
		if (mailbox_specific_topic) {
			l->mwi_event_sub = stasis_subscribe_pool(mailbox_specific_topic, mwi_event_cb, l);
		}
	}

	if (!ast_strlen_zero(vmexten) && ast_strlen_zero(l->vmexten)) {
		ast_copy_string(l->vmexten, vmexten, sizeof(l->vmexten));
	}

	ast_mutex_unlock(&l->lock);

	/* We do not want to unlink or free the line yet, it needs
	   to be available to detect a device reconfig when we load the
	   devices.  Old lines will be pruned after the reload completes */

	ast_verb(3, "%s config for line '%s'\n", update ? "Updated" : (skinnyreload ? "Reloaded" : "Created"), l->name);

	return l;
}

static struct skinny_device *config_device(const char *dname, struct ast_variable *v)
{
	struct skinny_device *d, *temp;
	struct skinny_line *l, *ltemp;
	struct skinny_subchannel *sub;
	int update = 0;

	ast_log(LOG_NOTICE, "Configuring skinny device %s.\n", dname);

	AST_LIST_LOCK(&devices);
	AST_LIST_TRAVERSE(&devices, temp, list) {
		if (!strcasecmp(dname, temp->name) && temp->prune) {
			update = 1;
			break;
		}
	}

	if (!(d = skinny_device_alloc(dname))) {
		ast_verb(1, "Unable to allocate memory for device %s.\n", dname);
		AST_LIST_UNLOCK(&devices);
		return NULL;
	}
	memcpy(d, default_device, sizeof(*default_device));
	ast_mutex_init(&d->lock);
	ast_copy_string(d->name, dname, sizeof(d->name));
	ast_format_cap_append_from_cap(d->confcap, default_cap, AST_MEDIA_TYPE_UNKNOWN);
	AST_LIST_INSERT_TAIL(&devices, d, list);

	ast_mutex_lock(&d->lock);
	AST_LIST_UNLOCK(&devices);

	config_parse_variables(TYPE_DEVICE, d, v);

	if (!AST_LIST_FIRST(&d->lines)) {
		ast_log(LOG_ERROR, "A Skinny device must have at least one line!\n");
		ast_mutex_unlock(&d->lock);
		return NULL;
	}
	if (/*d->addr.sin_addr.s_addr && */!ntohs(d->addr.sin_port)) {
		d->addr.sin_port = htons(DEFAULT_SKINNY_PORT);
	}

	if (skinnyreload){
		AST_LIST_LOCK(&devices);
		AST_LIST_TRAVERSE(&devices, temp, list) {
			if (strcasecmp(d->id, temp->id) || !temp->prune || !temp->session) {
				continue;
			}
			ast_mutex_lock(&d->lock);
			d->session = temp->session;
			d->session->device = d;
			d->hookstate = temp->hookstate;

			AST_LIST_LOCK(&d->lines);
			AST_LIST_TRAVERSE(&d->lines, l, list){

				AST_LIST_LOCK(&temp->lines);
				AST_LIST_TRAVERSE(&temp->lines, ltemp, list) {
					if (strcasecmp(l->name, ltemp->name)) {
						continue;
					}
					ast_mutex_lock(&ltemp->lock);
					l->instance = ltemp->instance;
					if (l == temp->activeline) {
						d->activeline = l;
					}
					if (!AST_LIST_EMPTY(&ltemp->sub)) {
						ast_mutex_lock(&l->lock);
						l->sub = ltemp->sub;
						l->activesub = ltemp->activesub;
						AST_LIST_TRAVERSE(&l->sub, sub, list) {
							sub->line = l;
						}
						ast_mutex_unlock(&l->lock);
					}
					ast_mutex_unlock(&ltemp->lock);
				}
				AST_LIST_UNLOCK(&temp->lines);
			}
			AST_LIST_UNLOCK(&d->lines);
			ast_mutex_unlock(&d->lock);
		}
		AST_LIST_UNLOCK(&devices);
	}

	ast_mutex_unlock(&d->lock);

	ast_verb(3, "%s config for device '%s'\n", update ? "Updated" : (skinnyreload ? "Reloaded" : "Created"), d->name);

	return d;

}

static int config_load(void)
{
	int on = 1;
	struct ast_config *cfg;
	char *cat;
	int oldport = ntohs(bindaddr.sin_port);
	struct ast_flags config_flags = { 0 };

	ast_log(LOG_NOTICE, "Configuring skinny from %s\n", config);

	if (gethostname(ourhost, sizeof(ourhost))) {
		ast_log(LOG_WARNING, "Unable to get hostname, Skinny disabled.\n");
		return 0;
	}
	cfg = ast_config_load(config, config_flags);

	/* We *must* have a config file otherwise stop immediately */
	if (!cfg || cfg == CONFIG_STATUS_FILEINVALID) {
		ast_log(LOG_NOTICE, "Unable to load config %s, Skinny disabled.\n", config);
		return -1;
	}

	memset(&bindaddr, 0, sizeof(bindaddr));
	immed_dialchar = '\0';
	memset(&vmexten, '\0', sizeof(vmexten));


	/* Copy the default jb config over global_jbconf */
	memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));

	/* load the general section */
	cat = ast_category_browse(cfg, "general");
	config_parse_variables(TYPE_GENERAL, NULL, ast_variable_browse(cfg, "general"));

	if (ntohl(bindaddr.sin_addr.s_addr)) {
		__ourip = bindaddr.sin_addr;
	} else {
		hp = ast_gethostbyname(ourhost, &ahp);
		if (!hp) {
			ast_log(LOG_WARNING, "Unable to get our IP address, Skinny disabled\n");
			ast_config_destroy(cfg);
			return 0;
		}
		memcpy(&__ourip, hp->h_addr, sizeof(__ourip));
	}
	if (!ntohs(bindaddr.sin_port)) {
		bindaddr.sin_port = htons(DEFAULT_SKINNY_PORT);
	}
	bindaddr.sin_family = AF_INET;

	/* load the lines sections */
	config_parse_variables(TYPE_DEF_LINE, default_line, ast_variable_browse(cfg, "lines"));
	cat = ast_category_browse(cfg, "lines");
	while (cat && strcasecmp(cat, "general") && strcasecmp(cat, "devices")) {
		config_line(cat, ast_variable_browse(cfg, cat));
		cat = ast_category_browse(cfg, cat);
	}

	/* load the devices sections */
	config_parse_variables(TYPE_DEF_DEVICE, default_device, ast_variable_browse(cfg, "devices"));
	cat = ast_category_browse(cfg, "devices");
	while (cat && strcasecmp(cat, "general") && strcasecmp(cat, "lines")) {
		config_device(cat, ast_variable_browse(cfg, cat));
		cat = ast_category_browse(cfg, cat);
	}

	ast_mutex_lock(&netlock);
	if ((skinnysock > -1) && (ntohs(bindaddr.sin_port) != oldport)) {
		close(skinnysock);
		skinnysock = -1;
	}
	if (skinnysock < 0) {
		skinnysock = socket(AF_INET, SOCK_STREAM, 0);
		if(setsockopt(skinnysock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) {
			ast_log(LOG_ERROR, "Set Socket Options failed: errno %d, %s\n", errno, strerror(errno));
			ast_config_destroy(cfg);
			ast_mutex_unlock(&netlock);
			return 0;
		}
		if (skinnysock < 0) {
			ast_log(LOG_WARNING, "Unable to create Skinny socket: %s\n", strerror(errno));
		} else {
			if (bind(skinnysock, (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(skinnysock);
				skinnysock = -1;
				ast_config_destroy(cfg);
				ast_mutex_unlock(&netlock);
				return 0;
			}
			if (listen(skinnysock, DEFAULT_SKINNY_BACKLOG)) {
					ast_log(LOG_WARNING, "Failed to start listening to %s:%d: %s\n",
						ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
							strerror(errno));
					close(skinnysock);
					skinnysock = -1;
					ast_config_destroy(cfg);
					ast_mutex_unlock(&netlock);
					ret