File: msg_translator.c

package info (click to toggle)
kamailio 4.2.0-2+deb8u3
  • links: PTS, VCS
  • area: main
  • in suites: jessie
  • size: 56,276 kB
  • sloc: ansic: 552,836; xml: 166,484; sh: 8,659; makefile: 7,676; sql: 6,235; perl: 3,487; yacc: 3,428; python: 1,457; cpp: 1,219; php: 1,047; java: 449; pascal: 194; cs: 40; awk: 27
file content (3091 lines) | stat: -rw-r--r-- 85,324 bytes parent folder | download | duplicates (2)
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
/*
 * $Id$
 *
 *
 * Copyright (C) 2001-2003 FhG Fokus
 *
 * This file is part of ser, a free SIP server.
 *
 * ser 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
 *
 * For a license to use the ser software under conditions
 * other than those described here, or to purchase support for this
 * software, please contact iptel.org by e-mail at the following addresses:
 *    info@iptel.org
 *
 * ser 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *
 * History:
 * --------
 * 2003-01-20  bug_fix: use of return value of snprintf aligned to C99 (jiri)
 * 2003-01-23  added rport patches, contributed by
 *              Maxim Sobolev <sobomax@FreeBSD.org> and heavily modified by me
 *              (andrei)
 * 2003-01-24  added i param to via of outgoing requests (used by tcp),
 *              modified via_builder params (andrei)
 * 2003-01-27  more rport fixes (make use of new via_param->start)  (andrei)
 * 2003-01-27  next baby-step to removing ZT - PRESERVE_ZT (jiri)
 * 2003-01-29  scratchpad removed (jiri)
 * 2003-02-28  scratchpad compatibility abandoned (jiri)
 * 2003-03-01  VOICE_MAIL defs removed (jiri)
 * 2003-03-06  totags in outgoing replies bookmarked to enable
 *             ACK/200 tag matching (andrei)
 * 2003-03-18  killed the build_warning snprintf (andrei)
 * 2003-03-31  added subst lump support (andrei)
 * 2003-04-01  added opt (conditional) lump support (andrei)
 * 2003-04-02  added more subst lumps: SUBST_{SND,RCV}_ALL
 *              => ip:port;transport=proto (andrei)
 * 2003-04-12  added FL_FORCE_RPORT support (andrei)
 * 2003-04-13  updated warning builder -- fixed (andrei)
 * 2003-07-10  check_via_address knows now how to compare with ipv6 address
 *              references (e.g [::1]) (andrei)
 *             build_req_fomr_sip_req no longer adds 1 for ipv6 via parameter
 *              position calculations ([] are part of host.s now) (andrei)
 * 2003-10-02  via+lump dst address/port can be set to preset values (andrei)
 * 2003-10-08  receive_test function-alized (jiri)
 * 2003-10-20  added body_lump list (sip_msg), adjust_clen (andrei & jan)
 * 2003-11-11  type of rpl_lumps replaced by flags (bogdan)
 * 2006-04-20  build_req_from_sip_req, via_builder and lump_* functions
 *              use now struct dest_info; lumps & via comp param support
 *              (rfc3486) (andrei)
 * 2007-08-31  id_builder() and via_builder() are grouped into one function:
 *             create_via_hf() -- tm module needs them as well (Miklos)
 * 2008-12-17  build_req_from_sip_req() will now fallback to tcp, tls or sctp
 *              if packet size > udp_mtu and fallback is enabled 
 *             build_req_from_sip_req() uses now global_req_flags along
 *               msg->msg_flags  (andrei)
 *
 */
/* Via special params:
 * requests:
 * - if the address in via is different from the src_ip or an existing
 *   received=something is found, received=src_ip is added (and any preexisting
 *   received is deleted). received is added as the first via parameter if no
 *   receive is previously present or over the old receive.
 * - if the original via contains rport / rport=something or msg->msg_flags
 *   FL_FORCE_RPORT is set (e.g. script force_rport() cmd) rport=src_port
 *   is added (over previous rport / as first via param or after received
 *   if no received was present and received is added too)
 * local replies:
 *    (see also sl_send_reply)
 *  - rport and received are added in mostly the same way as for requests, but
 *    in the reverse order (first rport and then received). See also
 *    limitations.
 *  - if reply_to_via is set (default off) the local reply will be sent to
 *    the address in via (received is ignored since it was not set by us). The
 *    destination port is either the message source port if via contains rport
 *    or the FL_FORCE_RPORT flag is set or the port from the via. If either
 *    port or rport are present a normal dns lookup (instead of a srv lookup)
 *    is performed on the address. If no port is present and a srv lookup is
 *    performed the port is taken from the srv lookup. If the srv lookup failed
 *    or it was not performed, the port is set to the default sip port (5060).
 *  - if reply_to_via is off (default) the local reply is sent to the message
 *    source ip address. The destination port is set to the source port if
 *    rport is present or FL_FORCE_RPORT flag is set, to the via port or to
 *    the default sip port (5060) if neither rport or via port are present.
 * "normal" replies:
 *  - if received is present the message is sent to the received address else
 *    if no port is present (neither a normal via port or rport) a dns srv
 *    lookup is performed on the host part and the reply is sent to the
 *    resulting ip. If a port is present or the host part is an ip address
 *    the dns lookup will be a "normal" one (A or AAAA).
 *  - if rport is present, it's value will be used as the destination port
 *   (and this will also disable srv lookups)
 *  - if no port is present the destination port will be taken from the srv
 *    lookup. If the srv lookup fails or is not performed (e.g. ip address
 *    in host) the destination port will be set to the default sip port (5060).
 *
 * Known limitations:
 * - when locally replying to a message, rport and received will be appended to
 *   the via header parameters (for forwarded requests they are inserted at the
 *   beginning).
 * - a locally generated reply might get two received via parameters if a
 *   received is already present in the original message (this should not
 *   happen though, but ...)
 *
 *--andrei
*/

/*!
 * \file
 * \brief SIP-router core :: 
 * \ingroup core
 * Module: \ref core
 */

#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#include "comp_defs.h"
#include "msg_translator.h"
#include "globals.h"
#include "error.h"
#include "mem/mem.h"
#include "dprint.h"
#include "config.h"
#include "md5utils.h"
#include "data_lump.h"
#include "data_lump_rpl.h"
#include "ip_addr.h"
#include "resolve.h"
#include "ut.h"
#include "pt.h"
#include "cfg/cfg.h"
#include "parser/parse_to.h"
#include "parser/parse_param.h"
#include "forward.h"
#include "str_list.h"

#define append_str_trans(_dest,_src,_len,_msg) \
	append_str( (_dest), (_src), (_len) );

extern char version[];
extern int version_len;



/** per process fixup function for global_req_flags.
  * It should be called from the configuration framework.
  */
void fix_global_req_flags(str* gname, str* name)
{
	global_req_flags=0;
	switch(cfg_get(core, core_cfg, udp_mtu_try_proto)){
		case PROTO_NONE:
		case PROTO_UDP:
			/* do nothing */
			break;
		case PROTO_TCP:
			global_req_flags|=FL_MTU_TCP_FB;
			break;
		case PROTO_TLS:
			global_req_flags|=FL_MTU_TLS_FB;
			break;
		case PROTO_SCTP:
			global_req_flags|=FL_MTU_SCTP_FB;
			break;
	}
	if (cfg_get(core, core_cfg, force_rport))
		global_req_flags|=FL_FORCE_RPORT;
}



/* checks if ip is in host(name) and ?host(ip)=name?
 * ip must be in network byte order!
 *  resolver = DO_DNS | DO_REV_DNS; if 0 no dns check is made
 * return 0 if equal */
static int check_via_address(struct ip_addr* ip, str *name,
				unsigned short port, int resolver)
{
	struct hostent* he;
	int i;
	char* s;
	int len;

	/* maybe we are lucky and name it's an ip */
	s=ip_addr2a(ip);
	if (s){
		DBG("check_via_address(%s, %.*s, %d)\n",
			s, name->len, name->s, resolver);

		len=strlen(s);

		/* check if name->s is an ipv6 address or an ipv6 address ref. */
		if ((ip->af==AF_INET6) &&
				(	((len==name->len)&&(strncasecmp(name->s, s, name->len)==0))
					||
					((len==(name->len-2))&&(name->s[0]=='[')&&
						(name->s[name->len-1]==']')&&
						(strncasecmp(name->s+1, s, len)==0))
				)
		   )
			return 0;
		else

			if (strncmp(name->s, s, name->len)==0)
				return 0;
	}else{
		LM_CRIT("could not convert ip address\n");
		return -1;
	}

	if (port==0) port=SIP_PORT;
	if (resolver&DO_DNS){
		DBG("check_via_address: doing dns lookup\n");
		/* try all names ips */
		he=sip_resolvehost(name, &port, 0); /* don't use naptr */
		if (he && ip->af==he->h_addrtype){
			for(i=0;he && he->h_addr_list[i];i++){
				if ( memcmp(&he->h_addr_list[i], ip->u.addr, ip->len)==0)
					return 0;
			}
		}
	}
	if (resolver&DO_REV_DNS){
		DBG("check_via_address: doing rev. dns lookup\n");
		/* try reverse dns */
		he=rev_resolvehost(ip);
		if (he && (strncmp(he->h_name, name->s, name->len)==0))
			return 0;
		for (i=0; he && he->h_aliases[i];i++){
			if (strncmp(he->h_aliases[i],name->s, name->len)==0)
				return 0;
		}
	}
	return -1;
}


/* check if IP address in Via != source IP address of signaling */
int received_test( struct sip_msg *msg )
{
	int rcvd;

	rcvd=msg->via1->received || msg->via1->rport
			|| check_via_address(&msg->rcv.src_ip, &msg->via1->host,
							msg->via1->port, received_dns);
	return rcvd;
}


static char * warning_builder( struct sip_msg *msg, unsigned int *returned_len)
{
	static char buf[MAX_WARNING_LEN];
	str *foo;
	int print_len, l;
	int clen;
	char* t;

#define str_print(string, string_len) \
		do{ \
			l=(string_len); \
			if ((clen+l)>MAX_WARNING_LEN) \
				goto error_overflow; \
			memcpy(buf+clen, (string), l); \
			clen+=l; \
		}while(0)

#define str_lenpair_print(string, string_len, string2, string2_len) \
		do{ \
			str_print(string, string_len); \
			str_print(string2, string2_len);\
		}while(0)

#define str_pair_print( string, string2, string2_len) \
		str_lenpair_print((string), strlen((string)), (string2), (string2_len))

#define str_int_print(string, intval)\
		do{\
			t=int2str((intval), &print_len); \
			str_pair_print(string, t, print_len);\
		} while(0)

#define str_su_print(sockaddr)\
		do{\
			t=su2a(&sockaddr, sizeof(sockaddr)); \
			print_len=strlen(t); \
			str_print(t, print_len); \
		} while(0)

#define str_ipaddr_print(string, ipaddr_val)\
		do{\
			t=ip_addr2a((ipaddr_val)); \
			print_len=strlen(t); \
			str_pair_print(string, t, print_len);\
		} while(0)

	clen=0;
	str_print(WARNING, WARNING_LEN);
	str_su_print(msg->rcv.bind_address->su);
	str_print(WARNING_PHRASE, WARNING_PHRASE_LEN);

	/*adding out_uri*/
	if (msg->new_uri.s)
		foo=&(msg->new_uri);
	else
		foo=&(msg->first_line.u.request.uri);
	/* pid= */
	str_int_print(" pid=", my_pid());
	/* req_src_ip= */
	str_ipaddr_print(" req_src_ip=", &msg->rcv.src_ip);
	str_int_print(" req_src_port=", msg->rcv.src_port);
	str_pair_print(" in_uri=", msg->first_line.u.request.uri.s,
								msg->first_line.u.request.uri.len);
	str_pair_print(" out_uri=", foo->s, foo->len);
	str_pair_print(" via_cnt",
					(msg->parsed_flag & HDR_EOH_F)==HDR_EOH_F ? "=" : ">", 1);
	str_int_print("=", via_cnt);
	if (clen<MAX_WARNING_LEN){ buf[clen]='"'; clen++; }
	else goto error_overflow;


	*returned_len=clen;
	return buf;
error_overflow:
	LM_NOTICE("buffer size exceeded (probably too long URI)\n");
	*returned_len=0;
	return 0;
}




char* received_builder(struct sip_msg *msg, unsigned int *received_len)
{
	char *buf;
	int  len;
	struct ip_addr *source_ip;
	char *tmp;
	int  tmp_len;

	source_ip=&msg->rcv.src_ip;

	buf=pkg_malloc(sizeof(char)*MAX_RECEIVED_SIZE);
	if (buf==0){
		ser_error=E_OUT_OF_MEM;
		LM_ERR("out of memory\n");
		return 0;
	}
	memcpy(buf, RECEIVED, RECEIVED_LEN);
	if ( (tmp=ip_addr2a(source_ip))==0) {
		pkg_free(buf);
		return 0; /* error*/
	}
	tmp_len=strlen(tmp);
	len=RECEIVED_LEN+tmp_len;

	memcpy(buf+RECEIVED_LEN, tmp, tmp_len);
	buf[len]=0; /*null terminate it */

	*received_len = len;
	return buf;
}



char* rport_builder(struct sip_msg *msg, unsigned int *rport_len)
{
	char* buf;
	char* tmp;
	int tmp_len;
	int len;

	tmp_len=0;
	tmp=int2str(msg->rcv.src_port, &tmp_len);
	len=RPORT_LEN+tmp_len;
	buf=pkg_malloc(sizeof(char)*(len+1));/* space for null term */
	if (buf==0){
		ser_error=E_OUT_OF_MEM;
		LM_ERR("out of memory\n");
		return 0;
	}
	memcpy(buf, RPORT, RPORT_LEN);
	memcpy(buf+RPORT_LEN, tmp, tmp_len);
	buf[len]=0; /*null terminate it*/

	*rport_len=len;
	return buf;
}



char* id_builder(struct sip_msg* msg, unsigned int *id_len)
{
	char* buf;
	int len, value_len;
	char revhex[sizeof(int)*2];
	char* p;
	int size;

	size=sizeof(int)*2;
	p=&revhex[0];
	if (int2reverse_hex(&p, &size, msg->rcv.proto_reserved1)==-1){
		LM_CRIT("not enough space for id\n");
		return 0;
	}
	value_len=p-&revhex[0];
	len=ID_PARAM_LEN+value_len;
	buf=pkg_malloc(sizeof(char)*(len+1));/* place for ending \0 */
	if (buf==0){
		ser_error=E_OUT_OF_MEM;
		LM_ERR("out of memory\n");
		return 0;
	}
	memcpy(buf, ID_PARAM, ID_PARAM_LEN);
	memcpy(buf+ID_PARAM_LEN, revhex, value_len);
	buf[len]=0; /* null terminate it */
	*id_len=len;
	return buf;
}



char* clen_builder(	struct sip_msg* msg, int *clen_len, int diff, 
					int body_only)
{
	char* buf;
	int len;
	int value;
	char* value_s;
	int value_len;
	char* body;


	body=get_body(msg);
	if (body==0){
		ser_error=E_BAD_REQ;
		LM_ERR("no message body found (missing crlf?)");
		return 0;
	}
	value=msg->len-(int)(body-msg->buf)+diff;
	value_s=int2str(value, &value_len);
	DBG("clen_builder: content-length: %d (%s)\n", value, value_s);

	if (body_only) {
		len=value_len;
	}
	else {
		len=CONTENT_LENGTH_LEN+value_len+CRLF_LEN;
	}
	buf=pkg_malloc(sizeof(char)*(len+1));
	if (buf==0){
		ser_error=E_OUT_OF_MEM;
		LM_ERR("out of memory\n");
		return 0;
	}
	if (body_only) {
		memcpy(buf, value_s, value_len);
	}
	else {
		memcpy(buf, CONTENT_LENGTH, CONTENT_LENGTH_LEN);
		memcpy(buf+CONTENT_LENGTH_LEN, value_s, value_len);
		memcpy(buf+CONTENT_LENGTH_LEN+value_len, CRLF, CRLF_LEN);
	}
	buf[len]=0; /* null terminate it */
	*clen_len=len;
	return buf;
}



/* checks if a lump opt condition
 * returns 1 if cond is true, 0 if false */
static inline int lump_check_opt(	struct lump *l,
									struct sip_msg* msg,
									struct dest_info* snd_i
									)
{
	struct ip_addr* ip;
	unsigned short port;
	int proto;

#define get_ip_port_proto \
			if ((snd_i==0) || (snd_i->send_sock==0)){ \
				LM_CRIT("null send socket\n"); \
				return 1; /* we presume they are different :-) */ \
			} \
			if (msg->rcv.bind_address){ \
				ip=&msg->rcv.bind_address->address; \
				port=msg->rcv.bind_address->port_no; \
				proto=msg->rcv.bind_address->proto; \
			}else{ \
				ip=&msg->rcv.dst_ip; \
				port=msg->rcv.dst_port; \
				proto=msg->rcv.proto; \
			} \

	switch(l->u.cond){
		case COND_FALSE:
			return 0;
		case COND_TRUE:
			LUMP_SET_COND_TRUE(l);
			return 1;
		case COND_IF_DIFF_REALMS:
			get_ip_port_proto;
			/* faster tests first */
			if ((port==snd_i->send_sock->port_no) && 
					(proto==snd_i->send_sock->proto) &&
#ifdef USE_COMP
					(msg->rcv.comp==snd_i->comp) &&
#endif
					(ip_addr_cmp(ip, &snd_i->send_sock->address)))
				return 0;
			else {
				LUMP_SET_COND_TRUE(l);
				return 1;
			}
		case COND_IF_DIFF_AF:
			get_ip_port_proto;
			if (ip->af!=snd_i->send_sock->address.af) {
				LUMP_SET_COND_TRUE(l);
				return 1;
			} else return 0;
		case COND_IF_DIFF_PROTO:
			get_ip_port_proto;
			if (proto!=snd_i->send_sock->proto) {
				LUMP_SET_COND_TRUE(l);
				return 1;
			} else return 0;
		case COND_IF_DIFF_PORT:
			get_ip_port_proto;
			if (port!=snd_i->send_sock->port_no) {
				LUMP_SET_COND_TRUE(l);
				return 1;
			} else return 0;
		case COND_IF_DIFF_IP:
			get_ip_port_proto;
			if (ip_addr_cmp(ip, &snd_i->send_sock->address)) return 0;
			else {
				LUMP_SET_COND_TRUE(l);
				return 1;
			}
		case COND_IF_RAND:
			if(rand()>=RAND_MAX/2) {
				LUMP_SET_COND_TRUE(l);
				return 1;
			} else return 0;
		default:
			LM_CRIT("unknown lump condition %d\n", l->u.cond);
	}
	return 0; /* false */
}



/* computes the "unpacked" len of a lump list,
   code moved from build_req_from_req */
static inline int lumps_len(struct sip_msg* msg, struct lump* lumps, 
								struct dest_info* send_info)
{
	int s_offset;
	int new_len;
	struct lump* t;
	struct lump* r;
	str* send_address_str;
	str* send_port_str;
	str* recv_address_str = NULL;
	str* recv_port_str = NULL;
	int  recv_port_no = 0;
	struct socket_info* send_sock;
	

#ifdef USE_COMP
	#define RCVCOMP_LUMP_LEN \
						/* add;comp=xxx */ \
					switch(msg->rcv.comp){ \
						case COMP_NONE: \
								break; \
						case COMP_SIGCOMP: \
								new_len+=COMP_PARAM_LEN+SIGCOMP_NAME_LEN; \
								break; \
						case COMP_SERGZ: \
								new_len+=COMP_PARAM_LEN+SERGZ_NAME_LEN ; \
								break; \
						default: \
						LM_CRIT("unknown comp %d\n", msg->rcv.comp); \
					}

	#define SENDCOMP_LUMP_LEN \
					/* add;comp=xxx */ \
					switch(send_info->comp){ \
						case COMP_NONE: \
								break; \
						case COMP_SIGCOMP: \
								new_len+=COMP_PARAM_LEN+SIGCOMP_NAME_LEN; \
								break; \
						case COMP_SERGZ: \
								new_len+=COMP_PARAM_LEN+SERGZ_NAME_LEN ; \
								break; \
						default: \
						LM_CRIT("unknown comp %d\n", send_info->comp); \
					}
#else
	#define RCVCOMP_LUMP_LEN
	#define SENDCOMP_LUMP_LEN
#endif /*USE_COMP */
	
#define SUBST_LUMP_LEN(subst_l) \
		switch((subst_l)->u.subst){ \
			case SUBST_RCV_IP: \
				if (msg->rcv.bind_address){ \
					new_len+=recv_address_str->len; \
					if (msg->rcv.bind_address->address.af!=AF_INET) \
						new_len+=2; \
				}else{ \
					/* FIXME */ \
					LM_CRIT("FIXME: null bind_address\n"); \
				}; \
				break; \
			case SUBST_RCV_PORT: \
				if (msg->rcv.bind_address){ \
					new_len+=recv_port_str->len; \
				}else{ \
					/* FIXME */ \
					LM_CRIT("FIXME: null bind_address\n"); \
				}; \
				break; \
			case SUBST_RCV_PROTO: \
				if (msg->rcv.bind_address){ \
					switch(msg->rcv.bind_address->proto){ \
						case PROTO_NONE: \
						case PROTO_UDP: \
							new_len+=3; \
							break; \
						case PROTO_TCP: \
						case PROTO_TLS: \
							switch(msg->rcv.proto){ \
								case PROTO_WS: \
								case PROTO_WSS: \
									new_len+=2; \
									break; \
								default: \
									new_len+=3; \
									break; \
							} \
							break; \
						case PROTO_SCTP: \
							new_len+=4; \
							break; \
						default: \
						LM_CRIT("unknown proto %d\n", msg->rcv.bind_address->proto); \
					}\
				}else{ \
					/* FIXME */ \
					LM_CRIT("FIXME: null bind_address\n"); \
				}; \
				break; \
			case SUBST_RCV_ALL: \
				if (msg->rcv.bind_address){ \
					new_len+=recv_address_str->len; \
					if (msg->rcv.bind_address->address.af!=AF_INET) \
						new_len+=2; \
					if (recv_port_no!=SIP_PORT){ \
						/* add :port_no */ \
						new_len+=1+recv_port_str->len; \
					}\
						/*add;transport=xxx*/ \
					switch(msg->rcv.bind_address->proto){ \
						case PROTO_NONE: \
						case PROTO_UDP: \
							break; /* udp is the default */ \
						case PROTO_TCP: \
						case PROTO_TLS: \
							switch(msg->rcv.proto){ \
								case PROTO_WS: \
								case PROTO_WSS: \
									new_len+=TRANSPORT_PARAM_LEN+2; \
									break; \
								default: \
									new_len+=TRANSPORT_PARAM_LEN+3; \
									break; \
							} \
							break; \
						case PROTO_SCTP: \
							new_len+=TRANSPORT_PARAM_LEN+4; \
							break; \
						default: \
						LM_CRIT("unknown proto %d\n", \
								msg->rcv.bind_address->proto); \
					}\
					RCVCOMP_LUMP_LEN \
				}else{ \
					/* FIXME */ \
					LM_CRIT("FIXME: null bind_address\n"); \
				}; \
				break; \
			case SUBST_SND_IP: \
				if (send_sock){ \
					new_len+=send_address_str->len; \
					if (send_sock->address.af!=AF_INET && \
							send_address_str==&(send_sock->address_str)) \
						new_len+=2; \
				}else{ \
					LM_CRIT("FIXME: null send_sock\n"); \
				}; \
				break; \
			case SUBST_SND_PORT: \
				if (send_sock){ \
					new_len+=send_port_str->len; \
				}else{ \
					LM_CRIT("FIXME: null send_sock\n"); \
				}; \
				break; \
			case SUBST_SND_PROTO: \
				if (send_sock){ \
					switch(send_sock->proto){ \
						case PROTO_NONE: \
						case PROTO_UDP: \
							new_len+=3; \
							break; \
						case PROTO_TCP: \
						case PROTO_TLS: \
							switch(send_info->proto){ \
								case PROTO_WS: \
								case PROTO_WSS: \
									new_len+=2; \
									break; \
								default: \
									new_len+=3; \
									break; \
							} \
							break; \
						case PROTO_SCTP: \
							new_len+=4; \
							break; \
						default: \
						LM_CRIT("unknown proto %d\n", send_sock->proto); \
					}\
				}else{ \
					LM_CRIT("FIXME: null send_sock\n"); \
				}; \
				break; \
			case SUBST_SND_ALL: \
				if (send_sock){ \
					new_len+=send_address_str->len; \
					if ((send_sock->address.af!=AF_INET) && \
							(send_address_str==&(send_sock->address_str))) \
						new_len+=2; \
					if ((send_sock->port_no!=SIP_PORT) || \
							(send_port_str!=&(send_sock->port_no_str))){ \
						/* add :port_no */ \
						new_len+=1+send_port_str->len; \
					}\
					/*add;transport=xxx*/ \
					switch(send_sock->proto){ \
						case PROTO_NONE: \
						case PROTO_UDP: \
							break; /* udp is the default */ \
						case PROTO_TCP: \
						case PROTO_TLS: \
							switch(send_info->proto){ \
								case PROTO_WS: \
								case PROTO_WSS: \
									new_len+=TRANSPORT_PARAM_LEN+2; \
									break; \
								default: \
									new_len+=TRANSPORT_PARAM_LEN+3; \
									break; \
							} \
							break; \
						case PROTO_SCTP: \
							new_len+=TRANSPORT_PARAM_LEN+4; \
							break; \
						default: \
						LM_CRIT("unknown proto %d\n", send_sock->proto); \
					}\
					SENDCOMP_LUMP_LEN \
				}else{ \
					/* FIXME */ \
					LM_CRIT("FIXME: null send_sock\n"); \
				}; \
				break; \
			case SUBST_NOP: /* do nothing */ \
				break; \
			default: \
				LM_CRIT("unknown subst type %d\n", (subst_l)->u.subst); \
		}
	
	if (send_info){
		send_sock=send_info->send_sock;
	}else{
		send_sock=0;
	};
	s_offset=0;
	new_len=0;
	/* init send_address_str & send_port_str */
	if(send_sock && send_sock->useinfo.name.len>0)
		send_address_str=&(send_sock->useinfo.name);
	else if (msg->set_global_address.len)
		send_address_str=&(msg->set_global_address);
	else
		send_address_str=&(send_sock->address_str);
	if(send_sock && send_sock->useinfo.port_no>0)
		send_port_str=&(send_sock->useinfo.port_no_str);
	else if (msg->set_global_port.len)
		send_port_str=&(msg->set_global_port);
	else
		send_port_str=&(send_sock->port_no_str);
	/* init recv_address_str, recv_port_str & recv_port_no */
	if(msg->rcv.bind_address) {
		if(msg->rcv.bind_address->useinfo.name.len>0)
			recv_address_str=&(msg->rcv.bind_address->useinfo.name);
		else
			recv_address_str=&(msg->rcv.bind_address->address_str);
		if(msg->rcv.bind_address->useinfo.port_no>0) {
			recv_port_str=&(msg->rcv.bind_address->useinfo.port_no_str);
			recv_port_no = msg->rcv.bind_address->useinfo.port_no;
		} else {
			recv_port_str=&(msg->rcv.bind_address->port_no_str);
			recv_port_no = msg->rcv.bind_address->port_no;
		}
	}

	for(t=lumps;t;t=t->next){
		/* skip if this is an OPT lump and the condition is not satisfied */
		if ((t->op==LUMP_ADD_OPT)&& !lump_check_opt(t, msg, send_info))
			continue;
		for(r=t->before;r;r=r->before){
			switch(r->op){
				case LUMP_ADD:
					new_len+=r->len;
					break;
				case LUMP_ADD_SUBST:
					SUBST_LUMP_LEN(r);
					break;
				case LUMP_ADD_OPT:
					/* skip if this is an OPT lump and the condition is
					 * not satisfied */
					if (!lump_check_opt(r, msg, send_info))
						goto skip_before;
					break;
				default:
					/* only ADD allowed for before/after */
						LM_CRIT("invalid op for data lump (%x)\n", r->op);
			}
		}
skip_before:
		switch(t->op){
			case LUMP_ADD:
				new_len+=t->len;
				break;
			case LUMP_ADD_SUBST:
				SUBST_LUMP_LEN(t);
				break;
			case LUMP_ADD_OPT:
				/* we don't do anything here, it's only a condition for
				 * before & after */
				break;
			case LUMP_DEL:
				/* fix overlapping deleted zones */
				if (t->u.offset < s_offset){
					/* change len */
					if (t->len>s_offset-t->u.offset)
							t->len-=s_offset-t->u.offset;
					else t->len=0;
					t->u.offset=s_offset;
				}
				s_offset=t->u.offset+t->len;
				new_len-=t->len;
				break;
			case LUMP_NOP:
				/* fix offset if overlapping on a deleted zone */
				if (t->u.offset < s_offset){
					t->u.offset=s_offset;
				}else
					s_offset=t->u.offset;
				/* do nothing */
				break;
			default:
				LM_CRIT("invalid op for data lump (%x)\n", r->op);
		}
		for (r=t->after;r;r=r->after){
			switch(r->op){
				case LUMP_ADD:
					new_len+=r->len;
					break;
				case LUMP_ADD_SUBST:
					SUBST_LUMP_LEN(r);
					break;
				case LUMP_ADD_OPT:
					/* skip if this is an OPT lump and the condition is
					 * not satisfied */
					if (!lump_check_opt(r, msg, send_info))
						goto skip_after;
					break;
				default:
					/* only ADD allowed for before/after */
					LM_CRIT("invalid op for data lump (%x)\n", r->op);
			}
		}
skip_after:
		; /* to make gcc 3.* happy */
	}
	return new_len;
#undef RCVCOMP_LUMP_LEN
#undef SENDCOMP_LUMP_LEN
}



/* another helper functions, adds/Removes the lump,
	code moved form build_req_from_req  */

static inline void process_lumps(	struct sip_msg* msg,
					                                struct lump* lumps,
									char* new_buf,
									unsigned int* new_buf_offs,
									unsigned int* orig_offs,
									struct dest_info* send_info)
{
	struct lump *t;
	struct lump *r;
	char* orig;
	int size;
	int offset;
	int s_offset;
	str* send_address_str;
	str* send_port_str;
	str* recv_address_str = NULL;
	str* recv_port_str = NULL;
	int  recv_port_no = 0;
	struct socket_info* send_sock;

#ifdef USE_COMP
	#define RCVCOMP_PARAM_ADD \
				/* add ;comp=xxxx */ \
				switch(msg->rcv.comp){ \
					case COMP_NONE: \
						break; \
					case COMP_SIGCOMP: \
						memcpy(new_buf+offset, COMP_PARAM, COMP_PARAM_LEN);\
						offset+=COMP_PARAM_LEN; \
						memcpy(new_buf+offset, SIGCOMP_NAME, \
								SIGCOMP_NAME_LEN); \
						offset+=SIGCOMP_NAME_LEN; \
						break; \
					case COMP_SERGZ: \
						memcpy(new_buf+offset, COMP_PARAM, COMP_PARAM_LEN);\
						offset+=COMP_PARAM_LEN; \
						memcpy(new_buf+offset, SERGZ_NAME, SERGZ_NAME_LEN); \
						offset+=SERGZ_NAME_LEN; \
						break;\
					default:\
						LM_CRIT("unknown comp %d\n", msg->rcv.comp); \
				}
	
	#define SENDCOMP_PARAM_ADD \
				/* add ;comp=xxxx */ \
				switch(send_info->comp){ \
					case COMP_NONE: \
						break; \
					case COMP_SIGCOMP: \
						memcpy(new_buf+offset, COMP_PARAM, COMP_PARAM_LEN);\
						offset+=COMP_PARAM_LEN; \
						memcpy(new_buf+offset, SIGCOMP_NAME, \
								SIGCOMP_NAME_LEN); \
						offset+=SIGCOMP_NAME_LEN; \
						break; \
					case COMP_SERGZ: \
						memcpy(new_buf+offset, COMP_PARAM, COMP_PARAM_LEN);\
						offset+=COMP_PARAM_LEN; \
						memcpy(new_buf+offset, SERGZ_NAME, SERGZ_NAME_LEN); \
						offset+=SERGZ_NAME_LEN; \
						break;\
					default:\
						LM_CRIT("unknown comp %d\n", msg->rcv.comp); \
				} 
#else
	#define RCVCOMP_PARAM_ADD
	#define SENDCOMP_PARAM_ADD
#endif /* USE_COMP */

#define SUBST_LUMP(subst_l) \
	switch((subst_l)->u.subst){ \
		case SUBST_RCV_IP: \
			if (msg->rcv.bind_address){  \
				if (msg->rcv.bind_address->address.af!=AF_INET){\
					new_buf[offset]='['; offset++; \
				}\
				memcpy(new_buf+offset, recv_address_str->s, \
						recv_address_str->len); \
				offset+=recv_address_str->len; \
				if (msg->rcv.bind_address->address.af!=AF_INET){\
					new_buf[offset]=']'; offset++; \
				}\
			}else{  \
				/*FIXME*/ \
				LM_CRIT("FIXME: null bind_address\n"); \
			}; \
			break; \
		case SUBST_RCV_PORT: \
			if (msg->rcv.bind_address){  \
				memcpy(new_buf+offset, recv_port_str->s, \
						recv_port_str->len); \
				offset+=recv_port_str->len; \
			}else{  \
				/*FIXME*/ \
				LM_CRIT("FIXME: null bind_address\n"); \
			}; \
			break; \
		case SUBST_RCV_ALL: \
			if (msg->rcv.bind_address){  \
				/* address */ \
				if (msg->rcv.bind_address->address.af!=AF_INET){\
					new_buf[offset]='['; offset++; \
				}\
				memcpy(new_buf+offset, recv_address_str->s, \
						recv_address_str->len); \
				offset+=recv_address_str->len; \
				if (msg->rcv.bind_address->address.af!=AF_INET){\
					new_buf[offset]=']'; offset++; \
				}\
				/* :port */ \
				if (recv_port_no!=SIP_PORT){ \
					new_buf[offset]=':'; offset++; \
					memcpy(new_buf+offset, \
							recv_port_str->s, \
							recv_port_str->len); \
					offset+=recv_port_str->len; \
				}\
				switch(msg->rcv.bind_address->proto){ \
					case PROTO_NONE: \
					case PROTO_UDP: \
						break; /* nothing to do, udp is default*/ \
					case PROTO_TCP: \
						memcpy(new_buf+offset, TRANSPORT_PARAM, \
								TRANSPORT_PARAM_LEN); \
						offset+=TRANSPORT_PARAM_LEN; \
						if (msg->rcv.proto == PROTO_WS) { \
							memcpy(new_buf+offset, "ws", 2); \
							offset+=2; \
						} else { \
							memcpy(new_buf+offset, "tcp", 3); \
							offset+=3; \
						} \
						break; \
					case PROTO_TLS: \
						memcpy(new_buf+offset, TRANSPORT_PARAM, \
								TRANSPORT_PARAM_LEN); \
						offset+=TRANSPORT_PARAM_LEN; \
						if (msg->rcv.proto == PROTO_WS || msg->rcv.proto == PROTO_WSS) { \
							memcpy(new_buf+offset, "ws", 2); \
							offset+=2; \
						} else { \
							memcpy(new_buf+offset, "tls", 3); \
							offset+=3; \
						} \
						break; \
					case PROTO_SCTP: \
						memcpy(new_buf+offset, TRANSPORT_PARAM, \
								TRANSPORT_PARAM_LEN); \
						offset+=TRANSPORT_PARAM_LEN; \
						memcpy(new_buf+offset, "sctp", 4); \
						offset+=4; \
						break; \
					default: \
						LM_CRIT("unknown proto %d\n", msg->rcv.bind_address->proto); \
				} \
				RCVCOMP_PARAM_ADD \
			}else{  \
				/*FIXME*/ \
				LM_CRIT("FIXME: null bind_address\n"); \
			}; \
			break; \
		case SUBST_SND_IP: \
			if (send_sock){  \
				if ((send_sock->address.af!=AF_INET) && \
						(send_address_str==&(send_sock->address_str))){\
					new_buf[offset]='['; offset++; \
				}\
				memcpy(new_buf+offset, send_address_str->s, \
									send_address_str->len); \
				offset+=send_address_str->len; \
				if ((send_sock->address.af!=AF_INET) && \
						(send_address_str==&(send_sock->address_str))){\
					new_buf[offset]=']'; offset++; \
				}\
			}else{  \
				/*FIXME*/ \
				LM_CRIT("FIXME: null send_sock\n"); \
			}; \
			break; \
		case SUBST_SND_PORT: \
			if (send_sock){  \
				memcpy(new_buf+offset, send_port_str->s, \
									send_port_str->len); \
				offset+=send_port_str->len; \
			}else{  \
				/*FIXME*/ \
				LM_CRIT("FIXME: null send_sock\n"); \
			}; \
			break; \
		case SUBST_SND_ALL: \
			if (send_sock){  \
				/* address */ \
				if ((send_sock->address.af!=AF_INET) && \
						(send_address_str==&(send_sock->address_str))){\
					new_buf[offset]='['; offset++; \
				}\
				memcpy(new_buf+offset, send_address_str->s, \
						send_address_str->len); \
				offset+=send_address_str->len; \
				if ((send_sock->address.af!=AF_INET) && \
						(send_address_str==&(send_sock->address_str))){\
					new_buf[offset]=']'; offset++; \
				}\
				/* :port */ \
				if ((send_sock->port_no!=SIP_PORT) || \
					(send_port_str!=&(send_sock->port_no_str))){ \
					new_buf[offset]=':'; offset++; \
					memcpy(new_buf+offset, send_port_str->s, \
							send_port_str->len); \
					offset+=send_port_str->len; \
				}\
				switch(send_sock->proto){ \
					case PROTO_NONE: \
					case PROTO_UDP: \
						break; /* nothing to do, udp is default*/ \
					case PROTO_TCP: \
						memcpy(new_buf+offset, TRANSPORT_PARAM, \
								TRANSPORT_PARAM_LEN); \
						offset+=TRANSPORT_PARAM_LEN; \
						if (send_info->proto == PROTO_WS) { \
							memcpy(new_buf+offset, "ws", 2); \
							offset+=2; \
						} else { \
							memcpy(new_buf+offset, "tcp", 3); \
							offset+=3; \
						} \
						break; \
					case PROTO_TLS: \
						memcpy(new_buf+offset, TRANSPORT_PARAM, \
								TRANSPORT_PARAM_LEN); \
						offset+=TRANSPORT_PARAM_LEN; \
						if (send_info->proto == PROTO_WS || send_info->proto == PROTO_WSS) { \
							memcpy(new_buf+offset, "ws", 2); \
							offset+=2; \
						} else { \
							memcpy(new_buf+offset, "tls", 3); \
							offset+=3; \
						} \
						break; \
					case PROTO_SCTP: \
						memcpy(new_buf+offset, TRANSPORT_PARAM, \
								TRANSPORT_PARAM_LEN); \
						offset+=TRANSPORT_PARAM_LEN; \
						memcpy(new_buf+offset, "sctp", 4); \
						offset+=4; \
						break; \
					default: \
						LM_CRIT("unknown proto %d\n", send_sock->proto); \
				} \
				SENDCOMP_PARAM_ADD \
			}else{  \
				/*FIXME*/ \
				LM_CRIT("FIXME: null bind_address\n"); \
			}; \
			break; \
		case SUBST_RCV_PROTO: \
			if (msg->rcv.bind_address){ \
				switch(msg->rcv.bind_address->proto){ \
					case PROTO_NONE: \
					case PROTO_UDP: \
						memcpy(new_buf+offset, "udp", 3); \
						offset+=3; \
						break; \
					case PROTO_TCP: \
						if (msg->rcv.proto == PROTO_WS) { \
							memcpy(new_buf+offset, "ws", 2); \
							offset+=2; \
						} else { \
							memcpy(new_buf+offset, "tcp", 3); \
							offset+=3; \
						} \
						break; \
					case PROTO_TLS: \
						if (msg->rcv.proto == PROTO_WS || msg->rcv.proto == PROTO_WSS) { \
							memcpy(new_buf+offset, "ws", 2); \
							offset+=2; \
						} else { \
							memcpy(new_buf+offset, "tls", 3); \
							offset+=3; \
						} \
						break; \
					case PROTO_SCTP: \
						memcpy(new_buf+offset, "sctp", 4); \
						offset+=4; \
						break; \
					default: \
						LM_CRIT("unknown proto %d\n", msg->rcv.bind_address->proto); \
				} \
			}else{  \
				/*FIXME*/ \
				LM_CRIT("FIXME: null send_sock \n"); \
			}; \
			break; \
		case  SUBST_SND_PROTO: \
			if (send_sock){ \
				switch(send_sock->proto){ \
					case PROTO_NONE: \
					case PROTO_UDP: \
						memcpy(new_buf+offset, "udp", 3); \
						offset+=3; \
						break; \
					case PROTO_TCP: \
						if (send_info->proto == PROTO_WS) { \
							memcpy(new_buf+offset, "ws", 2); \
							offset+=2; \
						} else { \
							memcpy(new_buf+offset, "tcp", 3); \
							offset+=3; \
						} \
						break; \
					case PROTO_TLS: \
						if (send_info->proto == PROTO_WS || send_info->proto == PROTO_WSS) { \
							memcpy(new_buf+offset, "ws", 2); \
							offset+=2; \
						} else { \
							memcpy(new_buf+offset, "tls", 3); \
							offset+=3; \
						} \
						break; \
					case PROTO_SCTP: \
						memcpy(new_buf+offset, "sctp", 4); \
						offset+=4; \
						break; \
					default: \
						LM_CRIT("unknown proto %d\n", send_sock->proto); \
				} \
			}else{  \
				/*FIXME*/ \
				LM_CRIT("FIXME: null send_sock \n"); \
			}; \
			break; \
		default: \
				LM_CRIT("unknown subst type %d\n", (subst_l)->u.subst); \
	}

	if (send_info){
		send_sock=send_info->send_sock;
	}else{
		send_sock=0;
	}
	/* init send_address_str & send_port_str */
	if (msg->set_global_address.len)
		send_address_str=&(msg->set_global_address);
	else
		send_address_str=&(send_sock->address_str);
	if (msg->set_global_port.len)
		send_port_str=&(msg->set_global_port);
	else
		send_port_str=&(send_sock->port_no_str);
	/* init send_address_str & send_port_str */
	if(send_sock && send_sock->useinfo.name.len>0)
		send_address_str=&(send_sock->useinfo.name);
	else if (msg->set_global_address.len)
		send_address_str=&(msg->set_global_address);
	else
		send_address_str=&(send_sock->address_str);
	if(send_sock && send_sock->useinfo.port_no>0)
		send_port_str=&(send_sock->useinfo.port_no_str);
	else if (msg->set_global_port.len)
		send_port_str=&(msg->set_global_port);
	else
		send_port_str=&(send_sock->port_no_str);
	/* init recv_address_str, recv_port_str & recv_port_no */
	if(msg->rcv.bind_address) {
		if(msg->rcv.bind_address->useinfo.name.len>0)
			recv_address_str=&(msg->rcv.bind_address->useinfo.name);
		else
			recv_address_str=&(msg->rcv.bind_address->address_str);
		if(msg->rcv.bind_address->useinfo.port_no>0) {
			recv_port_str=&(msg->rcv.bind_address->useinfo.port_no_str);
			recv_port_no = msg->rcv.bind_address->useinfo.port_no;
		} else {
			recv_port_str=&(msg->rcv.bind_address->port_no_str);
			recv_port_no = msg->rcv.bind_address->port_no;
		}
	}

	orig=msg->buf;
	offset=*new_buf_offs;
	s_offset=*orig_offs;

	for (t=lumps;t;t=t->next){
		switch(t->op){
			case LUMP_ADD:
			case LUMP_ADD_SUBST:
			case LUMP_ADD_OPT:
				/* skip if this is an OPT lump and the condition is
				 * not satisfied */
				if ((t->op==LUMP_ADD_OPT) &&
						(!lump_check_opt(t, msg, send_info)))
					continue;
				/* just add it here! */
				/* process before  */
				for(r=t->before;r;r=r->before){
					switch (r->op){
						case LUMP_ADD:
							/*just add it here*/
							memcpy(new_buf+offset, r->u.value, r->len);
							offset+=r->len;
							break;
						case LUMP_ADD_SUBST:
							SUBST_LUMP(r);
							break;
						case LUMP_ADD_OPT:
							/* skip if this is an OPT lump and the condition is
					 		* not satisfied */
							if (!lump_check_opt(r, msg, send_info))
								goto skip_before;
							break;
						default:
							/* only ADD allowed for before/after */
							LM_CRIT("invalid op for data lump (%x)\n", r->op);
					}
				}
skip_before:
				/* copy "main" part */
				switch(t->op){
					case LUMP_ADD:
						memcpy(new_buf+offset, t->u.value, t->len);
						offset+=t->len;
						break;
					case LUMP_ADD_SUBST:
						SUBST_LUMP(t);
						break;
					case LUMP_ADD_OPT:
						/* do nothing, it's only a condition */
						break;
					default:
						/* should not ever get here */
						LM_CRIT("unhandled data lump op %d\n", t->op);
				}
				/* process after */
				for(r=t->after;r;r=r->after){
					switch (r->op){
						case LUMP_ADD:
							/*just add it here*/
							memcpy(new_buf+offset, r->u.value, r->len);
							offset+=r->len;
							break;
						case LUMP_ADD_SUBST:
							SUBST_LUMP(r);
							break;
						case LUMP_ADD_OPT:
							/* skip if this is an OPT lump and the condition is
					 		* not satisfied */
							if (!lump_check_opt(r, msg, send_info))
								goto skip_after;
							break;
						default:
							/* only ADD allowed for before/after */
							LM_CRIT("invalid op for data lump (%x)\n", r->op);
					}
				}
skip_after:
				break;
			case LUMP_NOP:
			case LUMP_DEL:
				/* copy till offset */
				if (s_offset>t->u.offset){
					DBG("Warning: (%d) overlapped lumps offsets,"
						" ignoring(%x, %x)\n", t->op, s_offset,t->u.offset);
					/* this should've been fixed above (when computing len) */
					/* just ignore it*/
					break;
				}
				size=t->u.offset-s_offset;
				if (size){
					memcpy(new_buf+offset, orig+s_offset,size);
					offset+=size;
					s_offset+=size;
				}
				/* process before  */
				for(r=t->before;r;r=r->before){
					switch (r->op){
						case LUMP_ADD:
							/*just add it here*/
							memcpy(new_buf+offset, r->u.value, r->len);
							offset+=r->len;
							break;
						case LUMP_ADD_SUBST:
							SUBST_LUMP(r);
							break;
						case LUMP_ADD_OPT:
							/* skip if this is an OPT lump and the condition is
					 		* not satisfied */
							if (!lump_check_opt(r, msg, send_info))
								goto skip_nop_before;
							break;
						default:
							/* only ADD allowed for before/after */
							LM_CRIT("invalid op for data lump (%x)\n",r->op);
					}
				}
skip_nop_before:
				/* process main (del only) */
				if (t->op==LUMP_DEL){
					/* skip len bytes from orig msg */
					s_offset+=t->len;
				}
				/* process after */
				for(r=t->after;r;r=r->after){
					switch (r->op){
						case LUMP_ADD:
							/*just add it here*/
							memcpy(new_buf+offset, r->u.value, r->len);
							offset+=r->len;
							break;
						case LUMP_ADD_SUBST:
							SUBST_LUMP(r);
							break;
						case LUMP_ADD_OPT:
							/* skip if this is an OPT lump and the condition is
					 		* not satisfied */
							if (!lump_check_opt(r, msg, send_info))
								goto skip_nop_after;
							break;
						default:
							/* only ADD allowed for before/after */
							LM_CRIT("invalid op for data lump (%x)\n", r->op);
					}
				}
skip_nop_after:
				break;
			default:
					LM_CRIT("unknown op (%x)\n", t->op);
		}
	}
	*new_buf_offs=offset;
	*orig_offs=s_offset;
#undef RCVCOMP_PARAM_ADD 
#undef SENDCOMP_PARAM_ADD
}


/*
 * Adjust/insert Content-Length if necessary
 */
static inline int adjust_clen(struct sip_msg* msg, int body_delta, int proto)
{
	struct lump* anchor;
	char* clen_buf;
	int clen_len, body_only;
#ifdef USE_TCP
	char* body;
	int comp_clen;
#endif /* USE_TCP */

	/* Calculate message length difference caused by lumps modifying message
	 * body, from this point on the message body must not be modified. Zero
	 * value indicates that the body hasn't been modified
	*/

	clen_buf = 0;
	anchor=0;
	body_only=1;

	/* check to see if we need to add clen */
#ifdef USE_TCP
	if (proto == PROTO_TCP
#ifdef USE_TLS
	    || proto == PROTO_TLS
#endif
	    ) {
		if (parse_headers(msg, HDR_CONTENTLENGTH_F, 0)==-1){
			LM_ERR("error parsing content-length\n");
			goto error;
		}
		if (unlikely(msg->content_length==0)){
			/* not present, we need to add it */
			/* msg->unparsed should point just before the final crlf
			 * - whole message was parsed by the above parse_headers
			 *   which did not find content-length */
			anchor=anchor_lump(msg, msg->unparsed-msg->buf, 0,
												HDR_CONTENTLENGTH_T);
			if (anchor==0){
				LM_ERR("cannot set clen anchor\n");
				goto error;
			}
			body_only=0;
		}else{
			/* compute current content length and compare it with the
			   one in the message */
			body=get_body(msg);
			if (unlikely(body==0)){
				ser_error=E_BAD_REQ;
				LM_ERR("no message body found (missing crlf?)");
				goto error;
			}
			comp_clen=msg->len-(int)(body-msg->buf)+body_delta;
			if (comp_clen!=(int)(long)msg->content_length->parsed){
				/* note: we don't distinguish here between received with
				   wrong content-length and content-length changed, we just
				   fix it automatically in both cases (the reason being
				   that an error message telling we have received a msg-
				   with wrong content-length is of very little use) */
				anchor = del_lump(msg, msg->content_length->body.s-msg->buf,
									msg->content_length->body.len,
									HDR_CONTENTLENGTH_T);
				if (anchor==0) {
					LM_ERR("Can't remove original Content-Length\n");
					goto error;
				}
				body_only=1;
			}
		}
	}else
#endif /* USE_TCP */
	if (body_delta){
		if (parse_headers(msg, HDR_CONTENTLENGTH_F, 0) == -1) {
			LM_ERR("Error parsing Content-Length\n");
			goto error;
		}

		/* The body has been changed, try to find
		 * existing Content-Length
		 */
		/* no need for Content-Length if it's and UDP packet and
		 * it hasn't Content-Length already */
		if (msg->content_length==0){
		    /* content-length doesn't exist, append it */
			/* msg->unparsed should point just before the final crlf
			 * - whole message was parsed by the above parse_headers
			 *   which did not find content-length */
			if (proto!=PROTO_UDP){
				anchor=anchor_lump(msg, msg->unparsed-msg->buf, 0,
													HDR_CONTENTLENGTH_T);
				if (anchor==0){
					LM_ERR("cannot set clen anchor\n");
					goto error;
				}
				body_only=0;
			} /* else
				DBG("adjust_clen: UDP packet with no clen => "
						"not adding one \n"); */
		}else{
			/* Content-Length has been found, remove it */
			anchor = del_lump(	msg, msg->content_length->body.s - msg->buf,
								msg->content_length->body.len,
								HDR_CONTENTLENGTH_T);
			if (anchor==0) {
				LM_ERR("Can't remove original Content-Length\n");
				goto error;
			}
		}
	}

	if (anchor){
		clen_buf = clen_builder(msg, &clen_len, body_delta, body_only);
		if (!clen_buf) goto error;
		if (insert_new_lump_after(anchor, clen_buf, clen_len,
					HDR_CONTENTLENGTH_T) == 0)
			goto error;
	}
	
	return 0;
error:
	if (clen_buf) pkg_free(clen_buf);
	return -1;
}

static inline int find_line_start(char *text, unsigned int text_len,
				  char **buf, unsigned int *buf_len)
{
	char *ch, *start;
	unsigned int len;

	start = *buf;
	len = *buf_len;

	while (text_len <= len) {
		if (strncmp(text, start, text_len) == 0) {
			*buf = start;
			*buf_len = len;
			return 1;
		}
		if ((ch = memchr(start, 13, len - 1))) {
			if (*(ch + 1) != 10) {
				LM_ERR("No LF after CR\n");
				return 0;
			}
			len = len - (ch - start + 2);
			start = ch + 2;
		} else {
			LM_ERR("No CRLF found\n");
			return 0;
		}
	}
	return 0;
}

static inline int get_line(str s)
{
	char *ch;

	if ((ch = memchr(s.s, 13, s.len))) {
		if (*(ch + 1) != 10) {
			LM_ERR("No LF after CR\n");
			return 0;
		}
		return ch - s.s + 2;
	} else {
		LM_ERR("No CRLF found\n");
		return s.len;
	}
	return 0;
}

int replace_body(struct sip_msg *msg, str txt)
{
	struct lump *anchor;
	char *buf;
	str body = {0,0};

	body.s = get_body(msg);
	if(body.s==0)
	{
		LM_ERR("malformed sip message\n");
		return 0;
	}
	body.len = msg->len -(int)(body.s-msg->buf);
	LM_DBG("old size body[%d] actual[%d]\n", body.len, txt.len);
	if(body.s+body.len>msg->buf+msg->len)
	{
		LM_ERR("invalid content length: %d\n", body.len);
		return 0;
	}
	del_nonshm_lump( &(msg->body_lumps) );
	msg->body_lumps = NULL;

	if(del_lump(msg, body.s-msg->buf, body.len, 0) == 0)
	{
		LM_ERR("cannot delete existing body");
		return 0;
	}

	anchor = anchor_lump(msg, body.s - msg->buf, 0, 0);
	if(anchor==0)
	{
		LM_ERR("failed to get anchor\n");
		return 0;
	}

	buf=pkg_malloc(sizeof(char)*txt.len);
	if(buf==0)
	{
		PKG_MEM_ERROR;
		return 0;
	}
	memcpy(buf, txt.s, txt.len);
	if(insert_new_lump_after(anchor, buf, txt.len, 0)==0)
	{
		LM_ERR("failed to insert body lump\n");
		pkg_free(buf);
		return 0;
	}
	return 1;
}

/**
 * returns the boundary defined by the Content-Type
 * header
 */
int get_boundary(struct sip_msg* msg, str* boundary)
{
	str params;
	param_t *p, *list;
	param_hooks_t hooks;

	params.s = memchr(msg->content_type->body.s, ';',
		msg->content_type->body.len);
	if (params.s == NULL)
	{
		LM_ERR("Content-Type hdr has no params\n");
		return -1;
	}
	params.len = msg->content_type->body.len -
		(params.s - msg->content_type->body.s);
	if (parse_params(&params, CLASS_ANY, &hooks, &list) < 0)
	{
		LM_ERR("while parsing Content-Type params\n");
		return -1;
	}
	boundary->s = NULL;
	boundary->len = 0;
	for (p = list; p; p = p->next) {
		if ((p->name.len == 8)
			&& (strncasecmp(p->name.s, "boundary", 8) == 0))
		{
			boundary->s = pkg_malloc(p->body.len + 2);
			if (boundary->s == NULL)
			{
				free_params(list);
				LM_ERR("no memory for boundary string\n");
				return -1;
			}
			*(boundary->s) = '-';
			*(boundary->s + 1) = '-';
			memcpy(boundary->s + 2, p->body.s, p->body.len);
			boundary->len = 2 + p->body.len;
			LM_DBG("boundary is <%.*s>\n", boundary->len, boundary->s);
			break;
		}
	}
	free_params(list);
	return 0;
}

int check_boundaries(struct sip_msg *msg, struct dest_info *send_info)
{
	str b = {0,0};
	str fb = {0,0};
	str ob = {0,0};
	str bsuffix = {"\r\n", 2};
	str fsuffix = {"--\r\n", 4};
	str body = {0,0};
	str buf = {0,0};
	str tmp = {0,0};
	struct str_list* lb = NULL;
	struct str_list* lb_t = NULL;
	int lb_found = 0;
	int t, ret, lb_size;
	char *pb;

	if(!(msg->msg_flags&FL_BODY_MULTIPART)) return 0;
	else
	{
		buf.s = build_body(msg, (unsigned int *)&buf.len, &ret, send_info);
		if(ret) {
			LM_ERR("Can't get body\n");
			return -1;
		}
		tmp.s = buf.s;
		t = tmp.len = buf.len;
		if(get_boundary(msg, &ob)!=0) return -1;
		if(str_append(&ob, &bsuffix, &b)!=0) {
			LM_ERR("Can't append suffix to boundary\n");
			goto error;
		}
		if(str_append(&ob, &fsuffix,&fb)!=0) {
			LM_ERR("Can't append suffix to final boundary\n");
			goto error;
		}
		ret = b.len-2;
		while(t>0)
		{
			if(find_line_start(b.s, ret, &tmp.s,
				(unsigned int *)&tmp.len))
			{
				/*LM_DBG("found t[%d] tmp.len[%d]:[%.*s]\n",
					t, tmp.len, tmp.len, tmp.s);*/
				if(!lb)
				{
					lb = pkg_malloc(sizeof(struct str_list));
					if (!lb) {
						PKG_MEM_ERROR;
						goto error;
					}
					lb->s.s = tmp.s;
					lb->s.len = tmp.len;
					lb->next = 0;
					lb_t = lb;
				}
				else
				{
					lb_t = append_str_list(tmp.s, tmp.len, &lb_t, &lb_size);
				}
				lb_found = lb_found + 1;
				tmp.s = tmp.s + ret;
				t =  t - ret;
				tmp.len = tmp.len - ret;
			}
			else { t=0; }
		}
		if(lb_found<2)
		{
			LM_ERR("found[%d] wrong number of boundaries\n", lb_found);
			goto error;
		}
		/* adding 2 chars in advance */
		body.len = buf.len + 2;
		body.s = pkg_malloc(sizeof(char)*body.len);
		if (!body.s) {
			PKG_MEM_ERROR;
			goto error;
		}
		pb = body.s; body.len = 0;
		lb_t = lb;
		while(lb_t)
		{
			tmp.s = lb_t->s.s; tmp.len = lb_t->s.len;
			tmp.len = get_line(lb_t->s);
			if(tmp.len!=b.len || strncmp(b.s, tmp.s, b.len)!=0)
			{
				LM_DBG("malformed bondary in the middle\n");
				memcpy(pb, b.s, b.len); body.len = body.len + b.len;
				pb = pb + b.len;
				t = lb_t->s.s - (lb_t->s.s + tmp.len);
				memcpy(pb, lb_t->s.s+tmp.len, t); pb = pb + t;
				/*LM_DBG("new chunk[%d][%.*s]\n", t, t, pb-t);*/
			}
			else {
				t = lb_t->next->s.s - lb_t->s.s;
				memcpy(pb, lb_t->s.s, t);
				/*LM_DBG("copy[%d][%.*s]\n", t, t, pb);*/
				pb = pb + t;
			}
			body.len = body.len + t;
			/*LM_DBG("body[%d][%.*s]\n", body.len, body.len, body.s);*/
			lb_t = lb_t->next;
			if(!lb_t->next) lb_t = NULL;
		}
		/* last boundary */
		tmp.s = lb->s.s; tmp.len = lb->s.len;
		tmp.len = get_line(lb->s);
		if(tmp.len!=fb.len || strncmp(fb.s, tmp.s, fb.len)!=0)
		{
			LM_DBG("last bondary without -- at the end\n");
			memcpy(pb, fb.s, fb.len);
			/*LM_DBG("new chunk[%d][%.*s]\n", fb.len, fb.len, pb);*/
			pb = pb + fb.len;
			body.len = body.len + fb.len;
		}
		else {
			memcpy(pb, lb->s.s, lb->s.len); pb = pb + lb->s.len;
			body.len = body.len + lb->s.len;
			/*LM_DBG("copy[%d][%.*s]\n", lb->s.len, lb->s.len, pb - lb->s.len);*/
		}
		/*LM_DBG("body[%d][%.*s] expected[%ld]\n",
			body.len, body.len, body.s, pb-body.s); */
		if(!replace_body(msg, body))
		{
			LM_ERR("Can't replace body\n");
			goto error;
		}
		msg->msg_flags &= ~FL_BODY_MULTIPART;
		ret = 1;
		goto clean;
	}

error:
	ret = -1;
clean:
	if(ob.s) pkg_free(ob.s);
	if(b.s) pkg_free(b.s);
	if(fb.s) pkg_free(fb.s);
	if(body.s) pkg_free(body.s);
	if(buf.s) pkg_free(buf.s);
	while(lb)
	{
		lb_t = lb->next;
		pkg_free(lb);
		lb = lb_t;
	}
	return ret;
}

/** builds a request in memory from another sip request.
  *
  * Side-effects: - it adds lumps to the msg which are _not_ cleaned.
  * The added lumps are HDR_VIA_T (almost always added), HDR_CONTENLENGTH_T
  * and HDR_ROUTE_T (when a Route: header is added as a result of a non-null
  * msg->path_vec).
  *               - it might change send_info->proto and send_info->send_socket
  *                 if proto fallback is enabled (see below).
  *
  * Uses also global_req_flags ( OR'ed with msg->msg_flags, see send_info
  * below).
  *
  * @param msg  - sip message structure, complete with lumps
  * @param returned_len - result length (filled in)
  * @param send_info  - dest_info structure (value/result), contains where the
  *                     packet will be sent to (it's needed for building a 
  *                     correct via, fill RR lumps a.s.o.). If MTU based
  *                     protocol fall-back is enabled (see flags below),
  *                     send_info->proto might be updated with the new
  *                     protocol.
  *                     msg->msg_flags used:
  *                     - FL_TCP_MTU_FB, FL_TLS_MTU_FB and FL_SCTP_MTU_FB -
  *                       fallback to the corresp. proto if the built 
  *                       message > mtu and send_info->proto==PROTO_UDP. 
  *                       It will also update send_info->proto.
  *                     - FL_FORCE_RPORT: add rport to via
  * @param mode - flags for building the message, can be a combination of:
  *                 * BUILD_NO_LOCAL_VIA - don't add a local via
  *                 * BUILD_NO_VIA1_UPDATE - don't update first via (rport,
  *                    received a.s.o)
  *                 * BUILD_NO_PATH - don't add a Route: header with the 
  *                   msg->path_vec content.
  *                 * BUILD_IN_SHM - build the result in shm memory
  *
  * @return pointer to the new request (pkg_malloc'ed or shm_malloc'ed,
  * depending on the presence of the BUILD_IN_SHM flag, needs freeing when
  *   done) and sets returned_len or 0 on error.
  */
char * build_req_buf_from_sip_req( struct sip_msg* msg,
								unsigned int *returned_len,
								struct dest_info* send_info,
								unsigned int mode)
{
	unsigned int len, new_len, received_len, rport_len, uri_len, via_len,
				 body_delta;
	char* line_buf;
	char* received_buf;
	char* rport_buf;
	char* new_buf;
	char* buf;
	str path_buf;
	unsigned int offset, s_offset, size;
	struct lump* via_anchor;
	struct lump* via_lump;
	struct lump* via_insert_param;
	struct lump* path_anchor;
	struct lump* path_lump;
	str branch;
	unsigned int flags;
	unsigned int udp_mtu;
	struct dest_info di;

	via_insert_param=0;
	uri_len=0;
	buf=msg->buf;
	len=msg->len;
	received_len=0;
	rport_len=0;
	new_buf=0;
	received_buf=0;
	rport_buf=0;
	via_anchor=0;
	line_buf=0;
	via_len=0;
	path_buf.s=0;
	path_buf.len=0;

	flags=msg->msg_flags|global_req_flags;
	if(check_boundaries(msg, send_info)<0){
		LM_WARN("check_boundaries error\n");
	}
	/* Calculate message body difference and adjust Content-Length */
	body_delta = lumps_len(msg, msg->body_lumps, send_info);
	if (adjust_clen(msg, body_delta, send_info->proto) < 0) {
		LM_ERR("Error while adjusting Content-Length\n");
		goto error00;
	}

	if(unlikely(mode&BUILD_NO_LOCAL_VIA))
		goto after_local_via;

	/* create the via header */
	branch.s=msg->add_to_branch_s;
	branch.len=msg->add_to_branch_len;

	via_anchor=anchor_lump(msg, msg->via1->hdr.s-buf, 0, HDR_VIA_T);
	if (unlikely(via_anchor==0)) goto error00;
	line_buf = create_via_hf( &via_len, msg, send_info, &branch);
	if (unlikely(!line_buf)){
		LM_ERR("could not create Via header\n");
		goto error00;
	}
after_local_via:
	if(unlikely(mode&BUILD_NO_VIA1_UPDATE))
		goto after_update_via1;
	/* check if received needs to be added */
	if ( received_test(msg) ) {
		if ((received_buf=received_builder(msg,&received_len))==0){
			LM_ERR("received_builder failed\n");
			goto error01;  /* free also line_buf */
		}
	}

	/* check if rport needs to be updated:
	 *  - if FL_FORCE_RPORT is set add it (and del. any previous version)
	 *  - if via already contains an rport add it and overwrite the previous
	 *  rport value if present (if you don't want to overwrite the previous
	 *  version remove the comments) */
	if ((flags&FL_FORCE_RPORT)||
			(msg->via1->rport /*&& msg->via1->rport->value.s==0*/)){
		if ((rport_buf=rport_builder(msg, &rport_len))==0){
			LM_ERR("rport_builder failed\n");
			goto error01; /* free everything */
		}
	}

	/* find out where the offset of the first parameter that should be added
	 * (after host:port), needed by add receive & maybe rport */
	if (msg->via1->params.s){
			size= msg->via1->params.s-msg->via1->hdr.s-1; /*compensate
														  for ';' */
	}else{
			size= msg->via1->host.s-msg->via1->hdr.s+msg->via1->host.len;
			if (msg->via1->port!=0){
				/*size+=strlen(msg->via1->hdr.s+size+1)+1;*/
				size += msg->via1->port_str.len + 1; /* +1 for ':'*/
			}
#if 0
			/* no longer necessary, now hots.s contains [] */
			if(send_sock->address.af==AF_INET6) size+=1; /* +1 for ']'*/
#endif
	}
	/* if received needs to be added, add anchor after host and add it, or
	 * overwrite the previous one if already present */
	if (received_len){
		if (msg->via1->received){ /* received already present => overwrite it*/
			via_insert_param=del_lump(msg,
								msg->via1->received->start-buf-1, /*;*/
								msg->via1->received->size+1, /*;*/ HDR_VIA_T);
		}else if (via_insert_param==0){ /* receive not present, ok */
			via_insert_param=anchor_lump(msg, msg->via1->hdr.s-buf+size, 0,
											HDR_VIA_T);
		}
		if (via_insert_param==0) goto error02; /* free received_buf */
		if (insert_new_lump_after(via_insert_param, received_buf, received_len,
					HDR_VIA_T) ==0 ) goto error02; /* free received_buf */
	}
	/* if rport needs to be updated, delete it if present and add it's value */
	if (rport_len){
		if (msg->via1->rport){ /* rport already present */
			via_insert_param=del_lump(msg,
								msg->via1->rport->start-buf-1, /*';'*/
								msg->via1->rport->size+1 /* ; */, HDR_VIA_T);
		}else if (via_insert_param==0){ /*force rport, no rport present */
			/* no rport, add it */
			via_insert_param=anchor_lump(msg, msg->via1->hdr.s-buf+size, 0,
											HDR_VIA_T);
		}
		if (via_insert_param==0) goto error03; /* free rport_buf */
		if (insert_new_lump_after(via_insert_param, rport_buf, rport_len,
									HDR_VIA_T) ==0 )
			goto error03; /* free rport_buf */

	}

after_update_via1:
	/* add route with path content */
	if(unlikely(!(mode&BUILD_NO_PATH) && msg->path_vec.s &&
					msg->path_vec.len)){
		path_buf.len=ROUTE_PREFIX_LEN+msg->path_vec.len+CRLF_LEN;
		path_buf.s=pkg_malloc(path_buf.len+1);
		if (unlikely(path_buf.s==0)){
			LM_ERR("out of memory\n");
			ser_error=E_OUT_OF_MEM;
			goto error00;
		}
		memcpy(path_buf.s, ROUTE_PREFIX, ROUTE_PREFIX_LEN);
		memcpy(path_buf.s+ROUTE_PREFIX_LEN, msg->path_vec.s,
					msg->path_vec.len);
		memcpy(path_buf.s+ROUTE_PREFIX_LEN+msg->path_vec.len, CRLF, CRLF_LEN);
		path_buf.s[path_buf.len]=0;
		/* insert Route header either before the other routes
		   (if present & parsed), after the local via or after in front of
		    the first via if we don't add a local via*/
		if (msg->route){
			path_anchor=anchor_lump(msg, msg->route->name.s-buf, 0, 
									HDR_ROUTE_T);
		}else if (likely(via_anchor)){
			path_anchor=via_anchor;
		}else if (likely(msg->via1)){
			path_anchor=anchor_lump(msg, msg->via1->hdr.s-buf, 0, 
									HDR_ROUTE_T);
		}else{
			/* if no via1 (theoretically possible for non-sip messages,
			   e.g. http xmlrpc) */
			path_anchor=anchor_lump(msg, msg->headers->name.s-buf, 0, 
									HDR_ROUTE_T);
		}
		if (unlikely(path_anchor==0))
			goto error05;
		if (unlikely((path_lump=insert_new_lump_after(path_anchor, path_buf.s,
														path_buf.len,
														HDR_ROUTE_T))==0))
			goto error05;
	}
	/* compute new msg len and fix overlapping zones*/
	new_len=len+body_delta+lumps_len(msg, msg->add_rm, send_info)+via_len;
#ifdef XL_DEBUG
	LM_ERR("new_len(%d)=len(%d)+lumps_len\n", new_len, len);
#endif
	udp_mtu=cfg_get(core, core_cfg, udp_mtu);
	di.proto=PROTO_NONE;
	if (unlikely((send_info->proto==PROTO_UDP) && udp_mtu && 
					(flags & FL_MTU_FB_MASK) && (new_len>udp_mtu)
					&& (!(mode&BUILD_NO_LOCAL_VIA)))){

		di=*send_info; /* copy whole struct - will be used in the Via builder */
		di.proto=PROTO_NONE; /* except the proto */
#ifdef USE_TCP
		if (!tcp_disable && (flags & FL_MTU_TCP_FB) &&
				(di.send_sock=get_send_socket(msg, &send_info->to, PROTO_TCP))){
			di.proto=PROTO_TCP;
		}
	#ifdef USE_TLS
		else if (!tls_disable && (flags & FL_MTU_TLS_FB) &&
				(di.send_sock=get_send_socket(msg, &send_info->to, PROTO_TLS))){
			di.proto=PROTO_TLS;
		}
	#endif /* USE_TLS */
#endif /* USE_TCP */
#ifdef USE_SCTP
	#ifdef USE_TCP
		else
	#endif /* USE_TCP */
		 if (!sctp_disable && (flags & FL_MTU_SCTP_FB) &&
				(di.send_sock=get_send_socket(msg, &send_info->to, PROTO_SCTP))){
			di.proto=PROTO_SCTP;
		 }
#endif /* USE_SCTP */
		
		if (di.proto!=PROTO_NONE){
			new_len-=via_len;
			if(likely(line_buf)) pkg_free(line_buf);
			line_buf = create_via_hf( &via_len, msg, &di, &branch);
			if (!line_buf){
				LM_ERR("memory allocation failure!\n");
				goto error00;
			}
			new_len+=via_len;
		}
	}
	/* add via header to the list */
	/* try to add it before msg. 1st via */
	/* add first via, as an anchor for second via*/
	if(likely(line_buf)) {
		if ((via_lump=insert_new_lump_before(via_anchor, line_buf, via_len,
											HDR_VIA_T))==0)
			goto error04;
	}
	if (msg->new_uri.s){
		uri_len=msg->new_uri.len;
		new_len=new_len-msg->first_line.u.request.uri.len+uri_len;
	}
	if(unlikely(mode&BUILD_IN_SHM))
		new_buf=(char*)shm_malloc(new_len+1);
	else
		new_buf=(char*)pkg_malloc(new_len+1);
	if (new_buf==0){
		ser_error=E_OUT_OF_MEM;
		LM_ERR("out of memory\n");
		goto error00;
	}

	offset=s_offset=0;
	if (msg->new_uri.s){
		/* copy message up to uri */
		size=msg->first_line.u.request.uri.s-buf;
		memcpy(new_buf, buf, size);
		offset+=size;
		s_offset+=size;
		/* add our uri */
		memcpy(new_buf+offset, msg->new_uri.s, uri_len);
		offset+=uri_len;
		s_offset+=msg->first_line.u.request.uri.len; /* skip original uri */
	}
	new_buf[new_len]=0;
	/* copy msg adding/removing lumps */
	process_lumps(msg, msg->add_rm, new_buf, &offset, &s_offset, send_info);
	process_lumps(msg, msg->body_lumps, new_buf, &offset, &s_offset,send_info);
	/* copy the rest of the message */
	memcpy(new_buf+offset, buf+s_offset, len-s_offset);
	new_buf[new_len]=0;

	/* update the send_info if udp_mtu affected */
	if (di.proto!=PROTO_NONE) { 
		send_info->proto=di.proto;
		send_info->send_sock=di.send_sock;
	}

#ifdef DBG_MSG_QA
	if (new_buf[new_len-1]==0) {
		LM_ERR("0 in the end\n");
		abort();
	}
#endif

	*returned_len=new_len;
	return new_buf;

error01:
error02:
	if (received_buf) pkg_free(received_buf);
error03:
	if (rport_buf) pkg_free(rport_buf);
error04:
	if (line_buf) pkg_free(line_buf);
error05:
	if (path_buf.s) pkg_free(path_buf.s);
error00:
	*returned_len=0;
	return 0;
}

char * generate_res_buf_from_sip_res( struct sip_msg* msg,
				unsigned int *returned_len, unsigned int mode)
{
	unsigned int new_len, via_len, body_delta;
	char* new_buf;
	unsigned offset, s_offset, via_offset;
	char* buf;
	unsigned int len;

	buf=msg->buf;
	len=msg->len;
	new_buf=0;

	if(unlikely(mode&BUILD_NO_VIA1_UPDATE)) {
		via_len = 0;
		via_offset = 0;
	} else {
		/* we must remove the first via */
		if (msg->via1->next) {
			via_len=msg->via1->bsize;
			via_offset=msg->h_via1->body.s-buf;
		} else {
			via_len=msg->h_via1->len;
			via_offset=msg->h_via1->name.s-buf;
		}
	}

	     /* Calculate message body difference and adjust
	      * Content-Length
	      */
	body_delta = lumps_len(msg, msg->body_lumps, 0);
	if (adjust_clen(msg, body_delta, (msg->via2? msg->via2->proto:PROTO_UDP))
			< 0) {
		LM_ERR("error while adjusting Content-Length\n");
		goto error;
	}

	if(likely(!(mode&BUILD_NO_VIA1_UPDATE))) {
		/* remove the first via*/
		if (del_lump( msg, via_offset, via_len, HDR_VIA_T)==0){
			LM_ERR("error trying to remove first via\n");
			goto error;
		}
	}

	new_len=len+body_delta+lumps_len(msg, msg->add_rm, 0); /*FIXME: we don't
														know the send sock */

	DBG(" old size: %d, new size: %d\n", len, new_len);
	new_buf=(char*)pkg_malloc(new_len+1); /* +1 is for debugging
											 (\0 to print it )*/
	if (new_buf==0){
		LM_ERR("out of mem\n");
		goto error;
	}
	new_buf[new_len]=0; /* debug: print the message */
	offset=s_offset=0;
	/*FIXME: no send sock*/
	process_lumps(msg, msg->add_rm, new_buf, &offset, &s_offset, 0);/*FIXME:*/
	process_lumps(msg, msg->body_lumps, new_buf, &offset, &s_offset, 0);
	/* copy the rest of the message */
	memcpy(new_buf+offset,
		buf+s_offset,
		len-s_offset);
	 /* send it! */
	DBG("copied size: orig:%d, new: %d, rest: %d"
			" msg=\n%s\n", s_offset, offset, len-s_offset, new_buf);

	*returned_len=new_len;
	return new_buf;
error:
	*returned_len=0;
	return 0;
}

char * build_res_buf_from_sip_res( struct sip_msg* msg,
				unsigned int *returned_len)
{
	return generate_res_buf_from_sip_res(msg, returned_len, 0);
}

char * build_res_buf_from_sip_req( unsigned int code, str *text ,str *new_tag,
		struct sip_msg* msg, unsigned int *returned_len, struct bookmark *bmark)
{
	char              *buf, *p;
	unsigned int      len,foo;
	struct hdr_field  *hdr;
	struct lump_rpl   *lump;
	struct lump_rpl   *body;
	int               i;
	char*             received_buf;
	unsigned int      received_len;
	char*             rport_buf;
	unsigned int      rport_len;
	char*             warning_buf;
	unsigned int      warning_len;
	char*             content_len_buf;
	unsigned int      content_len_len;
	char *after_body;
	str  to_tag;
	char *totags;

	body = 0;
	buf=0;
	received_buf=rport_buf=warning_buf=content_len_buf=0;
	received_len=rport_len=warning_len=content_len_len=0;

	to_tag.s=0;  /* fixes gcc 4.0 warning */
	to_tag.len=0;

	/* force parsing all headers -- we want to return all
	Via's in the reply and they may be scattered down to the
	end of header (non-block Vias are a really poor property
	of SIP :( ) */
	if (parse_headers( msg, HDR_EOH_F, 0 )==-1) {
		LM_ERR("alas, parse_headers failed\n");
		goto error00;
	}

	/*computes the length of the new response buffer*/
	len = 0;

	/* check if received needs to be added */
	if (received_test(msg)) {
		if ((received_buf=received_builder(msg,&received_len))==0) {
			LM_ERR("alas, received_builder failed\n");
			goto error00;
		}
	}
	/* check if rport needs to be updated */
	if ( ((msg->msg_flags|global_req_flags)&FL_FORCE_RPORT)||
		(msg->via1->rport /*&& msg->via1->rport->value.s==0*/)){
		if ((rport_buf=rport_builder(msg, &rport_len))==0){
			LM_ERR("rport_builder failed\n");
			goto error01; /* free everything */
		}
		if (msg->via1->rport)
			len -= msg->via1->rport->size+1; /* include ';' */
	}

	/* first line */
	len += msg->first_line.u.request.version.len + 1/*space*/ + 3/*code*/ + 1/*space*/ +
		text->len + CRLF_LEN/*new line*/;
	/*headers that will be copied (TO, FROM, CSEQ,CALLID,VIA)*/
	for ( hdr=msg->headers ; hdr ; hdr=hdr->next ) {
		switch (hdr->type) {
			case HDR_TO_T:
				if (new_tag && new_tag->len) {
					to_tag=get_to(msg)->tag_value;
					if ( to_tag.len || to_tag.s )
						len+=new_tag->len-to_tag.len;
					else
						len+=new_tag->len+TOTAG_TOKEN_LEN/*";tag="*/;
				}
				len += hdr->len;
				break;
			case HDR_VIA_T:
				/* we always add CRLF to via*/
				len+=(hdr->body.s+hdr->body.len)-hdr->name.s+CRLF_LEN;
				if (hdr==msg->h_via1) len += received_len+rport_len;
				break;
			case HDR_RECORDROUTE_T:
				/* RR only for 1xx and 2xx replies */
				if (code<180 || code>=300)
					break;
			case HDR_FROM_T:
			case HDR_CALLID_T:
			case HDR_CSEQ_T:
				/* we keep the original termination for these headers*/
				len += hdr->len;
				break;
			default:
				/* do nothing, we are interested only in the above headers */
				;
		}
	}
	/* lumps length */
	for(lump=msg->reply_lump;lump;lump=lump->next) {
		len += lump->text.len;
		if (lump->flags&LUMP_RPL_BODY)
			body = lump;
	}
	/* server header */
	if (server_signature && server_hdr.len)
		len += server_hdr.len + CRLF_LEN;
	/* warning hdr */
	if (sip_warning) {
		warning_buf = warning_builder(msg,&warning_len);
		if (warning_buf) len += warning_len + CRLF_LEN;
		else LM_WARN("warning skipped -- too big\n");
	}
	/* content length hdr */
	if (body) {
		content_len_buf = int2str(body->text.len, (int*)&content_len_len);
		len += CONTENT_LENGTH_LEN + content_len_len + CRLF_LEN;
	} else {
		len += CONTENT_LENGTH_LEN + 1/*0*/ + CRLF_LEN;
	}
	/* end of message */
	len += CRLF_LEN; /*new line*/

	/*allocating mem*/
	buf = (char*) pkg_malloc( len+1 );
	if (!buf)
	{
		LM_ERR("out of memory; needs %d\n",len);
		goto error01;
	}

	/* filling the buffer*/
	p=buf;
	/* first line */
	memcpy( p , msg->first_line.u.request.version.s , 
		msg->first_line.u.request.version.len);
	p += msg->first_line.u.request.version.len;
	*(p++) = ' ' ;
	/*code*/
	for ( i=2 , foo = code  ;  i>=0  ;  i-- , foo=foo/10 )
		*(p+i) = '0' + foo - ( foo/10 )*10;
	p += 3;
	*(p++) = ' ' ;
	memcpy( p , text->s , text->len );
	p += text->len;
	memcpy( p, CRLF, CRLF_LEN );
	p+=CRLF_LEN;
	/* headers*/
	for ( hdr=msg->headers ; hdr ; hdr=hdr->next ) {
		switch (hdr->type)
		{
			case HDR_VIA_T:
				if (hdr==msg->h_via1){
					if (rport_buf){
						if (msg->via1->rport){ /* delete the old one */
							/* copy until rport */
							append_str_trans( p, hdr->name.s ,
								msg->via1->rport->start-hdr->name.s-1,msg);
							/* copy new rport */
							append_str(p, rport_buf, rport_len);
							/* copy the rest of the via */
							append_str_trans(p, msg->via1->rport->start+
												msg->via1->rport->size,
												hdr->body.s+hdr->body.len-
												msg->via1->rport->start-
												msg->via1->rport->size, msg);
						}else{ /* just append the new one */
							/* normal whole via copy */
							append_str_trans( p, hdr->name.s ,
								(hdr->body.s+hdr->body.len)-hdr->name.s, msg);
							append_str(p, rport_buf, rport_len);
						}
					}else{
						/* normal whole via copy */
						append_str_trans( p, hdr->name.s ,
								(hdr->body.s+hdr->body.len)-hdr->name.s, msg);
					}
					if (received_buf)
						append_str( p, received_buf, received_len);
				}else{
					/* normal whole via copy */
					append_str_trans( p, hdr->name.s,
							(hdr->body.s+hdr->body.len)-hdr->name.s, msg);
				}
				append_str( p, CRLF,CRLF_LEN);
				break;
			case HDR_RECORDROUTE_T:
				/* RR only for 1xx and 2xx replies */
				if (code<180 || code>=300) break;
				append_str(p, hdr->name.s, hdr->len);
				break;
			case HDR_TO_T:
				if (new_tag && new_tag->len){
					if (to_tag.s ) { /* replacement */
						/* before to-tag */
						append_str( p, hdr->name.s, to_tag.s-hdr->name.s);
						/* to tag replacement */
						bmark->to_tag_val.s=p;
						bmark->to_tag_val.len=new_tag->len;
						append_str( p, new_tag->s,new_tag->len);
						/* the rest after to-tag */
						append_str( p, to_tag.s+to_tag.len,
							hdr->name.s+hdr->len-(to_tag.s+to_tag.len));
					}else{ /* adding a new to-tag */
						after_body=hdr->body.s+hdr->body.len;
						append_str( p, hdr->name.s, after_body-hdr->name.s);
						append_str(p, TOTAG_TOKEN, TOTAG_TOKEN_LEN);
						bmark->to_tag_val.s=p;
						bmark->to_tag_val.len=new_tag->len;
						append_str( p, new_tag->s,new_tag->len);
						append_str( p, after_body,
										hdr->name.s+hdr->len-after_body);
					}
					break;
				} /* no new to-tag -- proceed to 1:1 copying  */
				totags=((struct to_body*)(hdr->parsed))->tag_value.s;
				if (totags) {
					bmark->to_tag_val.s=p+(totags-hdr->name.s);
					bmark->to_tag_val.len=
							((struct to_body*)(hdr->parsed))->tag_value.len;
				}
				else {
					bmark->to_tag_val.len = 0;
					bmark->to_tag_val.s = p+(hdr->body.s+hdr->body.len-hdr->name.s);
				}
				/* no break */
			case HDR_FROM_T:
			case HDR_CALLID_T:
			case HDR_CSEQ_T:
					append_str(p, hdr->name.s, hdr->len);
					break;
			default:
				/* do nothing, we are interested only in the above headers */
				;
		} /* end switch */
	} /* end for */
	/* lumps */
	for(lump=msg->reply_lump;lump;lump=lump->next)
		if (lump->flags&LUMP_RPL_HDR){
			memcpy(p,lump->text.s,lump->text.len);
			p += lump->text.len;
		}
	/* server header */
	if (server_signature && server_hdr.len>0) {
		memcpy( p, server_hdr.s, server_hdr.len );
		p+=server_hdr.len;
		memcpy( p, CRLF, CRLF_LEN );
		p+=CRLF_LEN;
	}
	/* content_length hdr */
	if (content_len_len) {
		append_str( p, CONTENT_LENGTH, CONTENT_LENGTH_LEN);
		append_str( p, content_len_buf, content_len_len );
		append_str( p, CRLF, CRLF_LEN );
	} else {
		append_str( p, CONTENT_LENGTH"0"CRLF,CONTENT_LENGTH_LEN+1+CRLF_LEN);
	}
	/* warning header */
	if (warning_buf) {
		memcpy( p, warning_buf, warning_len);
		p+=warning_len;
		memcpy( p, CRLF, CRLF_LEN);
		p+=CRLF_LEN;
	}
	/*end of message*/
	memcpy( p, CRLF, CRLF_LEN );
	p+=CRLF_LEN;
	/* body */
	if (body) {
		memcpy ( p, body->text.s, body->text.len );
		p+=body->text.len;
	}

	if (len!=p-buf)
		LM_CRIT("diff len=%d p-buf=%d\n", len, (int)(p-buf));

	*(p) = 0;
	*returned_len = len;
	/* in req2reply, received_buf is not introduced to lumps and
	   needs to be deleted here
	*/
	if (received_buf) pkg_free(received_buf);
	if (rport_buf) pkg_free(rport_buf);
	return buf;

error01:
	if (received_buf) pkg_free(received_buf);
	if (rport_buf) pkg_free(rport_buf);
error00:
	*returned_len=0;
	return 0;
}



/* return number of chars printed or 0 if space exceeded;
   assumes buffer size of at least MAX_BRANCH_PARAM_LEN
 */
int branch_builder( unsigned int hash_index,
	/* only either parameter useful */
	unsigned int label, char * char_v,
	int branch,
	char *branch_str, int *len )
{

	char *begin;
	int size;

	/* hash id provided ... start with it */
	size=MAX_BRANCH_PARAM_LEN;
	begin=branch_str;
	*len=0;

	memcpy(begin, MCOOKIE, MCOOKIE_LEN );
	size-=MCOOKIE_LEN;begin+=MCOOKIE_LEN;

	if (int2reverse_hex( &begin, &size, hash_index)==-1)
		return 0;

	if (size) {
		*begin=BRANCH_SEPARATOR;
		begin++; size--;
	} else return 0;

	/* string with request's characteristic value ... use it ... */
	if (char_v) {
		if (memcpy(begin,char_v,MD5_LEN)) {
			begin+=MD5_LEN; size-=MD5_LEN;
		} else return 0;
	} else { /* ... use the "label" value otherwise */
		if (int2reverse_hex( &begin, &size, label )==-1)
			return 0;
	}

	if (size) {
		*begin=BRANCH_SEPARATOR;
		begin++; size--;
	} else return 0;

	if (int2reverse_hex( &begin, &size, branch)==-1)
		return 0;

	*len=MAX_BRANCH_PARAM_LEN-size;
	return size;

}



/* uses only the send_info->send_socket, send_info->proto and 
 * send_info->comp (so that a send_info used for sending can be passed
 * to this function w/o changes and the correct via will be built) */
char* via_builder( unsigned int *len,
	struct dest_info* send_info /* where to send the reply */,
	str* branch, str* extra_params, struct hostport* hp)
{
	unsigned int  via_len, extra_len;
	char               *line_buf;
	int max_len;
	int via_prefix_len;
	str* address_str; /* address displayed in via */
	str* port_str; /* port no displayed in via */
	struct socket_info* send_sock;
	int comp_len, comp_name_len;
#ifdef USE_COMP
	char* comp_name;
#endif /* USE_COMP */
	int port;
	struct ip_addr ip;
	union sockaddr_union *from = NULL;
	union sockaddr_union local_addr;
	struct tcp_connection *con = NULL;

	send_sock=send_info->send_sock;
	/* use pre-set address in via, the outbound socket alias or address one */
	if (hp && hp->host->len)
		address_str=hp->host;
	else if(send_sock->useinfo.name.len>0)
		address_str=&(send_sock->useinfo.name);
	else
		address_str=&(send_sock->address_str);
	if (hp && hp->port->len)
		port_str=hp->port;
	else if(send_sock->useinfo.port_no>0)
		port_str=&(send_sock->useinfo.port_no_str);
	else
		port_str=&(send_sock->port_no_str);
	
	comp_len=comp_name_len=0;
#ifdef USE_COMP
	comp_name=0;
	switch(send_info->comp){
		case COMP_NONE:
			break;
		case COMP_SIGCOMP:
			comp_len=COMP_PARAM_LEN;
			comp_name_len=SIGCOMP_NAME_LEN;
			comp_name=SIGCOMP_NAME;
			break;
		case COMP_SERGZ:
			comp_len=COMP_PARAM_LEN;
			comp_name_len=SERGZ_NAME_LEN;
			comp_name=SERGZ_NAME;
			break;
		default:
			LM_CRIT("unknown comp %d\n", send_info->comp);
			/* continue, we'll just ignore comp */
	}
#endif /* USE_COMP */
			
	via_prefix_len=MY_VIA_LEN+(send_info->proto==PROTO_SCTP);
	max_len=via_prefix_len +address_str->len /* space in MY_VIA */
		+2 /* just in case it is a v6 address ... [ ] */
		+1 /*':'*/+port_str->len
		+(branch?(MY_BRANCH_LEN+branch->len):0)
		+(extra_params?extra_params->len:0)
		+comp_len+comp_name_len
		+CRLF_LEN+1;
	line_buf=pkg_malloc( max_len );
	if (line_buf==0){
		ser_error=E_OUT_OF_MEM;
		LM_ERR("out of memory\n");
		return 0;
	}

	extra_len=0;

	via_len=via_prefix_len+address_str->len; /*space included in MY_VIA*/

	memcpy(line_buf, MY_VIA, MY_VIA_LEN);
	if (send_info->proto==PROTO_UDP){
		/* do nothing */
	}else if (send_info->proto==PROTO_TCP){
		memcpy(line_buf+MY_VIA_LEN-4, "TCP ", 4);
	}else if (send_info->proto==PROTO_TLS){
		memcpy(line_buf+MY_VIA_LEN-4, "TLS ", 4);
	}else if (send_info->proto==PROTO_SCTP){
		memcpy(line_buf+MY_VIA_LEN-4, "SCTP ", 5);
	}else if (send_info->proto==PROTO_WS){
                if (unlikely(send_info->send_flags.f & SND_F_FORCE_SOCKET
                                && send_info->send_sock)) {
                        local_addr = send_info->send_sock->su;
                        su_setport(&local_addr, 0); /* any local port will do */
                        from = &local_addr;
                }

                port = su_getport(&send_info->to);
                if (likely(port)) {
                        su2ip_addr(&ip, &send_info->to);
                        con = tcpconn_get(send_info->id, &ip, port, from, 0);
                }
                else if (likely(send_info->id))
                        con = tcpconn_get(send_info->id, 0, 0, 0, 0);
                else {
                        LM_CRIT("null_id & to\n"); pkg_free(line_buf);
                        return 0;
                }

                if (con == NULL) {
                        LM_WARN("TCP/TLS connection (id: %d) for WebSocket could not be found\n",
								send_info->id);
						pkg_free(line_buf);
                        return 0;
                }

		if (con->rcv.proto==PROTO_WS) {
			memcpy(line_buf+MY_VIA_LEN-4, "WS ", 3);
		} else if (con->rcv.proto==PROTO_WSS) {
			memcpy(line_buf+MY_VIA_LEN-4, "WSS ", 4);
		} else {
			tcpconn_put(con);
			LM_CRIT("unknown proto %d\n", con->rcv.proto);
			pkg_free(line_buf);
			return 0;
		}
		tcpconn_put(con);
	}else if (send_info->proto==PROTO_WSS){
		memcpy(line_buf+MY_VIA_LEN-4, "WSS ", 4);
	}else{
		LM_CRIT("unknown proto %d\n", send_info->proto);
		pkg_free(line_buf);
		return 0;
	}
	/* add [] only if ipv6 and outbound socket address is used;
	 * if using pre-set no check is made */
	if ((send_sock->address.af==AF_INET6) &&
		(address_str==&(send_sock->address_str))) {
		line_buf[via_prefix_len]='[';
		line_buf[via_prefix_len+1+address_str->len]=']';
		extra_len=1;
		via_len+=2; /* [ ]*/
	}
	memcpy(line_buf+via_prefix_len+extra_len, address_str->s,
				address_str->len);
	if ((send_sock->port_no!=SIP_PORT) ||
				(port_str!=&send_sock->port_no_str)){
		line_buf[via_len]=':'; via_len++;
		memcpy(line_buf+via_len, port_str->s, port_str->len);
		via_len+=port_str->len;
	}

	/* branch parameter */
	if (branch){
		memcpy(line_buf+via_len, MY_BRANCH, MY_BRANCH_LEN );
		via_len+=MY_BRANCH_LEN;
		memcpy(line_buf+via_len, branch->s, branch->len );
		via_len+=branch->len;
	}
	/* extra params  */
	if (extra_params){
		memcpy(line_buf+via_len, extra_params->s, extra_params->len);
		via_len+=extra_params->len;
	}
#ifdef USE_COMP
	/* comp */
	if (comp_len){
		memcpy(line_buf+via_len, COMP_PARAM, COMP_PARAM_LEN);
		via_len+=COMP_PARAM_LEN;
		memcpy(line_buf+via_len, comp_name, comp_name_len);
		via_len+=comp_name_len;
	}
#endif

	memcpy(line_buf+via_len, CRLF, CRLF_LEN);
	via_len+=CRLF_LEN;
	line_buf[via_len]=0; /* null terminate the string*/

	*len = via_len;
	return line_buf;
}

/* creates a via header honoring the protocol of the incomming socket
 * msg is an optional parameter */
char* create_via_hf( unsigned int *len,
	struct sip_msg *msg,
	struct dest_info* send_info /* where to send the reply */,
	str* branch)
{
	char* via;
	str extra_params;
	struct hostport hp;
#if defined USE_TCP || defined USE_SCTP
	char* id_buf;
	unsigned int id_len;


	id_buf=0;
	id_len=0;
#endif
	extra_params.len=0;
	extra_params.s=0;


#if defined USE_TCP || defined USE_SCTP
	/* add id if tcp */
	if (msg && (
#ifdef USE_TCP
		(msg->rcv.proto==PROTO_TCP)
#ifdef USE_TLS
			|| (msg->rcv.proto==PROTO_TLS)
#endif
#ifdef USE_SCTP
			||
#endif /* USE_SCTP */
#endif /* USE_TCP */
#ifdef USE_SCTP
			(msg->rcv.proto==PROTO_SCTP)
#endif /* USE_SCTP */
			)){
		if  ((id_buf=id_builder(msg, &id_len))==0){
			LM_ERR("id_builder failed\n");
			return 0; /* we don't need to free anything,
			                 nothing alloc'ed yet*/
		}
		DBG("create_via_hf: id added: <%.*s>, rcv proto=%d\n",
				(int)id_len, id_buf, msg->rcv.proto);
		extra_params.s=id_buf;
		extra_params.len=id_len;
	}
#endif /* USE_TCP || USE_SCTP */

	/* test and add rport parameter to local via - rfc3581 */
	if(msg && msg->msg_flags&FL_ADD_LOCAL_RPORT) {
		/* params so far + ';rport' + '\0' */
		via = (char*)pkg_malloc(extra_params.len+RPORT_LEN);
		if(via==0) {
			LM_ERR("building local rport via param failed\n");
			if (extra_params.s) pkg_free(extra_params.s);
			return 0;
		}
		if(extra_params.len!=0) {
			memcpy(via, extra_params.s, extra_params.len);
			pkg_free(extra_params.s);
		}
		memcpy(via + extra_params.len, RPORT, RPORT_LEN-1);
		extra_params.s = via;
		extra_params.len += RPORT_LEN-1;
		extra_params.s[extra_params.len]='\0';
	}

	set_hostport(&hp, msg);
	via = via_builder( len, send_info, branch,
							extra_params.len?&extra_params:0, &hp);

	/* we do not need extra_params any more, already in the new via header */
	if (extra_params.s) pkg_free(extra_params.s);
	return via;
}

/* builds a char* buffer from message headers without body
 * first line is excluded in case of skip_first_line=1
 * error is set -1 if the memory allocation failes
 */
char * build_only_headers( struct sip_msg* msg, int skip_first_line,
				unsigned int *returned_len,
				int *error,
				struct dest_info* send_info)
{
	char		*buf, *new_buf;
	unsigned int	offset, s_offset, len, new_len;

	*error = 0;
	buf = msg->buf;
	if (skip_first_line)
		s_offset = msg->headers->name.s - buf;
	else
		s_offset = 0;

	/* original length without body, and without final \r\n */
	len = msg->unparsed - buf;
	/* new msg length */
	new_len =	len - /* original length  */
			s_offset + /* skipped first line */
			lumps_len(msg, msg->add_rm, send_info); /* lumps */

	if (new_len == 0) {
		*returned_len = 0;
		return 0;
	}

	new_buf = (char *)pkg_malloc(new_len+1);
	if (!new_buf) {
		LM_ERR("Not enough memory\n");
		*error = -1;
		return 0;
	}
	new_buf[0] = 0;
	offset = 0;

	/* copy message lumps */
	process_lumps(msg, msg->add_rm, new_buf, &offset, &s_offset, send_info);
	/* copy the rest of the message without body */
	if (len > s_offset) {
		memcpy(new_buf+offset, buf+s_offset, len-s_offset);
		offset += (len-s_offset);
	}
	new_buf[offset] = 0;

	*returned_len = offset;
	return new_buf;
}

/* builds a char* buffer from message body
 * error is set -1 if the memory allocation failes
 */
char * build_body( struct sip_msg* msg,
			unsigned int *returned_len,
			int *error,
			struct dest_info* send_info)
{
	char		*buf, *new_buf, *body;
	unsigned int	offset, s_offset, len, new_len;

	*error = 0;
	body = get_body(msg);

	if (!body || (body[0] == 0)) {
		*returned_len = 0;
		return 0;
	}
	buf = msg->buf;
	s_offset = body - buf;

	/* original length of msg with body */
	len = msg->len;
	/* new body length */
	new_len =	len - /* original length  */
			s_offset + /* msg without body */
			lumps_len(msg, msg->body_lumps, send_info); /* lumps */

	new_buf = (char *)pkg_malloc(new_len+1);
	if (!new_buf) {
		LM_ERR("Not enough memory\n");
		*error = -1;
		return 0;
	}
	new_buf[0] = 0;
	offset = 0;

	/* copy body lumps */
	process_lumps(msg, msg->body_lumps, new_buf, &offset, &s_offset, send_info);
	/* copy the rest of the message without body */
	if (len > s_offset) {
		memcpy(new_buf+offset, buf+s_offset, len-s_offset);
		offset += (len-s_offset);
	}
	new_buf[offset] = 0;

	*returned_len = offset;
	return new_buf;
}

/* builds a char* buffer from SIP message including body
 * The function adjusts the Content-Length HF according
 * to body lumps in case of touch_clen=1.
 */
char * build_all( struct sip_msg* msg, int touch_clen,
			unsigned int *returned_len,
			int *error,
			struct dest_info* send_info)
{
	char		*buf, *new_buf;
	unsigned int	offset, s_offset, len, new_len;
	unsigned int	body_delta;

	*error = 0;
	/* Calculate message body difference */
	body_delta = lumps_len(msg, msg->body_lumps, send_info);
	if (touch_clen) {
		/* adjust Content-Length */
		if (adjust_clen(msg, body_delta, send_info->proto) < 0) {
			LM_ERR("Error while adjusting Content-Length\n");
			*error = -1;
			return 0;
		}
	}

	buf = msg->buf;
	/* original msg length */
	len = msg->len;
	/* new msg length */
	new_len =	len + /* original length  */
			lumps_len(msg, msg->add_rm, send_info) + /* hdr lumps */
			body_delta; /* body lumps */

	if (new_len == 0) {
		returned_len = 0;
		return 0;
	}

	new_buf = (char *)pkg_malloc(new_len+1);
	if (!new_buf) {
		LM_ERR("Not enough memory\n");
		*error = -1;
		return 0;
	}
	new_buf[0] = 0;
	offset = s_offset = 0;

	/* copy message lumps */
	process_lumps(msg, msg->add_rm, new_buf, &offset, &s_offset, send_info);
	/* copy body lumps */
	process_lumps(msg, msg->body_lumps, new_buf, &offset, &s_offset, send_info);
	/* copy the rest of the message */
	memcpy(new_buf+offset, buf+s_offset, len-s_offset);
	offset += (len-s_offset);
	new_buf[offset] = 0;

	*returned_len = offset;
	return new_buf;	
}



/**
 * parse buf in msg and fill several fields
 */
int build_sip_msg_from_buf(struct sip_msg *msg, char *buf, int len,
		unsigned int id)
{
	if(msg==0 || buf==0)
		return -1;

	memset(msg, 0, sizeof(sip_msg_t));
	msg->id = id;
	msg->buf = buf;
	msg->len = len;
	if (parse_msg(buf, len, msg)!=0) {
		LM_ERR("parsing failed");
		return -1;
	}
	msg->set_global_address=default_global_address;
	msg->set_global_port=default_global_port;
	return 0;
}