File: sal_eXosip2.c

package info (click to toggle)
linphone 3.6.1-2.4
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 24,948 kB
  • ctags: 15,761
  • sloc: ansic: 93,315; sh: 11,953; cpp: 9,827; objc: 2,530; makefile: 1,332; java: 1,050; asm: 179; xml: 93; python: 84; perl: 50
file content (3422 lines) | stat: -rw-r--r-- 96,659 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
/*
linphone
Copyright (C) 2010  Simon MORLAT (simon.morlat@free.fr)

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "sal_eXosip2.h"
#include "offeranswer.h"

#ifdef ANDROID
// Necessary to make it linked
static void for_linker() { eXosip_transport_hook_register(NULL); }
#endif
static bool_t call_failure(Sal *sal, eXosip_event_t *ev);

static void text_received(Sal *sal, eXosip_event_t *ev);

static void masquerade_via(osip_message_t *msg, const char *ip, const char *port);
static bool_t fix_message_contact(SalOp *op, osip_message_t *request,osip_message_t *last_answer, bool_t expire_last_contact);
static void update_contact_from_response(SalOp *op, osip_message_t *response);


void _osip_list_set_empty(osip_list_t *l, void (*freefunc)(void*)){
	void *data;
	while(!osip_list_eol(l,0)) {
		data=osip_list_get(l,0);
		osip_list_remove(l,0);
		if (data) freefunc(data);
	}
}

void sal_get_default_local_ip(Sal *sal, int address_family,char *ip, size_t iplen){
#ifdef HAVE_STRUCT_EXOSIP_T
	if (eXosip_guess_localip(sal->excontext, address_family, ip, iplen) < 0){
#else
	if (eXosip_guess_localip(address_family,ip,iplen)<0){
#endif
		/*default to something */
		strncpy(ip,address_family==AF_INET6 ? "::1" : "127.0.0.1",iplen);
		ms_error("Could not find default routable ip address !");
	}
}

static SalOp * sal_find_call(Sal *sal, int cid){
	const MSList *elem;
	SalOp *op;
	for(elem=sal->calls;elem!=NULL;elem=elem->next){
		op=(SalOp*)elem->data;
		if (op->cid==cid) return op;
	}
	return NULL;
}

static void sal_add_call(Sal *sal, SalOp *op){
	sal->calls=ms_list_append(sal->calls,op);
}

static void sal_remove_call(Sal *sal, SalOp *op){
	sal->calls=ms_list_remove(sal->calls, op);
}

static SalOp * sal_find_register(Sal *sal, int rid){
	const MSList *elem;
	SalOp *op;
	for(elem=sal->registers;elem!=NULL;elem=elem->next){
		op=(SalOp*)elem->data;
		if (op->rid==rid) return op;
	}
	return NULL;
}

static void sal_add_register(Sal *sal, SalOp *op){
	sal->registers=ms_list_append(sal->registers,op);
}

static void sal_remove_register(Sal *sal, int rid){
	MSList *elem;
	SalOp *op;
	for(elem=sal->registers;elem!=NULL;elem=elem->next){
		op=(SalOp*)elem->data;
		if (op->rid==rid) {
			sal->registers=ms_list_remove_link(sal->registers,elem);
			return;
		}
	}
}

static SalOp * sal_find_other(Sal *sal, osip_message_t *message){
	const MSList *elem;
	SalOp *op;
	osip_call_id_t *callid=osip_message_get_call_id(message);
	if (callid==NULL) {
		ms_error("There is no call-id in this message !");
		return NULL;
	}
	for(elem=sal->other_transactions;elem!=NULL;elem=elem->next){
		op=(SalOp*)elem->data;
		if (osip_call_id_match(callid,op->call_id)==0) return op;
	}
	return NULL;
}

void sal_add_other(Sal *sal, SalOp *op, osip_message_t *request){
	osip_call_id_t *callid=osip_message_get_call_id(request);
	if (callid==NULL) {
		ms_error("There is no call id in the request !");
		return;
	}
	osip_call_id_clone(callid,&op->call_id);
	sal->other_transactions=ms_list_append(sal->other_transactions,op);
}

static void sal_remove_other(Sal *sal, SalOp *op){
	sal->other_transactions=ms_list_remove(sal->other_transactions,op);
}


static void sal_add_pending_auth(Sal *sal, SalOp *op){
	sal->pending_auths=ms_list_append(sal->pending_auths,op);
}


static void sal_remove_pending_auth(Sal *sal, SalOp *op){
	sal->pending_auths=ms_list_remove(sal->pending_auths,op);
}

void sal_exosip_fix_route(SalOp *op){
	if (sal_op_get_route(op)!=NULL){
		osip_route_t *rt=NULL;
		osip_uri_param_t *lr_param=NULL;
		
		osip_route_init(&rt);
		if (osip_route_parse(rt,sal_op_get_route(op))<0){
			ms_warning("Bad route  %s!",sal_op_get_route(op));
			sal_op_set_route(op,NULL);
		}else{
			/* check if the lr parameter is set , if not add it */
			osip_uri_uparam_get_byname(rt->url, "lr", &lr_param);
		  	if (lr_param==NULL){
				char *tmproute;
				osip_uri_uparam_add(rt->url,osip_strdup("lr"),NULL);
				osip_route_to_str(rt,&tmproute);
				sal_op_set_route(op,tmproute);
				osip_free(tmproute);
			}
		}
		osip_route_free(rt);
	}
}

SalOp * sal_op_new(Sal *sal){
	SalOp *op=ms_new0(SalOp,1);
	__sal_op_init(op,sal);
	op->cid=op->did=op->tid=op->rid=op->nid=op->sid=-1;
	op->result=NULL;
	op->supports_session_timers=FALSE;
	op->sdp_offering=TRUE;
	op->pending_auth=NULL;
	op->sdp_answer=NULL;
	op->reinvite=FALSE;
	op->call_id=NULL;
	op->replaces=NULL;
	op->referred_by=NULL;
	op->masquerade_via=FALSE;
	op->auto_answer_asked=FALSE;
	op->auth_info=NULL;
	op->terminated=FALSE;
	return op;
}

bool_t sal_call_autoanswer_asked(SalOp *op)
{
	return op->auto_answer_asked;
}

void sal_op_release(Sal *ctx, SalOp *op){
	if (op->sdp_answer)
		sdp_message_free(op->sdp_answer);
	if (op->pending_auth)
		eXosip_event_free(op->pending_auth);
	if (op->rid!=-1){
		sal_remove_register(op->base.root,op->rid);
		eXosip_register_remove(ctx->excontext, op->rid);
	}
	if (op->cid!=-1){
		ms_message("Cleaning cid %i",op->cid);
		sal_remove_call(op->base.root,op);
	}
	if (op->sid!=-1){
		sal_remove_out_subscribe(op->base.root,op);
	}
	if (op->nid!=-1){
		sal_remove_in_subscribe(op->base.root,op);
		if (op->call_id)
			osip_call_id_free(op->call_id);
		op->call_id=NULL;
	}
	if (op->pending_auth){
		sal_remove_pending_auth(op->base.root,op);
	}
	if (op->result)
		sal_media_description_unref(op->result);
	if (op->call_id){
		sal_remove_other(op->base.root,op);
		osip_call_id_free(op->call_id);
	}
	if (op->replaces){
		ms_free(op->replaces);
	}
	if (op->referred_by){
		ms_free(op->referred_by);
	}
	if (op->auth_info) {
		sal_auth_info_delete(op->auth_info);
	}
	__sal_op_free(op);
}

static void _osip_trace_func(char *fi, int li, osip_trace_level_t level, char *chfr, va_list ap){
	int ortp_level=ORTP_DEBUG;
	switch(level){
		case OSIP_INFO1:
		case OSIP_INFO2:
		case OSIP_INFO3:
		case OSIP_INFO4:
			ortp_level=ORTP_MESSAGE;
			break;
		case OSIP_WARNING:
			ortp_level=ORTP_WARNING;
			break;
		case OSIP_ERROR:
		case OSIP_BUG:
			ortp_level=ORTP_ERROR;
			break;
		case OSIP_FATAL:
			ortp_level=ORTP_FATAL;
			break;
		case END_TRACE_LEVEL:
			break;
	}
	if (ortp_log_level_enabled(level)){
		int len=strlen(chfr);
		char *chfrdup=ortp_strdup(chfr);
		/*need to remove endline*/
		if (len>1){
			if (chfrdup[len-1]=='\n')
				chfrdup[len-1]='\0';
			if (chfrdup[len-2]=='\r')
				chfrdup[len-2]='\0';
		}
		ortp_logv(ortp_level,chfrdup,ap);
		ortp_free(chfrdup);
	}
}


Sal * sal_init(){
	static bool_t firsttime=TRUE;
	Sal *sal;
	if (firsttime){
		osip_trace_initialize_func (OSIP_INFO4,&_osip_trace_func);
		firsttime=FALSE;
	}
	sal=ms_new0(Sal,1);
#ifdef HAVE_STRUCT_EXOSIP_T
	sal->excontext = eXosip_malloc();
	eXosip_init(sal->excontext);
	/* order with ms_new0 changed, maybe free(sal) on error? */
#else
	eXosip_init();
#endif
	sal->keepalive_period=30;
	sal->double_reg=TRUE;
	sal->use_rports=TRUE;
	sal->use_101=TRUE;
	sal->reuse_authorization=FALSE;
	sal->rootCa = 0;
	sal->verify_server_certs=TRUE;
	sal->verify_server_cn=TRUE;
	sal->expire_old_contact=FALSE;
	sal->add_dates=FALSE;
	sal->dscp=-1;
	return sal;
}

void sal_uninit(Sal* sal){
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_quit(sal->excontext);
	free(sal->excontext);
#else
	eXosip_quit();
#endif
	if (sal->rootCa)
		ms_free(sal->rootCa);
	ms_free(sal);
}

void sal_set_user_pointer(Sal *sal, void *user_data){
	sal->up=user_data;
}

void *sal_get_user_pointer(const Sal *sal){
	return sal->up;
}

static void unimplemented_stub(){
	ms_warning("Unimplemented SAL callback");
}

void sal_set_callbacks(Sal *ctx, const SalCallbacks *cbs){
	memcpy(&ctx->callbacks,cbs,sizeof(*cbs));
	if (ctx->callbacks.call_received==NULL) 
		ctx->callbacks.call_received=(SalOnCallReceived)unimplemented_stub;
	if (ctx->callbacks.call_ringing==NULL) 
		ctx->callbacks.call_ringing=(SalOnCallRinging)unimplemented_stub;
	if (ctx->callbacks.call_accepted==NULL) 
		ctx->callbacks.call_accepted=(SalOnCallAccepted)unimplemented_stub;
	if (ctx->callbacks.call_failure==NULL) 
		ctx->callbacks.call_failure=(SalOnCallFailure)unimplemented_stub;
	if (ctx->callbacks.call_terminated==NULL) 
		ctx->callbacks.call_terminated=(SalOnCallTerminated)unimplemented_stub;
	if (ctx->callbacks.call_released==NULL)
		ctx->callbacks.call_released=(SalOnCallReleased)unimplemented_stub;
	if (ctx->callbacks.call_updating==NULL) 
		ctx->callbacks.call_updating=(SalOnCallUpdating)unimplemented_stub;
	if (ctx->callbacks.auth_requested==NULL) 
		ctx->callbacks.auth_requested=(SalOnAuthRequested)unimplemented_stub;
	if (ctx->callbacks.auth_success==NULL) 
		ctx->callbacks.auth_success=(SalOnAuthSuccess)unimplemented_stub;
	if (ctx->callbacks.register_success==NULL) 
		ctx->callbacks.register_success=(SalOnRegisterSuccess)unimplemented_stub;
	if (ctx->callbacks.register_failure==NULL) 
		ctx->callbacks.register_failure=(SalOnRegisterFailure)unimplemented_stub;
	if (ctx->callbacks.dtmf_received==NULL) 
		ctx->callbacks.dtmf_received=(SalOnDtmfReceived)unimplemented_stub;
	if (ctx->callbacks.notify==NULL)
		ctx->callbacks.notify=(SalOnNotify)unimplemented_stub;
	if (ctx->callbacks.notify_presence==NULL)
		ctx->callbacks.notify_presence=(SalOnNotifyPresence)unimplemented_stub;
	if (ctx->callbacks.subscribe_received==NULL)
		ctx->callbacks.subscribe_received=(SalOnSubscribeReceived)unimplemented_stub;
	if (ctx->callbacks.text_received==NULL)
		ctx->callbacks.text_received=(SalOnTextReceived)unimplemented_stub;
	if (ctx->callbacks.ping_reply==NULL)
		ctx->callbacks.ping_reply=(SalOnPingReply)unimplemented_stub;
}

int sal_unlisten_ports(Sal *ctx){
	if (ctx->running){
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_quit(ctx->excontext);
#else
		eXosip_quit();
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_init(ctx->excontext);
#else
		eXosip_init();
#endif
		ctx->running=FALSE;
	}
	return 0;
}

int sal_reset_transports(Sal *ctx){
#ifdef HAVE_EXOSIP_RESET_TRANSPORTS
	if (ctx->running){
		ms_message("Exosip transports reset.");
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_reset_transports(ctx->excontext);
#else
		eXosip_reset_transports();
#endif
	}
	return 0;
#else /* HAVE_EXOSIP_RESET_TRANSPORTS */
	ms_warning("sal_reset_transports() not implemented in this version.");
	return -1;
#endif /* HAVE_EXOSIP_RESET_TRANSPORTS */
}


static void set_tls_options(Sal *ctx){
	if (ctx->rootCa) {
		eXosip_tls_ctx_t tlsCtx;
		memset(&tlsCtx, 0, sizeof(tlsCtx));
		snprintf(tlsCtx.root_ca_cert, sizeof(tlsCtx.client.cert), "%s", ctx->rootCa);
#ifdef EXOSIP_OPT_SET_TLS_CERTIFICATES_INFO
		eXosip_set_option(ctx->excontext, EXOSIP_OPT_SET_TLS_CERTIFICATES_INFO, &tlsCtx);
#else
		eXosip_set_tls_ctx(&tlsCtx);
#endif
	}
#ifdef EXOSIP_OPT_SET_TLS_VERIFY_CERTIFICATE
	eXosip_set_option(ctx->excontext, EXOSIP_OPT_SET_TLS_VERIFY_CERTIFICATE,
			  &ctx->verify_server_certs); 
#elif defined HAVE_EXOSIP_TLS_VERIFY_CERTIFICATE
	eXosip_tls_verify_certificate(ctx->verify_server_certs);
#endif
#ifdef HAVE_EXOSIP_TLS_VERIFY_CN
	eXosip_tls_verify_cn(ctx->verify_server_cn);
#endif
}

void sal_set_dscp(Sal *ctx, int dscp){
	ctx->dscp=dscp;
	if (dscp!=-1) {
#ifdef EXOSIP_OPT_SET_DSCP
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_set_option(ctx->excontext, EXOSIP_OPT_SET_DSCP, &ctx->dscp);
#else
		eXosip_set_option(EXOSIP_OPT_SET_DSCP,&ctx->dscp);
#endif
#endif /* EXOSIP_OPT_SET_DSCP */
        }
}

int sal_listen_port(Sal *ctx, const char *addr, int port, SalTransport tr, int is_secure){
	int err;
	bool_t ipv6;
	int proto=IPPROTO_UDP;
	int keepalive = ctx->keepalive_period;

	ctx->transport = tr;
	switch (tr) {
	case SalTransportUDP:
		proto=IPPROTO_UDP;
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_set_option (ctx->excontext, EXOSIP_OPT_UDP_KEEP_ALIVE, &keepalive);
#else
		eXosip_set_option (EXOSIP_OPT_UDP_KEEP_ALIVE, &keepalive);
#endif
		break;
	case SalTransportTCP:
	case SalTransportTLS:
		proto= IPPROTO_TCP;
		if (!ctx->tcp_tls_keepalive) keepalive=-1;
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_set_option (ctx->excontext, EXOSIP_OPT_UDP_KEEP_ALIVE, &keepalive);
#else
		eXosip_set_option (EXOSIP_OPT_UDP_KEEP_ALIVE,&keepalive);
#endif
		set_tls_options(ctx);
		break;
	default:
		ms_warning("unexpected proto, using datagram");
	}
	/*see if it looks like an IPv6 address*/
	int use_rports = ctx->use_rports; // Copy char to int to avoid bad alignment
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_set_option(ctx->excontext, EXOSIP_OPT_USE_RPORT, &use_rports);
#else
	eXosip_set_option(EXOSIP_OPT_USE_RPORT,&use_rports);
#endif
#ifdef EXOSIP_OPT_DONT_SEND_101
	int dont_use_101 = !ctx->use_101; // Copy char to int to avoid bad alignment
	eXosip_set_option(EXOSIP_OPT_DONT_SEND_101,&dont_use_101);
#endif
	sal_set_dscp(ctx,ctx->dscp);
	sal_use_dates(ctx,ctx->add_dates);

	ipv6=strchr(addr,':')!=NULL;
	eXosip_enable_ipv6(ipv6);

	if (is_secure && tr == SalTransportUDP){
		ms_fatal("SIP over DTLS is not supported yet.");
		return -1;
	}
#ifdef HAVE_STRUCT_EXOSIP_T
	err=eXosip_listen_addr(ctx->excontext, proto, addr, port, ipv6 ?  PF_INET6 : PF_INET, is_secure);
#else
	err=eXosip_listen_addr(proto, addr, port, ipv6 ?  PF_INET6 : PF_INET, is_secure);
#endif
	ctx->running=TRUE;
	return err;
}

ortp_socket_t sal_get_socket(Sal *ctx){
#ifdef HAVE_EXOSIP_GET_SOCKET
	return eXosip_get_socket(IPPROTO_UDP);
#else
	ms_warning("Sorry, eXosip does not have eXosip_get_socket() method");
	return -1;
#endif
}

void sal_set_user_agent(Sal *ctx, const char *user_agent){
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_set_user_agent(ctx->excontext, user_agent);
#else
	eXosip_set_user_agent(user_agent);
#endif
}

void sal_use_session_timers(Sal *ctx, int expires){
	ctx->session_expires=expires;
}

void sal_use_one_matching_codec_policy(Sal *ctx, bool_t one_matching_codec){
	ctx->one_matching_codec=one_matching_codec;
}

MSList *sal_get_pending_auths(Sal *sal){
	return ms_list_copy(sal->pending_auths);
}

void sal_use_double_registrations(Sal *ctx, bool_t enabled){
	ctx->double_reg=enabled;
}

void sal_expire_old_registration_contacts(Sal *ctx, bool_t enabled){
	ctx->expire_old_contact=enabled;
}

void sal_use_dates(Sal *ctx, bool_t enabled){
	ctx->add_dates=enabled;
#ifdef EXOSIP_OPT_REGISTER_WITH_DATE
	{
		int tmp=enabled;
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_set_option(ctx->excontext, EXOSIP_OPT_REGISTER_WITH_DATE, &tmp);
#else
		eXosip_set_option(EXOSIP_OPT_REGISTER_WITH_DATE,&tmp);
#endif
	}
#else /* EXOSIP_OPT_REGISTER_WITH_DATE */
	if (enabled) ms_warning("Exosip does not support EXOSIP_OPT_REGISTER_WITH_DATE option.");
#endif /* EXOSIP_OPT_REGISTER_WITH_DATE */
}

void sal_use_rport(Sal *ctx, bool_t use_rports){
	ctx->use_rports=use_rports;
}
void sal_use_101(Sal *ctx, bool_t use_101){
	ctx->use_101=use_101;
}

void sal_set_root_ca(Sal* ctx, const char* rootCa) {
	if (ctx->rootCa)
		ms_free(ctx->rootCa);
	ctx->rootCa = ms_strdup(rootCa);
	set_tls_options(ctx);
}

const char *sal_get_root_ca(Sal* ctx) {
	return ctx->rootCa;
}

void sal_verify_server_certificates(Sal *ctx, bool_t verify){
	ctx->verify_server_certs=verify;
#ifdef EXOSIP_OPT_SET_TLS_VERIFY_CERTIFICATE
	eXosip_set_option(ctx->excontext, EXOSIP_OPT_SET_TLS_VERIFY_CERTIFICATE, &verify); 
#elif defined HAVE_EXOSIP_TLS_VERIFY_CERTIFICATE
	eXosip_tls_verify_certificate(verify);
#endif
}

void sal_verify_server_cn(Sal *ctx, bool_t verify){
	ctx->verify_server_cn=verify;
#ifdef HAVE_EXOSIP_TLS_VERIFY_CN
	eXosip_tls_verify_cn(verify);
#endif
}

static int extract_received_rport(osip_message_t *msg, const char **received, int *rportval,SalTransport* transport){
	osip_via_t *via=NULL;
	osip_generic_param_t *param=NULL;
	const char *rport=NULL;

	*rportval=5060;
	*received=NULL;
	osip_message_get_via(msg,0,&via);
	if (!via) {
		ms_warning("extract_received_rport(): no via.");
		return -1;
	}

	*transport = sal_transport_parse(via->protocol);
	
	if (via->port && via->port[0]!='\0')
		*rportval=atoi(via->port);
	
	osip_via_param_get_byname(via,"rport",&param);
	if (param) {
		rport=param->gvalue;
		if (rport && rport[0]!='\0') *rportval=atoi(rport);
		*received=via->host;
	}
	param=NULL;
	osip_via_param_get_byname(via,"received",&param);
	if (param) *received=param->gvalue;

	if (rport==NULL && *received==NULL){
		ms_warning("extract_received_rport(): no rport and no received parameters.");
		return -1;
	}
	return 0;
}

static void set_sdp(osip_message_t *sip,sdp_message_t *msg){
	int sdplen;
	char clen[10];
	char *sdp=NULL;
	sdp_message_to_str(msg,&sdp);
	sdplen=strlen(sdp);
	snprintf(clen,sizeof(clen),"%i",sdplen);
	osip_message_set_body(sip,sdp,sdplen);
	osip_message_set_content_type(sip,"application/sdp");
	osip_message_set_content_length(sip,clen);
	osip_free(sdp);
}

static void set_sdp_from_desc(osip_message_t *sip, const SalMediaDescription *desc){
	sdp_message_t *msg=media_description_to_sdp(desc);
	if (msg==NULL) {
		ms_error("Fail to print sdp message !");
		return;
	}
	set_sdp(sip,msg);
	sdp_message_free(msg);
}

static void sdp_process(SalOp *h){
	ms_message("Doing SDP offer/answer process of type %s",h->sdp_offering ? "outgoing" : "incoming");
	if (h->result){
		sal_media_description_unref(h->result);
	}
	h->result=sal_media_description_new();
	if (h->sdp_offering){	
		offer_answer_initiate_outgoing(h->base.local_media,h->base.remote_media,h->result);
	}else{
		int i;
		if (h->sdp_answer){
			sdp_message_free(h->sdp_answer);
		}
		offer_answer_initiate_incoming(h->base.local_media,h->base.remote_media,h->result,h->base.root->one_matching_codec);
		h->sdp_answer=media_description_to_sdp(h->result);
		/*once we have generated the SDP answer, we modify the result description for processing by the upper layer.
		 It should contains media parameters constraint from the remote offer, not our response*/
		strcpy(h->result->addr,h->base.remote_media->addr);
		h->result->bandwidth=h->base.remote_media->bandwidth;
		
		for(i=0;i<h->result->n_active_streams;++i){
			strcpy(h->result->streams[i].rtp_addr,h->base.remote_media->streams[i].rtp_addr);
			strcpy(h->result->streams[i].rtcp_addr,h->base.remote_media->streams[i].rtcp_addr);
			h->result->streams[i].ptime=h->base.remote_media->streams[i].ptime;
			h->result->streams[i].bandwidth=h->base.remote_media->streams[i].bandwidth;
			h->result->streams[i].rtp_port=h->base.remote_media->streams[i].rtp_port;
			h->result->streams[i].rtcp_port=h->base.remote_media->streams[i].rtcp_port;
			if (h->result->streams[i].proto == SalProtoRtpSavp) {
				h->result->streams[i].crypto[0] = h->base.remote_media->streams[i].crypto[0];
			}
		}
	}
	
}

int sal_call_is_offerer(const SalOp *h){
	return h->sdp_offering;
}

int sal_call_set_local_media_description(SalOp *h, SalMediaDescription *desc){
	if (desc)
		sal_media_description_ref(desc);
	if (h->base.local_media)
		sal_media_description_unref(h->base.local_media);
	h->base.local_media=desc;
	if (h->base.remote_media){
		/*case of an incoming call where we modify the local capabilities between the time
		 * the call is ringing and it is accepted (for example if you want to accept without video*/
		/*reset the sdp answer so that it is computed again*/
		if (h->sdp_answer){
			sdp_message_free(h->sdp_answer);
			h->sdp_answer=NULL;
		}
	}
	return 0;
}

int sal_call(Sal *ctx, SalOp *h, const char *from, const char *to){
	int err;
	const char *route;
	osip_message_t *invite=NULL;
	osip_call_id_t *callid;
	sal_op_set_from(h,from);
	sal_op_set_to(h,to);
	sal_exosip_fix_route(h);
	
	h->terminated = FALSE;

	route = sal_op_get_route(h);
#ifdef HAVE_STRUCT_EXOSIP_T
	err=eXosip_call_build_initial_invite(ctx->excontext, &invite, to, from, route, "Phone call");
#else
	err=eXosip_call_build_initial_invite(&invite,to,from,route,"Phone call");
#endif
	if (err!=0){
		ms_error("Could not create call. Error %d (from=%s to=%s route=%s)",
				err, from, to, route);
		return -1;
	}
	osip_message_set_allow(invite, "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, NOTIFY, MESSAGE, SUBSCRIBE, INFO");
	if (h->base.contact){
		_osip_list_set_empty(&invite->contacts,(void (*)(void*))osip_contact_free);
		osip_message_set_contact(invite,h->base.contact);
	}
	if (h->base.root->session_expires!=0){
		osip_message_set_header(invite, "Session-expires", "200");
		osip_message_set_supported(invite, "timer");
	}
	sal_exosip_add_custom_headers(invite,h->base.custom_headers);
	if (h->base.local_media){
		h->sdp_offering=TRUE;
		set_sdp_from_desc(invite,h->base.local_media);
	}else h->sdp_offering=FALSE;
	if (h->replaces){
		osip_message_set_header(invite,"Replaces",h->replaces);
		if (h->referred_by)
			osip_message_set_header(invite,"Referred-By",h->referred_by);
	}
	
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_lock(ctx->excontext);
#else
	eXosip_lock();
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
	err=eXosip_call_send_initial_invite(ctx->excontext, invite);
#else
	err=eXosip_call_send_initial_invite(invite);
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_unlock(ctx->excontext);
#else
	eXosip_unlock();
#endif
	h->cid=err;
	if (err<0){
		ms_error("Fail to send invite ! Error code %d", err);
		return -1;
	}else{
		char *tmp=NULL;
		callid=osip_message_get_call_id(invite);
		osip_call_id_to_str(callid,&tmp);
		h->base.call_id=ms_strdup(tmp);
		osip_free(tmp);
		sal_add_call(h->base.root,h);
	}
	return 0;
}

int sal_call_notify_ringing(Sal *ctx, SalOp *h, bool_t early_media){
	osip_message_t *msg;
	
	/*if early media send also 180 and 183 */
	if (early_media){
		msg=NULL;
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_lock(ctx->excontext);
#else
		eXosip_lock();
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_call_build_answer(ctx->excontext, h->tid, 183, &msg);
#else
		eXosip_call_build_answer(h->tid,183,&msg);
#endif
		if (msg){
			sdp_process(h);
			if (h->sdp_answer){
				set_sdp(msg,h->sdp_answer);
				sdp_message_free(h->sdp_answer);
				h->sdp_answer=NULL;
			}
#ifdef HAVE_STRUCT_EXOSIP_T
			eXosip_call_send_answer(ctx->excontext, h->tid, 183, msg);
#else
			eXosip_call_send_answer(h->tid,183,msg);
#endif
		}
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_unlock(ctx->excontext);
#else
		eXosip_unlock();
#endif
	}else{
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_lock(ctx->excontext);
#else
		eXosip_lock();
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_call_send_answer(ctx->excontext, h->tid, 180, NULL);
#else
		eXosip_call_send_answer(h->tid,180,NULL);
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_unlock(ctx->excontext);
#else
		eXosip_unlock();
#endif
	}
	return 0;
}

int sal_call_accept(Sal *ctx, SalOp * h){
	osip_message_t *msg;
	const char *contact=sal_op_get_contact(h);
	/* sends a 200 OK */
#ifdef HAVE_STRUCT_EXOSIP_T
	int err=eXosip_call_build_answer(ctx->excontext, h->tid, 200, &msg);
#else
	int err=eXosip_call_build_answer(h->tid,200,&msg);
#endif
	if (err<0 || msg==NULL){
		ms_error("Fail to build answer for call: err=%i",err);
		return -1;
	}
	if (h->base.root->session_expires!=0){
		if (h->supports_session_timers) osip_message_set_supported(msg, "timer");
	}

	if (contact) {
		_osip_list_set_empty(&msg->contacts,(void (*)(void*))osip_contact_free);
		osip_message_set_contact(msg,contact);
	}
	
	if (h->base.local_media){
		/*this is the case where we received an invite without SDP*/
		if (h->sdp_offering) {
			set_sdp_from_desc(msg,h->base.local_media);
		}else{
			if (h->sdp_answer==NULL) sdp_process(h);
			if (h->sdp_answer){
				set_sdp(msg,h->sdp_answer);
				sdp_message_free(h->sdp_answer);
				h->sdp_answer=NULL;
			}
		}
	}else{
		ms_error("You are accepting a call but not defined any media capabilities !");
	}
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_call_send_answer(ctx->excontext, h->tid, 200, msg);
#else
	eXosip_call_send_answer(h->tid,200,msg);
#endif
	return 0;
}

int sal_call_decline(Sal * ctx, SalOp *h, SalReason reason, const char *redirect){
	if (reason==SalReasonBusy){
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_lock(ctx->excontext);
#else
		eXosip_lock();
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_call_send_answer(ctx->excontext, h->tid, 486, NULL);
#else
		eXosip_call_send_answer(h->tid,486,NULL);
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_unlock(ctx->excontext);
#else
		eXosip_unlock();
#endif
	}
	else if (reason==SalReasonTemporarilyUnavailable){
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_lock(ctx->excontext);
#else
		eXosip_lock();
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_call_send_answer(ctx->excontext, h->tid, 480, NULL);
#else
		eXosip_call_send_answer(h->tid,480,NULL);
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_unlock(ctx->excontext);
#else
		eXosip_unlock();
#endif
	}else if (reason==SalReasonDoNotDisturb){
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_lock(ctx->excontext);
#else
		eXosip_lock();
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_call_send_answer(ctx->excontext, h->tid, 600, NULL);
#else
		eXosip_call_send_answer(h->tid,600,NULL);
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_unlock(ctx->excontext);
#else
		eXosip_unlock();
#endif
	}else if (reason==SalReasonMedia){
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_lock(ctx->excontext);
#else
		eXosip_lock();
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_call_send_answer(ctx->excontext, h->tid, 415, NULL);
#else
		eXosip_call_send_answer(h->tid,415,NULL);
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_unlock(ctx->excontext);
#else
		eXosip_unlock();
#endif
	}else if (redirect!=NULL && reason==SalReasonRedirect){
		osip_message_t *msg;
		int code;
		if (strstr(redirect,"sip:")!=0) code=302;
		else code=380;
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_lock(ctx->excontext);
#else
		eXosip_lock();
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_call_build_answer(ctx->excontext, h->tid, code, &msg);
#else
		eXosip_call_build_answer(h->tid,code,&msg);
#endif
		osip_message_set_contact(msg,redirect);
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_call_send_answer(ctx->excontext, h->tid, code, msg);
#else
		eXosip_call_send_answer(h->tid,code,msg);
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_unlock(ctx->excontext);
#else
		eXosip_unlock();
#endif
	}else sal_call_terminate(ctx, h);
	return 0;
}

SalMediaDescription * sal_call_get_remote_media_description(SalOp *h){
	return h->base.remote_media;
}

SalMediaDescription * sal_call_get_final_media_description(SalOp *h){
	if (h->base.local_media && h->base.remote_media && !h->result){
		sdp_process(h);
	}
	return h->result;
}

int sal_call_set_referer(SalOp *h, SalOp *refered_call){
	if (refered_call->replaces)
		h->replaces=ms_strdup(refered_call->replaces);
	if (refered_call->referred_by)
		h->referred_by=ms_strdup(refered_call->referred_by);
	return 0;
}

static int send_notify_for_refer(Sal *ctx, int did, const char *sipfrag){
	osip_message_t *msg;
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_lock(ctx->excontext);
#else
	eXosip_lock();
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_call_build_notify(ctx->excontext, did, EXOSIP_SUBCRSTATE_ACTIVE, &msg);
#else
	eXosip_call_build_notify(did,EXOSIP_SUBCRSTATE_ACTIVE,&msg);
#endif
	if (msg==NULL){
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_unlock(ctx->excontext);
#else
		eXosip_unlock();
#endif
		ms_warning("Could not build NOTIFY for refer.");
		return -1;
	}
	osip_message_set_content_type(msg,"message/sipfrag");
	osip_message_set_header(msg,"Event","refer");
	osip_message_set_body(msg,sipfrag,strlen(sipfrag));
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_call_send_request(ctx->excontext, did, msg);
#else
	eXosip_call_send_request(did,msg);
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_unlock(ctx->excontext);
#else
	eXosip_unlock();
#endif
	return 0;
}

/* currently only support to notify trying and 200Ok*/
int sal_call_notify_refer_state(Sal *ctx, SalOp *h, SalOp *newcall){
	if (newcall==NULL){
		/* in progress*/
		send_notify_for_refer(ctx, h->did,"SIP/2.0 100 Trying\r\n");
	}
	else if (newcall->cid!=-1){
		if (newcall->did==-1){
			/* not yet established*/
			if (!newcall->terminated){
				/* in progress*/
				send_notify_for_refer(ctx, h->did,"SIP/2.0 100 Trying\r\n");
			}
		}else{
			if (!newcall->terminated){
				if (send_notify_for_refer(ctx, h->did,"SIP/2.0 200 Ok\r\n")==-1){
					/* we need previous notify transaction to complete, so buffer the request for later*/
					h->sipfrag_pending="SIP/2.0 200 Ok\r\n";
				}
			}
		}
	}
	return 0;
}

int sal_ping(Sal *ctx, SalOp *op, const char *from, const char *to){
	osip_message_t *options=NULL;
	
	sal_op_set_from(op,from);
	sal_op_set_to(op,to);
	sal_exosip_fix_route(op);

#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_options_build_request (ctx->excontext, &options, sal_op_get_to(op),
			sal_op_get_from(op),sal_op_get_route(op));
#else
	eXosip_options_build_request (&options, sal_op_get_to(op),
			sal_op_get_from(op),sal_op_get_route(op));
#endif
	if (options){
		if (op->base.root->session_expires!=0){
			osip_message_set_header(options, "Session-expires", "200");
			osip_message_set_supported(options, "timer");
		}
		sal_add_other(sal_op_get_sal(op),op,options);
#ifdef HAVE_STRUCT_EXOSIP_T
		return eXosip_options_send_request(ctx->excontext, options);
#else
		return eXosip_options_send_request(options);
#endif
	}
	return -1;
}

int sal_call_refer(Sal *ctx, SalOp *h, const char *refer_to){
	osip_message_t *msg=NULL;
	int err=0;
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_lock(ctx->excontext);
#else
	eXosip_lock();
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_call_build_refer(ctx->excontext, h->did, refer_to, &msg);
#else
	eXosip_call_build_refer(h->did,refer_to, &msg);
#endif
	if (msg) {
#ifdef HAVE_STRUCT_EXOSIP_T
		err=eXosip_call_send_request(ctx->excontext, h->did, msg);
#else
		err=eXosip_call_send_request(h->did, msg);
#endif
	}
	else err=-1;
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_unlock(ctx->excontext);
#else
	eXosip_unlock();
#endif
	return err;
}

int sal_call_refer_with_replaces(Sal *ctx, SalOp *h, SalOp *other_call_h){
	osip_message_t *msg=NULL;
	char referto[256]={0};
	int err=0;
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_lock(ctx->excontext);
#else
	eXosip_lock();
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
	if (eXosip_call_get_referto(ctx->excontext, other_call_h->did,referto,sizeof(referto)-1)!=0){
#else
	if (eXosip_call_get_referto(other_call_h->did,referto,sizeof(referto)-1)!=0){
#endif
		ms_error("eXosip_call_get_referto() failed for did=%i",other_call_h->did);
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_unlock(ctx->excontext);
#else
		eXosip_unlock();
#endif
		return -1;
	}
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_call_build_refer(ctx->excontext, h->did,referto, &msg);
#else
	eXosip_call_build_refer(h->did,referto, &msg);
#endif
	osip_message_set_header(msg,"Referred-By",h->base.from);
	if (msg) {
#ifdef HAVE_STRUCT_EXOSIP_T
		err=eXosip_call_send_request(ctx->excontext, h->did, msg);
#else
		err=eXosip_call_send_request(h->did, msg);
#endif
	}
	else err=-1;
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_unlock(ctx->excontext);
#else
	eXosip_unlock();
#endif
	return err;
}

SalOp *sal_call_get_replaces(Sal *ctx, SalOp *h){
	if (h!=NULL && h->replaces!=NULL){
		int cid;
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_lock(ctx->excontext);
#else
		eXosip_lock();
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
		cid=eXosip_call_find_by_replaces(ctx->excontext, h->replaces);
#else
		cid=eXosip_call_find_by_replaces(h->replaces);
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_unlock(ctx->excontext);
#else
		eXosip_unlock();
#endif
		if (cid>0){
			SalOp *ret=sal_find_call(h->base.root,cid);
			return ret;
		}
	}
	return NULL;
}

int sal_call_send_dtmf(Sal *ctx, SalOp *h, char dtmf){
	osip_message_t *msg=NULL;
	char dtmf_body[128];
	char clen[10];

#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_lock(ctx->excontext);
#else
	eXosip_lock();
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_call_build_info(ctx->excontext, h->did, &msg);
#else
	eXosip_call_build_info(h->did,&msg);
#endif
	if (msg){
		snprintf(dtmf_body, sizeof(dtmf_body), "Signal=%c\r\nDuration=250\r\n", dtmf);
		osip_message_set_body(msg,dtmf_body,strlen(dtmf_body));
		osip_message_set_content_type(msg,"application/dtmf-relay");
		snprintf(clen,sizeof(clen),"%lu",(unsigned long)strlen(dtmf_body));
		osip_message_set_content_length(msg,clen);		
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_call_send_request(ctx->excontext, h->did, msg);
#else
		eXosip_call_send_request(h->did,msg);
#endif
	}
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_unlock(ctx->excontext);
#else
	eXosip_unlock();
#endif
	return 0;
}

static void push_auth_to_exosip(Sal *ctx, const SalAuthInfo *info){
	const char *userid;
	if (info->userid==NULL || info->userid[0]=='\0') userid=info->username;
	else userid=info->userid;
	ms_message("Authentication info for username [%s], id[%s], realm [%s] added to eXosip", info->username,userid, info->realm);
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_add_authentication_info (ctx->excontext, info->username,userid,
                                  info->password, NULL,info->realm);
#else
	eXosip_add_authentication_info (info->username,userid,
                                  info->password, NULL,info->realm);
#endif
}
/*
 * Just for symmetry ;-)
 */
static void pop_auth_from_exosip(Sal *ctx) {
	eXosip_clear_authentication_info(ctx->excontext);
}

int sal_call_terminate(Sal *ctx, SalOp *h){
	int err;
	if (h == NULL) return -1;
	if (h->auth_info) push_auth_to_exosip(ctx, h->auth_info);
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_lock(ctx->excontext);
#else
	eXosip_lock();
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
	err=eXosip_call_terminate(ctx->excontext, h->cid, h->did);
#else
	err=eXosip_call_terminate(h->cid,h->did);
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_unlock(ctx->excontext);
#else
	eXosip_unlock();
#endif
	if (!h->base.root->reuse_authorization) pop_auth_from_exosip(ctx);
	if (err!=0){
		ms_warning("Exosip could not terminate the call: cid=%i did=%i", h->cid,h->did);
	}
	h->terminated=TRUE;
	return 0;
}

void sal_op_authenticate(Sal *ctx, SalOp *h, const SalAuthInfo *info){
       bool_t terminating=FALSE;
       if (h->pending_auth && strcmp(h->pending_auth->request->sip_method,"BYE")==0) {
               terminating=TRUE;
       }
       if (h->terminated && !terminating) return;

       if (h->pending_auth){
	        push_auth_to_exosip(ctx, info);
		
        /*FIXME exosip does not take into account this update register message*/
	/*
        if (fix_message_contact(h, h->pending_auth->request,h->pending_auth->response)) {
            
        };
	*/
		update_contact_from_response(h,h->pending_auth->response);
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_lock(ctx->excontext);
#else
		eXosip_lock();
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_default_action(ctx->excontext, h->pending_auth);
#else
		eXosip_default_action(h->pending_auth);
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_unlock(ctx->excontext);
#else
		eXosip_unlock();
#endif
		ms_message("eXosip_default_action() done");
		if (!h->base.root->reuse_authorization) pop_auth_from_exosip(ctx);
		
		if (h->auth_info) sal_auth_info_delete(h->auth_info); /*if already exist*/
		h->auth_info=sal_auth_info_clone(info); /*store auth info for subsequent request*/
	}
}
void sal_op_cancel_authentication(SalOp *h) {
	if (h->rid >0) {
		sal_op_get_sal(h)->callbacks.register_failure(h,SalErrorFailure, SalReasonForbidden,"Authentication failure");
	} else if (h->cid >0) {
		sal_op_get_sal(h)->callbacks.call_failure(h,SalErrorFailure, SalReasonForbidden,"Authentication failure",0);
	} else {
		ms_warning("Auth failure not handled");
	}

}
static void set_network_origin(SalOp *op, osip_message_t *req){
	const char *received=NULL;
	int rport=5060;
	char origin[64]={0};
    SalTransport transport;
	if (extract_received_rport(req,&received,&rport,&transport)!=0){
		osip_via_t *via=NULL;
		char *tmp;
		osip_message_get_via(req,0,&via);
		received=osip_via_get_host(via);
		tmp=osip_via_get_port(via);
		if (tmp) rport=atoi(tmp);
	}
    if (transport != SalTransportUDP) {
        snprintf(origin,sizeof(origin)-1,"sip:%s:%i",received,rport);
    } else {
       snprintf(origin,sizeof(origin)-1,"sip:%s:%i;transport=%s",received,rport,sal_transport_to_string(transport)); 
    }
	__sal_op_set_network_origin(op,origin);
}

static void set_remote_ua(SalOp* op, osip_message_t *req){
	if (op->base.remote_ua==NULL){
		osip_header_t *h=NULL;
		osip_message_get_user_agent(req,0,&h);
		if (h){
			op->base.remote_ua=ms_strdup(h->hvalue);
		}
	}
}

static void set_remote_contact(SalOp* op, osip_message_t *req){
	if (op->base.remote_contact==NULL){
		osip_contact_t *h=NULL;
		osip_message_get_contact(req,0,&h);
		if (h){
			char *tmp=NULL;
			osip_contact_to_str(h,&tmp);
			__sal_op_set_remote_contact(op,tmp);
			osip_free(tmp);
		}
	}
}

static void set_replaces(SalOp *op, osip_message_t *req){
	osip_header_t *h=NULL;

	if (op->replaces){
		ms_free(op->replaces);
		op->replaces=NULL;
	}
	osip_message_header_get_byname(req,"replaces",0,&h);
	if (h){
		if (h->hvalue && h->hvalue[0]!='\0'){
			op->replaces=ms_strdup(h->hvalue);
		}
	}
}

static SalOp *find_op(Sal *sal, eXosip_event_t *ev){
	if (ev->cid>0){
		return sal_find_call(sal,ev->cid);
	}
	if (ev->rid>0){
		return sal_find_register(sal,ev->rid);
	}
	if (ev->sid>0){
		return sal_find_out_subscribe(sal,ev->sid);
	}
	if (ev->nid>0){
		return sal_find_in_subscribe(sal,ev->nid);
	}
	if (ev->response) return sal_find_other(sal,ev->response);
	else if (ev->request) return sal_find_other(sal,ev->request);
	return NULL;
}

static void inc_new_call(Sal *sal, eXosip_event_t *ev){
	SalOp *op=sal_op_new(sal);
	osip_from_t *from,*to;
	osip_call_info_t *call_info;
	char *tmp=NULL;
	sdp_message_t *sdp=eXosip_get_sdp_info(ev->request);
	
	osip_call_id_t *callid=osip_message_get_call_id(ev->request);
	
	osip_call_id_to_str(callid,&tmp);
	op->base.call_id=ms_strdup(tmp);
	osip_free(tmp);
	
	set_network_origin(op,ev->request);
	set_remote_contact(op,ev->request);
	set_remote_ua(op,ev->request);
	set_replaces(op,ev->request);
	sal_op_set_custom_header(op,sal_exosip_get_custom_headers(ev->request));
	
	if (sdp){
		op->sdp_offering=FALSE;
		op->base.remote_media=sal_media_description_new();
		sdp_to_media_description(sdp,op->base.remote_media);
		sdp_message_free(sdp);
	}else op->sdp_offering=TRUE;

	from=osip_message_get_from(ev->request);
	to=osip_message_get_to(ev->request);
	osip_from_to_str(from,&tmp);
	sal_op_set_from(op,tmp);
	osip_free(tmp);
	osip_from_to_str(to,&tmp);
	sal_op_set_to(op,tmp);
	osip_free(tmp);

	osip_message_get_call_info(ev->request,0,&call_info);
	if(call_info)
	{
		osip_call_info_to_str(call_info,&tmp);
		if( strstr(tmp,"answer-after=") != NULL)
		{
			op->auto_answer_asked=TRUE;
			ms_message("The caller asked to automatically answer the call(Emergency?)\n");
		}
		osip_free(tmp);
	}

	op->tid=ev->tid;
	op->cid=ev->cid;
	op->did=ev->did;
	sal_add_call(op->base.root,op);
	sal->callbacks.call_received(op);
}

static void handle_reinvite(Sal *sal,  eXosip_event_t *ev){
	SalOp *op=find_op(sal,ev);
	sdp_message_t *sdp;

	if (op==NULL) {
		ms_warning("Reinvite for non-existing operation !");
		return;
	}
	op->reinvite=TRUE;
	op->tid=ev->tid;
	sdp=eXosip_get_sdp_info(ev->request);
	if (op->base.remote_media){
		sal_media_description_unref(op->base.remote_media);
		op->base.remote_media=NULL;
	}
	if (op->result){
		sal_media_description_unref(op->result);
		op->result=NULL;
	}
	if (sdp){
		op->sdp_offering=FALSE;
		op->base.remote_media=sal_media_description_new();
		sdp_to_media_description(sdp,op->base.remote_media);
		sdp_message_free(sdp);
		
	}else {
		op->sdp_offering=TRUE;
	}
	sal->callbacks.call_updating(op);
}

static void handle_ack(Sal *sal,  eXosip_event_t *ev){
	SalOp *op=find_op(sal,ev);
	sdp_message_t *sdp;

	if (op==NULL) {
		ms_warning("ack for non-existing call !");
		return;
	}
	if (op->terminated) {
		ms_warning("ack for terminated call, ignoring");
		return;
	}
	
	if (op->sdp_offering){
		sdp=eXosip_get_sdp_info(ev->ack);
		if (sdp){
			if (op->base.remote_media)
				sal_media_description_unref(op->base.remote_media);
			op->base.remote_media=sal_media_description_new();
			sdp_to_media_description(sdp,op->base.remote_media);
			sdp_process(op);
			sdp_message_free(sdp);
		}
	}
	if (op->reinvite){
		op->reinvite=FALSE;
	}
	sal->callbacks.call_ack(op);
}

static void update_contact_from_response(SalOp *op, osip_message_t *response){
	const char *received;
	int rport;
	SalTransport transport;
	if (extract_received_rport(response,&received,&rport,&transport)==0){
		const char *contact=sal_op_get_contact(op);
		if (!contact){
			/*no contact given yet, use from instead*/
			contact=sal_op_get_from(op);
		}
		if (contact){
			SalAddress *addr=sal_address_new(contact);
			char *tmp;
			sal_address_set_domain(addr,received);
			sal_address_set_port_int(addr,rport);
			if (transport!=SalTransportUDP)
				sal_address_set_transport(addr,transport);
			tmp=sal_address_as_string(addr);
			ms_message("Contact address updated to %s",tmp);
			sal_op_set_contact(op,tmp);
			sal_address_destroy(addr);
			ms_free(tmp);
		}
	}
}

static int call_proceeding(Sal *sal, eXosip_event_t *ev){
	SalOp *op=find_op(sal,ev);

	if (op==NULL || op->terminated==TRUE) {
		ms_warning("This call has been canceled.");
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_lock(sal->excontext);
#else
		eXosip_lock();
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_call_terminate(sal->excontext, ev->cid, ev->did);
#else
		eXosip_call_terminate(ev->cid,ev->did);
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_unlock(sal->excontext);
#else
		eXosip_unlock();
#endif
		return -1;
	}
	if (ev->did>0)
		op->did=ev->did;
	op->tid=ev->tid;
	
	/* update contact if received and rport are set by the server
	 note: will only be used by remote for next INVITE, if any...*/
	update_contact_from_response(op,ev->response);
	return 0;
}

static void call_ringing(Sal *sal, eXosip_event_t *ev){
	sdp_message_t *sdp;
	SalOp *op=find_op(sal,ev);
	if (call_proceeding(sal, ev)==-1) return;

	set_remote_ua(op,ev->response);
	sdp=eXosip_get_sdp_info(ev->response);
	if (sdp){
		op->base.remote_media=sal_media_description_new();
		sdp_to_media_description(sdp,op->base.remote_media);
		sdp_message_free(sdp);
		if (op->base.local_media) sdp_process(op);
	}
	sal->callbacks.call_ringing(op);
}

static void call_accepted(Sal *sal, eXosip_event_t *ev){
	sdp_message_t *sdp;
	osip_message_t *msg=NULL;
	SalOp *op=find_op(sal,ev);
	const char *contact;
	
	if (op==NULL || op->terminated==TRUE) {
		ms_warning("This call has been already terminated.");
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_lock(sal->excontext);
#else
		eXosip_lock();
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_call_terminate(sal->excontext, ev->cid, ev->did);
#else
		eXosip_call_terminate(ev->cid,ev->did);
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_unlock(sal->excontext);
#else
		eXosip_unlock();
#endif
		return ;
	}

	op->did=ev->did;
	set_remote_ua(op,ev->response);
	set_remote_contact(op,ev->response);

	sdp=eXosip_get_sdp_info(ev->response);
	if (sdp){
		op->base.remote_media=sal_media_description_new();
		sdp_to_media_description(sdp,op->base.remote_media);
		sdp_message_free(sdp);
		if (op->base.local_media) sdp_process(op);
	}
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_call_build_ack(sal->excontext, ev->did, &msg);
#else
	eXosip_call_build_ack(ev->did,&msg);
#endif
	if (msg==NULL) {
		ms_warning("This call has been already terminated.");
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_lock(sal->excontext);
#else
		eXosip_lock();
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_call_terminate(sal->excontext, ev->cid, ev->did);
#else
		eXosip_call_terminate(ev->cid,ev->did);
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_unlock(sal->excontext);
#else
		eXosip_unlock();
#endif
		return ;
	}
	contact=sal_op_get_contact(op);
	if (contact) {
		_osip_list_set_empty(&msg->contacts,(void (*)(void*))osip_contact_free);
		osip_message_set_contact(msg,contact);
	}
	if (op->sdp_answer){
		set_sdp(msg,op->sdp_answer);
		sdp_message_free(op->sdp_answer);
		op->sdp_answer=NULL;
	}
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_call_send_ack(sal->excontext, ev->did, msg);
#else
	eXosip_call_send_ack(ev->did,msg);
#endif
	sal->callbacks.call_accepted(op);
}

static void call_terminated(Sal *sal, eXosip_event_t *ev){
	char *from=NULL;
	SalOp *op=find_op(sal,ev);
	if (op==NULL){
		ms_warning("Call terminated for already closed call ?");
		return;
	}
	if (ev->request){
		osip_from_to_str(ev->request->from,&from);
	}
	sal->callbacks.call_terminated(op,from!=NULL ? from : sal_op_get_from(op));
	if (from) osip_free(from);
	op->terminated=TRUE;
}

static void call_released(Sal *sal, eXosip_event_t *ev){
	SalOp *op=find_op(sal,ev);
	if (op==NULL){
		ms_warning("No op associated to this call_released()");
		return;
	}
	if (!op->terminated){
		/* no response received so far */
		call_failure(sal,ev);
	}
	sal->callbacks.call_released(op);
}

static int get_auth_data_from_response(osip_message_t *resp, const char **realm, const char **username){
	const char *prx_realm=NULL,*www_realm=NULL;
	osip_proxy_authenticate_t *prx_auth;
	osip_www_authenticate_t *www_auth;
	
	*username=osip_uri_get_username(resp->from->url);
	prx_auth=(osip_proxy_authenticate_t*)osip_list_get(&resp->proxy_authenticates,0);
	www_auth=(osip_proxy_authenticate_t*)osip_list_get(&resp->www_authenticates,0);
	if (prx_auth!=NULL)
		prx_realm=osip_proxy_authenticate_get_realm(prx_auth);
	if (www_auth!=NULL)
		www_realm=osip_www_authenticate_get_realm(www_auth);

	if (prx_realm){
		*realm=prx_realm;
	}else if (www_realm){
		*realm=www_realm;
	}else{
		return -1;
	}
	return 0;
}

static int get_auth_data_from_request(osip_message_t *msg, const char **realm, const char **username){
	osip_authorization_t *auth=NULL;
	osip_proxy_authorization_t *prx_auth=NULL;
	
	*username=osip_uri_get_username(msg->from->url);
	osip_message_get_authorization(msg, 0, &auth);
	if (auth){
		*realm=osip_authorization_get_realm(auth);
		return 0;
	}
	osip_message_get_proxy_authorization(msg,0,&prx_auth);
	if (prx_auth){
		*realm=osip_proxy_authorization_get_realm(prx_auth);
		return 0;
	}
	return -1;
}

static int get_auth_data(eXosip_event_t *ev, const char **realm, const char **username){
	if (ev->response && get_auth_data_from_response(ev->response,realm,username)==0) return 0;
	if (ev->request && get_auth_data_from_request(ev->request,realm,username)==0) return 0;
	return -1;
}

int sal_op_get_auth_requested(SalOp *op, const char **realm, const char **username){
	if (op->pending_auth){
		return get_auth_data(op->pending_auth,realm,username);
	}
	return -1;
}

static bool_t process_authentication(Sal *sal, eXosip_event_t *ev){
	SalOp *op;
	const char *username,*realm;
	op=find_op(sal,ev);
	if (op==NULL){
		ms_warning("No operation associated with this authentication !");
		return TRUE;
	}
	if (get_auth_data(ev,&realm,&username)==0){
		if (op->pending_auth!=NULL){
			eXosip_event_free(op->pending_auth);
			op->pending_auth=ev;
		}else{
			op->pending_auth=ev;
			sal_add_pending_auth(sal,op);
		}
		
		sal->callbacks.auth_requested(op,realm,username);
		return FALSE;
	}
	return TRUE;
}

static void authentication_ok(Sal *sal, eXosip_event_t *ev){
	SalOp *op;
	const char *username,*realm;
	op=find_op(sal,ev);
	if (op==NULL){
		ms_warning("No operation associated with this authentication_ok!");
		return ;
	}
	if (op->pending_auth){
		eXosip_event_free(op->pending_auth);
		sal_remove_pending_auth(sal,op);
		op->pending_auth=NULL;
	}
	if (get_auth_data(ev,&realm,&username)==0){
		sal->callbacks.auth_success(op,realm,username);
	}
}

static bool_t call_failure(Sal *sal, eXosip_event_t *ev){
	SalOp *op;
	int code=0;
	char* computedReason=NULL;
	const char *reason=NULL;
	SalError error=SalErrorUnknown;
	SalReason sr=SalReasonUnknown;
	

	op=(SalOp*)find_op(sal,ev);

	if (op==NULL) {
		ms_warning("Call failure reported for a closed call, ignored.");
		return TRUE;
	}

	if (ev->response){
		code=osip_message_get_status_code(ev->response);
		reason=osip_message_get_reason_phrase(ev->response);
		osip_header_t *h=NULL;
		if (!osip_message_header_get_byname(	ev->response
											,"Reason"
											,0
											,&h)) {
			computedReason = ms_strdup_printf("%s %s",reason,osip_header_get_value(h));
			reason = computedReason;

		}
	}
	switch(code)
	{
		case 401:
		case 407:
			return process_authentication(sal,ev);
			break;
		case 400:
			error=SalErrorUnknown;
		break;
		case 404:
			error=SalErrorFailure;
			sr=SalReasonNotFound;
		break;
		case 415:
			error=SalErrorFailure;
			sr=SalReasonMedia;
		break;
		case 422:
#ifdef HAVE_STRUCT_EXOSIP_T
			eXosip_default_action(sal->excontext, ev);
#else
			eXosip_default_action(ev);
#endif
			return TRUE;
		break;
		case 480:
			error=SalErrorFailure;
			sr=SalReasonTemporarilyUnavailable;
		break;
		case 486:
			error=SalErrorFailure;
			sr=SalReasonBusy;
		break;
		case 487:
		break;
		case 600:
			error=SalErrorFailure;
			sr=SalReasonDoNotDisturb;
		break;
		case 603:
			error=SalErrorFailure;
			sr=SalReasonDeclined;
		break;
		default:
			if (code>0){
				error=SalErrorFailure;
				sr=SalReasonUnknown;
			}else error=SalErrorNoResponse;
	}
	op->terminated=TRUE;
	sal->callbacks.call_failure(op,error,sr,reason,code);
	if (computedReason != NULL){
		ms_free(computedReason);
	}
	return TRUE;
}

/* Request remote side to send us VFU */
void sal_call_send_vfu_request(Sal *ctx, SalOp *h){
	osip_message_t *msg=NULL;
	char info_body[] =
			"<?xml version=\"1.0\" encoding=\"utf-8\" ?>"
			 "<media_control>"
			 "  <vc_primitive>"
			 "    <to_encoder>"
			 "      <picture_fast_update></picture_fast_update>"
			 "    </to_encoder>"
			 "  </vc_primitive>"
			 "</media_control>";

	char clen[10];

#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_lock(ctx->excontext);
#else
	eXosip_lock();
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_call_build_info(ctx->excontext, h->did, &msg);
#else
	eXosip_call_build_info(h->did,&msg);
#endif
	if (msg){
		osip_message_set_body(msg,info_body,strlen(info_body));
		osip_message_set_content_type(msg,"application/media_control+xml");
		snprintf(clen,sizeof(clen),"%lu",(unsigned long)strlen(info_body));
		osip_message_set_content_length(msg,clen);
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_call_send_request(ctx->excontext, h->did, msg);
#else
		eXosip_call_send_request(h->did,msg);
#endif
		ms_message("Sending VFU request !");
	}
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_unlock(ctx->excontext);
#else
	eXosip_unlock();
#endif
}

static void process_media_control_xml(Sal *sal, eXosip_event_t *ev){
	SalOp *op=find_op(sal,ev);
	osip_body_t *body=NULL;

	if (op==NULL){
		ms_warning("media control xml received without operation context!");
		return ;
	}
	
	osip_message_get_body(ev->request,0,&body);
	if (body && body->body!=NULL &&
		strstr(body->body,"picture_fast_update")){
		osip_message_t *ans=NULL;
		ms_message("Receiving VFU request !");
		if (sal->callbacks.vfu_request){
			sal->callbacks.vfu_request(op);
#ifdef HAVE_STRUCT_EXOSIP_T
			eXosip_call_build_answer(sal->excontext, ev->tid, 200, &ans);
#else
			eXosip_call_build_answer(ev->tid,200,&ans);
#endif
			if (ans)
#ifdef HAVE_STRUCT_EXOSIP_T
				eXosip_call_send_answer(sal->excontext, ev->tid, 200, ans);
#else
				eXosip_call_send_answer(ev->tid,200,ans);
#endif
			return;
		}
	}
	/*in all other cases we must say it is not implemented.*/
	{
		osip_message_t *ans=NULL;
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_lock(sal->excontext);
#else
		eXosip_lock();
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_call_build_answer(sal->excontext, ev->tid, 501, &ans);
#else
		eXosip_call_build_answer(ev->tid,501,&ans);
#endif
		if (ans) {
#ifdef HAVE_STRUCT_EXOSIP_T
			eXosip_call_send_answer(sal->excontext, ev->tid, 501, ans);
#else
			eXosip_call_send_answer(ev->tid,501,ans);
#endif
		}
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_unlock(sal->excontext);
#else
		eXosip_unlock();
#endif
	}
}

static void process_dtmf_relay(Sal *sal, eXosip_event_t *ev){
	SalOp *op=find_op(sal,ev);
	osip_body_t *body=NULL;

	if (op==NULL){
		ms_warning("media dtmf relay received without operation context!");
		return ;
	}
	
	osip_message_get_body(ev->request,0,&body);
	if (body && body->body!=NULL){
		osip_message_t *ans=NULL;
		const char *name=strstr(body->body,"Signal");
		if (name==NULL) name=strstr(body->body,"signal");
		if (name==NULL) {
			ms_warning("Could not extract the dtmf name from the SIP INFO.");
		}else{
			char tmp[2];
			name+=strlen("signal");
			if (sscanf(name," = %1s",tmp)==1){
				ms_message("Receiving dtmf %s via SIP INFO.",tmp);
				if (sal->callbacks.dtmf_received != NULL)
					sal->callbacks.dtmf_received(op, tmp[0]);
			}
		}
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_lock(sal->excontext);
#else
		eXosip_lock();
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_call_build_answer(sal->excontext, ev->tid, 200, &ans);
#else
		eXosip_call_build_answer(ev->tid,200,&ans);
#endif
		if (ans) {
#ifdef HAVE_STRUCT_EXOSIP_T
			eXosip_call_send_answer(sal->excontext, ev->tid, 200, ans);
#else
			eXosip_call_send_answer(ev->tid,200,ans);
#endif
		}
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_unlock(sal->excontext);
#else
		eXosip_unlock();
#endif
	}
}

static void fill_options_answer(osip_message_t *options){
	osip_message_set_allow(options,"INVITE, ACK, BYE, CANCEL, OPTIONS, MESSAGE, SUBSCRIBE, NOTIFY, INFO");
	osip_message_set_accept(options,"application/sdp");
}

static void process_refer(Sal *sal, SalOp *op, eXosip_event_t *ev){
	osip_header_t *h=NULL;
	osip_message_t *ans=NULL;
	ms_message("Receiving REFER request !");
	osip_message_header_get_byname(ev->request,"Refer-To",0,&h);

	if (h){
		osip_from_t *from=NULL;
		char *tmp;
		osip_from_init(&from);
	
		if (osip_from_parse(from,h->hvalue)==0){
			if (op ){
				osip_uri_header_t *uh=NULL;
				osip_header_t *referred_by=NULL;
				osip_uri_header_get_byname(&from->url->url_headers,(char*)"Replaces",&uh);
				if (uh!=NULL && uh->gvalue && uh->gvalue[0]!='\0'){
					ms_message("Found replaces in Refer-To");
					if (op->replaces){
						ms_free(op->replaces);
					}
					op->replaces=ms_strdup(uh->gvalue);
				}
				osip_message_header_get_byname(ev->request,"Referred-By",0,&referred_by);
				if (referred_by && referred_by->hvalue && referred_by->hvalue[0]!='\0'){
					if (op->referred_by)
						ms_free(op->referred_by);
					op->referred_by=ms_strdup(referred_by->hvalue);
				}
			}
			osip_uri_header_freelist(&from->url->url_headers);
			osip_from_to_str(from,&tmp);
			sal->callbacks.refer_received(sal,op,tmp);
			osip_free(tmp);
			osip_from_free(from);
		}
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_lock(sal->excontext);
#else
		eXosip_lock();
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_call_build_answer(sal->excontext, ev->tid, 202, &ans);
#else
		eXosip_call_build_answer(ev->tid,202,&ans);
#endif
		if (ans) {
#ifdef HAVE_STRUCT_EXOSIP_T
			eXosip_call_send_answer(sal->excontext, ev->tid, 202, ans);
#else
			eXosip_call_send_answer(ev->tid,202,ans);
#endif
		}
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_unlock(sal->excontext);
#else
		eXosip_unlock();
#endif
	}
	else
	{
		ms_warning("cannot do anything with the refer without destination\n");
	}
}

static void process_notify(Sal *sal, eXosip_event_t *ev){
	osip_header_t *h=NULL;
	char *from=NULL;
	SalOp *op=find_op(sal,ev);
	osip_message_t *ans=NULL;

	ms_message("Receiving NOTIFY request !");
	osip_from_to_str(ev->request->from,&from);
	osip_message_header_get_byname(ev->request,"Event",0,&h);
	if(h){
		osip_body_t *body=NULL;
		//osip_content_type_t *ct=NULL;
		osip_message_get_body(ev->request,0,&body);
		//ct=osip_message_get_content_type(ev->request);
		if (h->hvalue && strncasecmp(h->hvalue,"refer",strlen("refer"))==0){
			/*special handling of refer events*/
			if (body && body->body){
				osip_message_t *msg;
				osip_message_init(&msg);
				if (osip_message_parse_sipfrag(msg,body->body,strlen(body->body))==0){
					int code=osip_message_get_status_code(msg);
					if (code==100){
						sal->callbacks.notify_refer(op,SalReferTrying);
					}else if (code==200){
						sal->callbacks.notify_refer(op,SalReferSuccess);
					}else if (code>=400){
						sal->callbacks.notify_refer(op,SalReferFailed);
					}
				}
				osip_message_free(msg);
			}
		}else{
			/*generic handling*/
			sal->callbacks.notify(op,from,h->hvalue);
		}
	}
	/*answer that we received the notify*/
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_lock(sal->excontext);
#else
	eXosip_lock();
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_call_build_answer(sal->excontext, ev->tid, 200, &ans);
#else
	eXosip_call_build_answer(ev->tid,200,&ans);
#endif
	if (ans) {
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_call_send_answer(sal->excontext, ev->tid, 200, ans);
#else
		eXosip_call_send_answer(ev->tid,200,ans);
#endif
	}
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_unlock(sal->excontext);
#else
	eXosip_unlock();
#endif
	osip_free(from);
}

static void call_message_new(Sal *sal, eXosip_event_t *ev){
	osip_message_t *ans=NULL;
	if (ev->request){
		if (MSG_IS_INFO(ev->request)){
			osip_content_type_t *ct;
			ct=osip_message_get_content_type(ev->request);
			if (ct && ct->subtype){
				if (strcmp(ct->subtype,"media_control+xml")==0)
					process_media_control_xml(sal,ev);
				else if (strcmp(ct->subtype,"dtmf-relay")==0)
					process_dtmf_relay(sal,ev);
				else {
					ms_message("Unhandled SIP INFO.");
					/*send an "Not implemented" answer*/
#ifdef HAVE_STRUCT_EXOSIP_T
					eXosip_lock(sal->excontext);
#else
					eXosip_lock();
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
					eXosip_call_build_answer(sal->excontext, ev->tid, 501, &ans);
#else
					eXosip_call_build_answer(ev->tid,501,&ans);
#endif
					if (ans) {
#ifdef HAVE_STRUCT_EXOSIP_T
						eXosip_call_send_answer(sal->excontext, ev->tid, 501, ans);
#else
						eXosip_call_send_answer(ev->tid,501,ans);
#endif
					}
#ifdef HAVE_STRUCT_EXOSIP_T
					eXosip_unlock(sal->excontext);
#else
					eXosip_unlock();
#endif
				}
			}else{
				/*empty SIP INFO, probably to test we are alive. Send an empty answer*/
#ifdef HAVE_STRUCT_EXOSIP_T
				eXosip_lock(sal->excontext);
#else
				eXosip_lock();
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
				eXosip_call_build_answer(sal->excontext, ev->tid, 200, &ans);
#else
				eXosip_call_build_answer(ev->tid,200,&ans);
#endif
				if (ans) {
#ifdef HAVE_STRUCT_EXOSIP_T
					eXosip_call_send_answer(sal->excontext, ev->tid, 200, ans);
#else
					eXosip_call_send_answer(ev->tid,200,ans);
#endif
				}
#ifdef HAVE_STRUCT_EXOSIP_T
				eXosip_unlock(sal->excontext);
#else
				eXosip_unlock();
#endif
			}
		}else if(MSG_IS_MESSAGE(ev->request)){
			/* SIP messages could be received into call */
			text_received(sal, ev);
#ifdef HAVE_STRUCT_EXOSIP_T
			eXosip_lock(sal->excontext);
#else
			eXosip_lock();
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
			eXosip_call_build_answer(sal->excontext, ev->tid, 200, &ans);
#else
			eXosip_call_build_answer(ev->tid,200,&ans);
#endif
			if (ans) {
#ifdef HAVE_STRUCT_EXOSIP_T
				eXosip_call_send_answer(sal->excontext, ev->tid, 200, ans);
#else
				eXosip_call_send_answer(ev->tid,200,ans);
#endif
			}
#ifdef HAVE_STRUCT_EXOSIP_T
			eXosip_unlock(sal->excontext);
#else
			eXosip_unlock();
#endif
		}else if(MSG_IS_REFER(ev->request)){
			SalOp *op=find_op(sal,ev);
			
			ms_message("Receiving REFER request !");
			process_refer(sal,op,ev);
		}else if(MSG_IS_NOTIFY(ev->request)){
			process_notify(sal,ev);
		}else if (MSG_IS_OPTIONS(ev->request)){
#ifdef HAVE_STRUCT_EXOSIP_T
			eXosip_lock(sal->excontext);
#else
			eXosip_lock();
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
			eXosip_call_build_answer(sal->excontext, ev->tid, 200, &ans);
#else
			eXosip_call_build_answer(ev->tid,200,&ans);
#endif
			if (ans){
				fill_options_answer(ans);
#ifdef HAVE_STRUCT_EXOSIP_T
				eXosip_call_send_answer(sal->excontext, ev->tid, 200, ans);
#else
				eXosip_call_send_answer(ev->tid,200,ans);
#endif
			}
#ifdef HAVE_STRUCT_EXOSIP_T
			eXosip_unlock(sal->excontext);
#else
			eXosip_unlock();
#endif
		}
	}else ms_warning("call_message_new: No request ?");
}

static void inc_update(Sal *sal, eXosip_event_t *ev){
	osip_message_t *msg=NULL;
	ms_message("Processing incoming UPDATE");
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_lock(sal->excontext);
#else
	eXosip_lock();
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_message_build_answer(sal->excontext, ev->tid, 200, &msg);
#else
	eXosip_message_build_answer(ev->tid,200,&msg);
#endif
	if (msg!=NULL) {
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_message_send_answer(sal->excontext, ev->tid, 200, msg);
#else
		eXosip_message_send_answer(ev->tid,200,msg);
#endif
	}
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_unlock(sal->excontext);
#else
	eXosip_unlock();
#endif
}

static bool_t comes_from_local_if(osip_message_t *msg){
	osip_via_t *via=NULL;
	osip_message_get_via(msg,0,&via);
	if (via){
		const char *host;
		host=osip_via_get_host(via);
		if (strcmp(host,"127.0.0.1")==0 || strcmp(host,"::1")==0){
			osip_generic_param_t *param=NULL;
			osip_via_param_get_byname(via,"received",&param);
			if (param==NULL) return TRUE;
			if (param->gvalue &&
				(strcmp(param->gvalue,"127.0.0.1")==0 || strcmp(param->gvalue,"::1")==0)){
				return TRUE;
			}
		}
	}
	return FALSE;
}

static const char *days[]={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
static const char *months[]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};

static int utc_offset() {
	time_t ref = 24 * 60 * 60L;
	struct tm * timeptr;
	int gmtime_hours;

	/* get the local reference time for Jan 2, 1900 00:00 UTC */
	timeptr = localtime(&ref);
	gmtime_hours = timeptr->tm_hour;

	/* if the local time is the "day before" the UTC, subtract 24 hours
	from the hours to get the UTC offset */
	if (timeptr->tm_mday < 2) gmtime_hours -= 24;

	return gmtime_hours;
}

time_t mktime_utc(struct tm *timeptr) {
	return mktime(timeptr) + utc_offset() * 3600;
}

static void text_received(Sal *sal, eXosip_event_t *ev){
	osip_body_t *body=NULL;
	char *from=NULL,*msg=NULL;
	osip_content_type_t* content_type;
	osip_uri_param_t* external_body_url; 
	char unquoted_external_body_url [256];
	int external_body_size=0;
	SalMessage salmsg;
	char message_id[256]={0};
	osip_header_t *date=NULL;
	struct tm ret={0};
	char tmp1[80]={0};
	char tmp2[80]={0};
	SalOp *op=sal_op_new(sal);

	osip_message_get_date(ev->request,0,&date);
	if(date!=NULL){
		int i,j;
		sscanf(date->hvalue,"%3c,%d%s%d%d:%d:%d",tmp1,&ret.tm_mday,tmp2,
	             &ret.tm_year,&ret.tm_hour,&ret.tm_min,&ret.tm_sec);
		ret.tm_year-=1900;
		for(i=0;i<7;i++) { 
			if(strcmp(tmp1,days[i])==0) ret.tm_wday=i; 
		}
		for(j=0;j<12;j++) { 
			if(strcmp(tmp2,months[j])==0) ret.tm_mon=j; 
		}
		ret.tm_isdst=0;
	}else ms_warning("No date header in SIP MESSAGE, we don't know when it was sent.");
	
	content_type= osip_message_get_content_type(ev->request);
	if (!content_type) {
		ms_error("Could not get message because no content type");
		return;
	}
	osip_from_to_str(ev->request->from,&from);
	if (content_type->type 
		&& strcmp(content_type->type, "text")==0 
		&& content_type->subtype
		&& strcmp(content_type->subtype, "plain")==0 ) {
		osip_message_get_body(ev->request,0,&body);
		if (body==NULL){
			ms_error("Could not get text message from SIP body");
			osip_free(from);
			return;
		}
		msg=body->body;
	}else if (content_type->type 
		  && strcmp(content_type->type, "message")==0 
		  && content_type->subtype
		  && strcmp(content_type->subtype, "external-body")==0 ) {
		
		osip_content_type_param_get_byname(content_type, "URL", &external_body_url);
		/*remove both first and last character*/
		strncpy(unquoted_external_body_url
				,&external_body_url->gvalue[1]
				,external_body_size=MIN(strlen(external_body_url->gvalue)-1,sizeof(unquoted_external_body_url)));
		unquoted_external_body_url[external_body_size-1]='\0';
	} else {
		ms_warning("Unsupported content type [%s/%s]",content_type->type,content_type->subtype);
		osip_free(from);
		return;
	}
	sal_op_set_custom_header(op,sal_exosip_get_custom_headers(ev->request));
	
	snprintf(message_id,sizeof(message_id)-1,"%s%s",ev->request->call_id->number,ev->request->cseq->number);
	
	salmsg.from=from;
	salmsg.text=msg;
	salmsg.url=external_body_size>0 ? unquoted_external_body_url : NULL;
	salmsg.message_id=message_id;
	salmsg.time=date!=NULL ? mktime_utc(&ret) : time(NULL);
	sal->callbacks.text_received(op,&salmsg);
	sal_op_release(sal, op);
	osip_free(from);
}

static void other_request(Sal *sal, eXosip_event_t *ev){
	ms_message("in other_request");
	if (ev->request==NULL) return;
	if (strcmp(ev->request->sip_method,"MESSAGE")==0){
		text_received(sal,ev);
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_message_send_answer(sal->excontext, ev->tid, 200, NULL);
#else
		eXosip_message_send_answer(ev->tid,200,NULL);
#endif
	}else if (strcmp(ev->request->sip_method,"OPTIONS")==0){
		osip_message_t *options=NULL;
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_options_build_answer(sal->excontext, ev->tid, 200, &options);
#else
		eXosip_options_build_answer(ev->tid,200,&options);
#endif
		fill_options_answer(options);
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_options_send_answer(sal->excontext, ev->tid, 200, options);
#else
		eXosip_options_send_answer(ev->tid,200,options);
#endif
	}else if (strncmp(ev->request->sip_method, "REFER", 5) == 0){
		ms_message("Receiving REFER request !");
		if (comes_from_local_if(ev->request)) {
			process_refer(sal,NULL,ev);
		}else ms_warning("Ignored REFER not coming from this local loopback interface.");
	}else if (strncmp(ev->request->sip_method, "UPDATE", 6) == 0){
		inc_update(sal,ev);
	}else {
		char *tmp=NULL;
		size_t msglen=0;
		osip_message_to_str(ev->request,&tmp,&msglen);
		if (tmp){
			ms_message("Unsupported request received:\n%s",tmp);
			osip_free(tmp);
		}
		/*answer with a 501 Not implemented*/
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_message_send_answer(sal->excontext, ev->tid, 501, NULL);
#else
		eXosip_message_send_answer(ev->tid,501,NULL);
#endif
	}
}

static void masquerade_via(osip_message_t *msg, const char *ip, const char *port){
	osip_via_t *via=NULL;
	osip_message_get_via(msg,0,&via);
	if (via){
		osip_free(via->port);
		via->port=osip_strdup(port);
		osip_free(via->host);
		via->host=osip_strdup(ip);
	}
}


static bool_t fix_message_contact(SalOp *op, osip_message_t *request,osip_message_t *last_answer, bool_t expire_last_contact) {
	osip_contact_t *ctt=NULL;
	const char *received;
	int rport;
	SalTransport transport;
	char port[20];

	if (extract_received_rport(last_answer,&received,&rport,&transport)==-1) return FALSE;
	osip_message_get_contact(request,0,&ctt);
	if (ctt == NULL) {
		ms_warning("fix_message_contact(): no contact to update");
		return FALSE;
	}
	if (expire_last_contact){
		osip_contact_t *oldct=NULL,*prevct;
		osip_generic_param_t *param=NULL;
		osip_contact_clone(ctt,&oldct);
		while ((prevct=(osip_contact_t*)osip_list_get(&request->contacts,1))!=NULL){
			osip_contact_free(prevct);
			osip_list_remove(&request->contacts,1);
		}
		osip_list_add(&request->contacts,oldct,1);
		osip_contact_param_get_byname(oldct,"expires",&param);
		if (param){
			if (param->gvalue) osip_free(param->gvalue);
			param->gvalue=osip_strdup("0");
		}else{
			osip_contact_param_add(oldct,osip_strdup("expires"),osip_strdup("0"));
		}
	}
	if (ctt->url->host!=NULL){
		osip_free(ctt->url->host);
	}
	ctt->url->host=osip_strdup(received);
	if (ctt->url->port!=NULL){
		osip_free(ctt->url->port);
	}
	snprintf(port,sizeof(port),"%i",rport);
	ctt->url->port=osip_strdup(port);
	if (op->masquerade_via) masquerade_via(request,received,port);

	if (transport != SalTransportUDP) {
		sal_address_set_param((SalAddress *)ctt, "transport", sal_transport_to_string(transport)); 
	}
	return TRUE;    
}

static bool_t register_again_with_updated_contact(Sal *ctx, SalOp *op, osip_message_t *orig_request, osip_message_t *last_answer){
	osip_contact_t *ctt=NULL;
	SalAddress* ori_contact_address=NULL;
	const char *received;
	int rport;
	SalTransport transport;
	char* tmp;
	osip_message_t *msg=NULL;
	Sal* sal=op->base.root;
	int i=0;
	bool_t found_valid_contact=FALSE;
	bool_t from_request=FALSE;

	if (sal->double_reg==FALSE ) return FALSE; 

	if (extract_received_rport(last_answer,&received,&rport,&transport)==-1) return FALSE;
	do{
		ctt=NULL;
		osip_message_get_contact(last_answer,i,&ctt);
		if (!from_request && ctt==NULL) {
			osip_message_get_contact(orig_request,0,&ctt);
			from_request=TRUE;
		}
		if (ctt){
			osip_contact_to_str(ctt,&tmp);
			ori_contact_address = sal_address_new(tmp);
	
			/*check if contact is up to date*/
			if (strcmp(sal_address_get_domain(ori_contact_address),received) ==0 
				&& sal_address_get_port_int(ori_contact_address) == rport
			&& sal_address_get_transport(ori_contact_address) == transport) {
				if (!from_request){
					ms_message("Register response has up to date contact, doing nothing.");
				}else {
					ms_warning("Register response does not have up to date contact, but last request had."
						"Stupid registrar detected, giving up.");
				}
				found_valid_contact=TRUE;
			}
			osip_free(tmp);
			sal_address_destroy(ori_contact_address);
		}else break;
		i++;
	}while(!found_valid_contact);
	if (!found_valid_contact)
		ms_message("Contact do not match, resending register.");
	else return FALSE;

#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_lock(ctx->excontext);
#else
	eXosip_lock();
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_register_build_register(ctx->excontext, op->rid, op->expires, &msg);
#else
	eXosip_register_build_register(op->rid,op->expires,&msg);
#endif
	if (msg==NULL){
#ifdef HAVE_STRUCT_EXOSIP_T
	    eXosip_unlock(ctx->excontext);
#else
	    eXosip_unlock();
#endif
	    ms_warning("Fail to create a contact updated register.");
	    return FALSE;
	}
	if (fix_message_contact(op,msg,last_answer,op->base.root->expire_old_contact)) {
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_register_send_register(ctx->excontext, op->rid, msg);
#else
		eXosip_register_send_register(op->rid,msg);
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_unlock(ctx->excontext);  
#else
		eXosip_unlock();  
#endif
		ms_message("Resending new register with updated contact");
		update_contact_from_response(op,last_answer);
		return TRUE;
	} else {
	    ms_warning("Fail to send updated register.");
#ifdef HAVE_STRUCT_EXOSIP_T
	    eXosip_unlock(ctx->excontext);
#else
	    eXosip_unlock();
#endif
	    return FALSE;
	}
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_unlock(ctx->excontext);
#else
	eXosip_unlock();
#endif
	return FALSE;
}

static void registration_success(Sal *sal, eXosip_event_t *ev){
	SalOp *op=sal_find_register(sal,ev->rid);
	osip_header_t *h=NULL;
	bool_t registered;
	if (op==NULL){
		ms_error("Receiving register response for unknown operation");
		return;
	}
	osip_message_get_expires(ev->request,0,&h);
	if (h!=NULL && atoi(h->hvalue)!=0){
		registered=TRUE;
		if (!register_again_with_updated_contact(sal,op,ev->request,ev->response)){
			sal->callbacks.register_success(op,registered);
		}
	}else {
		sal->callbacks.register_success(op,FALSE);
	}
}

static bool_t registration_failure(Sal *sal, eXosip_event_t *ev){
	int status_code=0;
	const char *reason=NULL;
	SalOp *op=sal_find_register(sal,ev->rid);
	SalReason sr=SalReasonUnknown;
	SalError se=SalErrorUnknown;
	
	if (op==NULL){
		ms_error("Receiving register failure for unknown operation");
		return TRUE;
	}
	if (ev->response){
		status_code=osip_message_get_status_code(ev->response);
		reason=osip_message_get_reason_phrase(ev->response);
	}
	switch(status_code){
		case 401:
		case 407:
			return process_authentication(sal,ev);
			break;
		case 423: /*interval too brief*/
			{/*retry with greater interval */
				osip_header_t *h=NULL;
				osip_message_t *msg=NULL;
				osip_message_header_get_byname(ev->response,"min-expires",0,&h);
				if (h && h->hvalue && h->hvalue[0]!='\0'){
					int val=atoi(h->hvalue);
					if (val>op->expires)
						op->expires=val;
				}else op->expires*=2;
#ifdef HAVE_STRUCT_EXOSIP_T
				eXosip_lock(sal->excontext);
#else
				eXosip_lock();
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
				eXosip_register_build_register(sal->excontext, op->rid, op->expires, &msg);
#else
				eXosip_register_build_register(op->rid,op->expires,&msg);
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
				eXosip_register_send_register(sal->excontext, op->rid, msg);
#else
				eXosip_register_send_register(op->rid,msg);
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
				eXosip_unlock(sal->excontext);
#else
				eXosip_unlock();
#endif
			}
		break;
		case 606: /*Not acceptable, workaround for proxies that don't like private addresses
				 in vias, such as ekiga.net 
				 On the opposite, freephonie.net bugs when via are masqueraded.
				 */
			op->masquerade_via=TRUE;
		default:
			/* if contact is up to date, process the failure, otherwise resend a new register with
				updated contact first, just in case the faillure is due to incorrect contact */
			if (ev->response && register_again_with_updated_contact(sal,op,ev->request,ev->response))
				return TRUE; /*we are retrying with an updated contact*/
			if (status_code==403){
				se=SalErrorFailure;
				sr=SalReasonForbidden;
			}else if (status_code==0){
				se=SalErrorNoResponse;
			}
			sal->callbacks.register_failure(op,se,sr,reason);
	}
	return TRUE;
}

static void other_request_reply(Sal *sal,eXosip_event_t *ev){
	SalOp *op=find_op(sal,ev);
	if (op==NULL){
		ms_warning("other_request_reply(): Receiving response to unknown request.");
		return;
	}
	if (ev->response){
		ms_message("Processing reponse status [%i] for method [%s]",ev->response->status_code,osip_message_get_method(ev->request));
		update_contact_from_response(op,ev->response);
		if (ev->request && strcmp(osip_message_get_method(ev->request),"OPTIONS")==0)
			sal->callbacks.ping_reply(op);
	}
	if (ev->request && strcmp(osip_message_get_method(ev->request),"MESSAGE")==0) {
		/*out of call message acknolegment*/
		SalTextDeliveryStatus status=SalTextDeliveryFailed;
		if (ev->response){
			if (ev->response->status_code<200){
				status=SalTextDeliveryInProgress;
			}else if (ev->response->status_code<300 && ev->response->status_code>=200){
				status=SalTextDeliveryDone;
			}
		}
		sal->callbacks.text_delivery_update(op,status);
	}
}

static void process_in_call_reply(Sal *sal, eXosip_event_t *ev){
	SalOp *op=find_op(sal,ev);
	if (ev->response){
		if (ev->request && strcmp(osip_message_get_method(ev->request),"NOTIFY")==0){
			if (op->sipfrag_pending){
				send_notify_for_refer(sal, op->did,op->sipfrag_pending);
				op->sipfrag_pending=NULL;
			}
		}
	}
}

static bool_t process_event(Sal *sal, eXosip_event_t *ev){
	ms_message("linphone process event get a message %d\n",ev->type);
	switch(ev->type){
		case EXOSIP_CALL_ANSWERED:
			ms_message("CALL_ANSWERED\n");
			call_accepted(sal,ev);
			authentication_ok(sal,ev);
			break;
		case EXOSIP_CALL_CLOSED:
		case EXOSIP_CALL_CANCELLED:
			ms_message("CALL_CLOSED or CANCELLED\n");
			call_terminated(sal,ev);
			break;
#ifdef EXOSIP_CALL_TIMEOUT
		case EXOSIP_CALL_TIMEOUT:
#endif
		case EXOSIP_CALL_NOANSWER:
			ms_message("CALL_TIMEOUT or NOANSWER\n");
			return call_failure(sal,ev);
			break;
		case EXOSIP_CALL_REQUESTFAILURE:
		case EXOSIP_CALL_GLOBALFAILURE:
		case EXOSIP_CALL_SERVERFAILURE:
			ms_message("CALL_REQUESTFAILURE or GLOBALFAILURE or SERVERFAILURE\n");
			return call_failure(sal,ev);
			break;
		case EXOSIP_CALL_RELEASED:
			ms_message("CALL_RELEASED\n");
			call_released(sal, ev);
			break;
		case EXOSIP_CALL_INVITE:
			ms_message("CALL_NEW\n");
			inc_new_call(sal,ev);
			break;
		case EXOSIP_CALL_REINVITE:
			handle_reinvite(sal,ev);
			break;
		case EXOSIP_CALL_ACK:
			ms_message("CALL_ACK");
			handle_ack(sal,ev);
			break;
		case EXOSIP_CALL_REDIRECTED:
			ms_message("CALL_REDIRECTED");
#ifdef HAVE_STRUCT_EXOSIP_T
			eXosip_default_action(sal->excontext, ev);
#else
			eXosip_default_action(ev);
#endif
			break;
		case EXOSIP_CALL_PROCEEDING:
			ms_message("CALL_PROCEEDING");
			call_proceeding(sal,ev);
			break;
		case EXOSIP_CALL_RINGING:
			ms_message("CALL_RINGING");
			call_ringing(sal,ev);
			authentication_ok(sal,ev);
			break;
		case EXOSIP_CALL_MESSAGE_NEW:
			ms_message("EXOSIP_CALL_MESSAGE_NEW");
			call_message_new(sal,ev);
			break;
		case EXOSIP_CALL_MESSAGE_REQUESTFAILURE:
			if (ev->response &&
				(ev->response->status_code==407 || ev->response->status_code==401)){
				 return process_authentication(sal,ev);
			}
			break;
		case EXOSIP_CALL_MESSAGE_ANSWERED:
			ms_message("EXOSIP_CALL_MESSAGE_ANSWERED ");
			process_in_call_reply(sal,ev);
		break;
		case EXOSIP_IN_SUBSCRIPTION_NEW:
			ms_message("CALL_IN_SUBSCRIPTION_NEW ");
			sal_exosip_subscription_recv(sal,ev);
			break;
#ifdef EXOSIP_IN_SUBSCRIPTION_RELEASED
		case EXOSIP_IN_SUBSCRIPTION_RELEASED:
			ms_message("CALL_SUBSCRIPTION_NEW ");
			sal_exosip_in_subscription_closed(sal,ev);
			break;
#endif
#ifdef EXOSIP_SUBSCRIPTION_UPDATE
		case EXOSIP_SUBSCRIPTION_UPDATE:
			ms_message("CALL_SUBSCRIPTION_UPDATE");
			break;
#endif
		case EXOSIP_SUBSCRIPTION_NOTIFY:
			ms_message("CALL_SUBSCRIPTION_NOTIFY");
			sal_exosip_notify_recv(sal,ev);
			break;
		case EXOSIP_SUBSCRIPTION_ANSWERED:
			ms_message("EXOSIP_SUBSCRIPTION_ANSWERED, ev->sid=%i, ev->did=%i\n",ev->sid,ev->did);
			sal_exosip_subscription_answered(sal,ev);
			break;
#ifdef EXOSIP_SUBSCRIPTION_CLOSED
		case EXOSIP_SUBSCRIPTION_CLOSED:
			ms_message("EXOSIP_SUBSCRIPTION_CLOSED\n");
			sal_exosip_subscription_closed(sal,ev);
			break;
#endif
		case EXOSIP_SUBSCRIPTION_REQUESTFAILURE:   /**< announce a request failure      */
			if (ev->response && (ev->response->status_code == 407 || ev->response->status_code == 401)){
				return process_authentication(sal,ev);
			}
		case EXOSIP_SUBSCRIPTION_SERVERFAILURE:
		case EXOSIP_SUBSCRIPTION_GLOBALFAILURE:
			sal_exosip_subscription_closed(sal,ev);
			break;
		case EXOSIP_REGISTRATION_FAILURE:
			ms_message("REGISTRATION_FAILURE\n");
			return registration_failure(sal,ev);
			break;
		case EXOSIP_REGISTRATION_SUCCESS:
			authentication_ok(sal,ev);
			registration_success(sal,ev);
			break;
		case EXOSIP_MESSAGE_NEW:
			other_request(sal,ev);
			break;
		case EXOSIP_MESSAGE_PROCEEDING:
		case EXOSIP_MESSAGE_ANSWERED:
		case EXOSIP_MESSAGE_REDIRECTED:
		case EXOSIP_MESSAGE_SERVERFAILURE:
		case EXOSIP_MESSAGE_GLOBALFAILURE:
			other_request_reply(sal,ev);
			break;
		case EXOSIP_MESSAGE_REQUESTFAILURE:
		case EXOSIP_NOTIFICATION_REQUESTFAILURE:
			if (ev->response) {
				switch (ev->response->status_code) {
					case 407:
					case 401:
						return process_authentication(sal,ev);
					case 412: {
#ifdef HAVE_STRUCT_EXOSIP_T
						eXosip_automatic_action (sal->excontext);
#else
						eXosip_automatic_action ();
#endif
						return 1;
					}
				}
			}
			other_request_reply(sal,ev);
			break;
		default:
			ms_message("Unhandled exosip event ! %i",ev->type);
			break;
	}
	return TRUE;
}

int sal_iterate(Sal *sal){
	eXosip_event_t *ev;
#ifdef HAVE_STRUCT_EXOSIP_T
	while((ev=eXosip_event_wait(sal->excontext, 0, 0))!=NULL){
#else
	while((ev=eXosip_event_wait(0,0))!=NULL){
#endif
		if (process_event(sal,ev))
			eXosip_event_free(ev);
	}
#ifdef HAVE_EXOSIP_TRYLOCK

	if (eXosip_trylock()==0){
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_automatic_refresh(sal->excontext);
#else
		eXosip_automatic_refresh();
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_unlock(sal->excontext);
#else
		eXosip_unlock();
#endif
	}else{
		ms_warning("eXosip_trylock busy.");
	}

#else /* HAVE_EXOSIP_TRYLOCK */

#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_lock(sal->excontext);
#else
	eXosip_lock();
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_automatic_refresh(sal->excontext);
#else
	eXosip_automatic_refresh();
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_unlock(sal->excontext);
#else
	eXosip_unlock();
#endif

#endif /* HAVE_EXOSIP_TRYLOCK */
	return 0;
}

static void register_set_contact(osip_message_t *msg, const char *contact){
	osip_uri_param_t *param = NULL;
	osip_contact_t *ct=NULL;
	char *line=NULL;
	/*we get the line parameter choosed by exosip, and add it to our own contact*/
	osip_message_get_contact(msg,0,&ct);
	if (ct!=NULL){
		osip_uri_uparam_get_byname(ct->url, "line", &param);
		if (param && param->gvalue)
			line=osip_strdup(param->gvalue);
	}
	_osip_list_set_empty(&msg->contacts,(void (*)(void*))osip_contact_free);
	osip_message_set_contact(msg,contact);
	osip_message_get_contact(msg,0,&ct);
	osip_uri_uparam_add(ct->url,osip_strdup("line"),line);
}

void sal_message_add_route(osip_message_t *msg, const char *proxy){
	osip_route_t *route;

	osip_list_special_free(&msg->routes,(void (*)(void*))osip_route_free);
	
	osip_route_init(&route);
	if (osip_route_parse(route,proxy)==0){
		osip_uri_param_t *lr_param = NULL;
		osip_uri_uparam_get_byname(route->url, "lr", &lr_param);
		if (lr_param == NULL){
			osip_uri_uparam_add(route->url,osip_strdup("lr"),NULL);
		}
		osip_list_add(&msg->routes,route,0);
		return;
	}
	osip_route_free(route);
}


int sal_register(Sal *ctx, SalOp *h, const char *proxy, const char *from, int expires){
	osip_message_t *msg;
	const char *contact=sal_op_get_contact(h);

	sal_op_set_route(h,proxy);
	if (h->rid==-1){
		SalAddress *from_parsed=sal_address_new(from);
		char domain[256];
		char *uri, *domain_ptr = NULL;
		if (from_parsed==NULL) {
			ms_warning("sal_register() bad from %s",from);
			return -1;
		}
		/* Get domain using sal_address_as_string_uri_only() and stripping the username part instead of
		   using sal_address_get_domain() because to have a properly formatted domain with IPv6 proxy addresses. */
		uri = sal_address_as_string_uri_only(from_parsed);
		if (uri) domain_ptr = strchr(uri, '@');
		if (domain_ptr) {
			snprintf(domain,sizeof(domain),"sip:%s",domain_ptr+1);
		} else {
			snprintf(domain,sizeof(domain),"sip:%s",sal_address_get_domain(from_parsed));
		}
		if (uri) ms_free(uri);
		sal_address_destroy(from_parsed);
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_lock(ctx->excontext);
#else
		eXosip_lock();
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
		h->rid=eXosip_register_build_initial_register(ctx->excontext, from, domain,
							      NULL, expires, &msg);
#else
		h->rid=eXosip_register_build_initial_register(from,domain,NULL,expires,&msg);
#endif
		if (msg){
			if (contact) register_set_contact(msg,contact);
			sal_message_add_route(msg,proxy);
			sal_add_register(h->base.root,h);
		}else{
			ms_error("Could not build initial register.");
#ifdef HAVE_STRUCT_EXOSIP_T
			eXosip_unlock(ctx->excontext);
#else
			eXosip_unlock();
#endif
			return -1;
		}
	}else{
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_lock(ctx->excontext);
#else
		eXosip_lock();
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_register_build_register(ctx->excontext, h->rid, expires, &msg);
#else
		eXosip_register_build_register(h->rid,expires,&msg);
#endif
		sal_message_add_route(msg,proxy);
	}
	if (msg){
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_register_send_register(ctx->excontext, h->rid, msg);
#else
		eXosip_register_send_register(h->rid,msg);
#endif
	}
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_unlock(ctx->excontext);
#else
	eXosip_unlock();
#endif
	h->expires=expires;
	return (msg != NULL) ? 0 : -1;
}

int sal_register_refresh(Sal *ctx, SalOp *op, int expires){
	osip_message_t *msg=NULL;
	const char *contact=sal_op_get_contact(op);
	
	if (op->rid==-1){
		ms_error("Unexistant registration context, not possible to refresh.");
		return -1;
	}
#ifdef HAVE_EXOSIP_TRYLOCK
	{
		int tries=0;
		/*iOS hack: in the keep alive handler, we have no more than 10 seconds to refresh registers, otherwise the application is suspended forever.
		* In order to prevent this case that can occur when the exosip thread is busy with DNS while network isn't in a good shape, we try to take
		* the exosip lock in a non blocking way, and give up if it takes too long*/
		while (eXosip_trylock()!=0){
			ms_usleep(100000);
			tries++;
			if (tries>30) {/*after 3 seconds, give up*/
				ms_warning("Could not obtain exosip lock in a reasonable time, giving up.");
				return -1;
			}
		}
	}
#else /* HAVE_EXOSIP_TRYLOCK */
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_lock(ctx->excontext);
#else
	eXosip_lock();
#endif
#endif /* HAVE_EXOSIP_TRYLOCK */
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_register_build_register(ctx->excontext, op->rid, expires, &msg);
#else
	eXosip_register_build_register(op->rid,expires,&msg);
#endif
	if (msg!=NULL){
		if (contact) register_set_contact(msg,contact);
		sal_message_add_route(msg,sal_op_get_route(op));
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_register_send_register(ctx->excontext, op->rid, msg);
#else
		eXosip_register_send_register(op->rid,msg);
#endif
	}else ms_error("Could not build REGISTER refresh message.");
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_unlock(ctx->excontext);
#else
	eXosip_unlock();
#endif
	return (msg != NULL) ? 0 : -1;
}

int sal_unregister(Sal *ctx, SalOp *h){
	osip_message_t *msg=NULL;
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_lock(ctx->excontext);
#else
	eXosip_lock();
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_register_build_register(ctx->excontext, h->rid, 0, &msg);
#else
	eXosip_register_build_register(h->rid, 0, &msg);
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
	if (msg) eXosip_register_send_register(ctx->excontext, h->rid,msg);
#else
	if (msg) eXosip_register_send_register(h->rid,msg);
#endif
	else ms_warning("Could not build unREGISTER !");
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_unlock(ctx->excontext);
#else
	eXosip_unlock();
#endif
	return 0;
}

SalAddress * sal_address_new(const char *uri){
	osip_from_t *from;
	osip_from_init(&from);

	// Remove front spaces
	while (uri[0]==' ') {
		uri++;
	}
		
	if (osip_from_parse(from,uri)!=0){
		osip_from_free(from);
		return NULL;
	}
	if (from->displayname!=NULL && from->displayname[0]=='"'){
		char *unquoted=osip_strdup_without_quote(from->displayname);
		osip_free(from->displayname);
		from->displayname=unquoted;
	}
	return (SalAddress*)from;
}

SalAddress * sal_address_clone(const SalAddress *addr){
	osip_from_t *ret=NULL;
	osip_from_clone((osip_from_t*)addr,&ret);
	return (SalAddress*)ret;
}

#define null_if_empty(s) (((s)!=NULL && (s)[0]!='\0') ? (s) : NULL )

const char *sal_address_get_scheme(const SalAddress *addr){
	const osip_from_t *u=(const osip_from_t*)addr;
	return null_if_empty(u->url->scheme);
}

const char *sal_address_get_display_name(const SalAddress* addr){
	const osip_from_t *u=(const osip_from_t*)addr;
	return null_if_empty(u->displayname);
}

const char *sal_address_get_username(const SalAddress *addr){
	const osip_from_t *u=(const osip_from_t*)addr;
	return null_if_empty(u->url->username);
}

const char *sal_address_get_domain(const SalAddress *addr){
	const osip_from_t *u=(const osip_from_t*)addr;
	return null_if_empty(u->url->host);
}

void sal_address_set_display_name(SalAddress *addr, const char *display_name){
	osip_from_t *u=(osip_from_t*)addr;
	if (u->displayname!=NULL){
		osip_free(u->displayname);
		u->displayname=NULL;
	}
	if (display_name!=NULL && display_name[0]!='\0'){
		u->displayname=osip_strdup(display_name);
	}
}

void sal_address_set_username(SalAddress *addr, const char *username){
	osip_from_t *uri=(osip_from_t*)addr;
	if (uri->url->username!=NULL){
		osip_free(uri->url->username);
		uri->url->username=NULL;
	}
	if (username)
		uri->url->username=osip_strdup(username);
}

void sal_address_set_domain(SalAddress *addr, const char *host){
	osip_from_t *uri=(osip_from_t*)addr;
	if (uri->url->host!=NULL){
		osip_free(uri->url->host);
		uri->url->host=NULL;
	}
	if (host)
		uri->url->host=osip_strdup(host);
}

void sal_address_set_port(SalAddress *addr, const char *port){
	osip_from_t *uri=(osip_from_t*)addr;
	if (uri->url->port!=NULL){
		osip_free(uri->url->port);
		uri->url->port=NULL;
	}
	if (port)
		uri->url->port=osip_strdup(port);
}

void sal_address_set_port_int(SalAddress *uri, int port){
	char tmp[12];
	if (port==5060){
		/*this is the default, special case to leave the port field blank*/
		sal_address_set_port(uri,NULL);
		return;
	}
	snprintf(tmp,sizeof(tmp),"%i",port);
	sal_address_set_port(uri,tmp);
}

void sal_address_clean(SalAddress *addr){
	osip_generic_param_freelist(& ((osip_from_t*)addr)->gen_params);
	osip_uri_param_freelist(& ((osip_from_t*)addr)->url->url_params);
}

char *sal_address_as_string(const SalAddress *u){
	char *tmp,*ret;
	osip_from_t *from=(osip_from_t *)u;
	char *old_displayname=NULL;
	/* hack to force use of quotes around the displayname*/
	if (from->displayname!=NULL
	    && from->displayname[0]!='"'){
		old_displayname=from->displayname;
		from->displayname=osip_enquote(from->displayname);
	}
	osip_from_to_str(from,&tmp);
	if (old_displayname!=NULL){
		ms_free(from->displayname);
		from->displayname=old_displayname;
	}
	ret=ms_strdup(tmp);
	osip_free(tmp);
	return ret;
}

char *sal_address_as_string_uri_only(const SalAddress *u){
	char *tmp=NULL,*ret;
	osip_uri_to_str(((osip_from_t*)u)->url,&tmp);
	ret=ms_strdup(tmp);
	osip_free(tmp);
	return ret;
}
void sal_address_set_param(SalAddress *u,const char* name,const char* value) {
	osip_uri_param_t *param=NULL;
    osip_uri_uparam_get_byname(((osip_from_t*)u)->url,(char*)name,&param);
    if (param == NULL){
        osip_uri_uparam_add	(((osip_from_t*)u)->url,ms_strdup(name),value ? ms_strdup(value) : NULL);
    } else {
        osip_free(param->gvalue);
        param->gvalue=value ? osip_strdup(value) : NULL;
    }
    
}

void sal_address_destroy(SalAddress *u){
	osip_from_free((osip_from_t*)u);
}

void sal_use_tcp_tls_keepalive(Sal *ctx, bool_t enabled) {
	ctx->tcp_tls_keepalive = enabled;
}

void sal_set_keepalive_period(Sal *ctx,unsigned int value) {
	switch (ctx->transport) {
		case SalTransportUDP:
			ctx->keepalive_period = value;
			break;
		case SalTransportTCP:
		case SalTransportTLS:
			if (ctx->tcp_tls_keepalive) ctx->keepalive_period = value;
			else ctx->keepalive_period = -1;
			break;
		default:
			break;
	}
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_set_option (ctx->excontext, EXOSIP_OPT_UDP_KEEP_ALIVE, &ctx->keepalive_period);
#else
	eXosip_set_option (EXOSIP_OPT_UDP_KEEP_ALIVE, &ctx->keepalive_period);
#endif
}

unsigned int sal_get_keepalive_period(Sal *ctx) {
	return ctx->keepalive_period;
}

const char * sal_address_get_port(const SalAddress *addr) {
	const osip_from_t *u=(const osip_from_t*)addr;
	return null_if_empty(u->url->port);
}

int sal_address_get_port_int(const SalAddress *uri) {
	const char* port = sal_address_get_port(uri);
	if (port != NULL) {
		return atoi(port);
	} else {
		return 5060;
	}
}
SalTransport sal_address_get_transport(const SalAddress* addr) {
    const osip_from_t *u=(const osip_from_t*)addr;
    osip_uri_param_t *transport_param=NULL;
    osip_uri_uparam_get_byname(u->url,"transport",&transport_param);
    if (transport_param == NULL){
        return SalTransportUDP;
    }  else {
        return sal_transport_parse(transport_param->gvalue);
    }
}
void sal_address_set_transport(SalAddress* addr,SalTransport transport) {
    sal_address_set_param(addr, "transport", sal_transport_to_string(transport));
}

/* sends a reinvite. Local media description may have changed by application since call establishment*/
int sal_call_update(Sal *sal, SalOp *h, const char *subject){
	int err=0;
	osip_message_t *reinvite=NULL;

#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_lock(sal->excontext);
#else
	eXosip_lock();
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
	if(eXosip_call_build_request(sal->excontext, h->did, "INVITE", &reinvite) != 0 || reinvite==NULL){
#else
	if(eXosip_call_build_request(h->did,"INVITE",&reinvite) != 0 || reinvite==NULL){
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
		eXosip_unlock(sal->excontext);
#else
		eXosip_unlock();
#endif
		return -1;
	}
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_unlock(sal->excontext);
#else
	eXosip_unlock();
#endif
	osip_message_set_subject(reinvite,subject);
	osip_message_set_allow(reinvite, "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, NOTIFY, MESSAGE, SUBSCRIBE, INFO");
	if (h->base.contact){
		_osip_list_set_empty(&reinvite->contacts,(void (*)(void*))osip_contact_free);
		osip_message_set_contact(reinvite,h->base.contact);
	}
	if (h->base.root->session_expires!=0){
		osip_message_set_header(reinvite, "Session-expires", "200");
		osip_message_set_supported(reinvite, "timer");
	}
	if (h->base.local_media){
		h->sdp_offering=TRUE;
		set_sdp_from_desc(reinvite,h->base.local_media);
	}else h->sdp_offering=FALSE;
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_lock(sal->excontext);
#else
	eXosip_lock();
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
	err = eXosip_call_send_request(sal->excontext, h->did, reinvite);
#else
	err = eXosip_call_send_request(h->did, reinvite);
#endif
#ifdef HAVE_STRUCT_EXOSIP_T
	eXosip_unlock(sal->excontext);
#else
	eXosip_unlock();
#endif
	return err;
}

void sal_reuse_authorization(Sal *ctx, bool_t value) {
	ctx->reuse_authorization=value;
}

void sal_exosip_add_custom_headers(osip_message_t *msg, SalCustomHeader *ch){
	MSList *elem=(MSList*)ch;
	for (;elem!=NULL;elem=elem->next){
		SalCustomHeader *it=(SalCustomHeader*)elem;
		osip_message_set_header(msg,it->header_name,it->header_value);
	}
}

SalCustomHeader * sal_exosip_get_custom_headers(osip_message_t *msg){
	int i=0;
	osip_header_t *header;
	SalCustomHeader *ret=NULL;

	while((header=osip_list_get(&msg->headers,i))!=NULL){
		ret=sal_custom_header_append(ret,header->hname,header->hvalue);
		i++;
	}
	return ret;
}