File: sr_module.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 (2000 lines) | stat: -rw-r--r-- 50,737 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
/*
 * 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-03-10  switched to new module_exports format: updated find_export,
 *               find_export_param, find_module (andrei)
 *  2003-03-19  replaced all mallocs/frees w/ pkg_malloc/pkg_free (andrei)
 *  2003-03-19  Support for flags in find_export (janakj)
 *  2003-03-29  cleaning pkg_mallocs introduced (jiri)
 *  2003-04-24  module version checking introduced (jiri)
 *  2004-09-19  compile flags are checked too (andrei)
 *  2005-01-07  removed find_module-overloading problems, added
 *               find_export_record
 *  2006-02-07  added fix_flag (andrei)
 *  2008-02-29  store all the reponse callbacks in their own array (andrei)
 *  2008-11-17  support dual module interface: ser & kamailio (andrei)
 *  2008-11-26  added fparam_free_contents() and fix_param_types (andrei)
 */

/**
 * @file
 * @brief SIP-Router core :: modules loading, structures declarations and utilities
 * @ingroup core
 * Module: \ref core
 */


#include "sr_module.h"
#include "mod_fix.h"
#include "dprint.h"
#include "error.h"
#include "mem/mem.h"
#include "core_cmd.h"
#include "ut.h"
#include "re.h"
#include "route_struct.h"
#include "flags.h"
#include "trim.h"
#include "pvapi.h"
#include "globals.h"
#include "rpc_lookup.h"
#include "sr_compat.h"
#include "ppcfg.h"
#include "async_task.h"

#include <sys/stat.h>
#include <regex.h>
#include <dlfcn.h>
#include <strings.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h> /* for offsetof */


struct sr_module* modules=0;

/*We need to define this symbol on Solaris becuase libcurl relies on libnspr which looks for this symbol.
  If it is not defined, dynamic module loading (dlsym) fails */
#ifdef __OS_solaris
	int nspr_use_zone_allocator = 0;
#endif


#ifdef STATIC_EXEC
	extern struct module_exports exec_exports;
#endif
#ifdef STATIC_TM
	extern struct module_exports tm_exports;
#endif

#ifdef STATIC_MAXFWD
	extern struct module_exports maxfwd_exports;
#endif

#ifdef STATIC_AUTH
	extern struct module_exports auth_exports;
#endif

#ifdef STATIC_RR
	extern struct module_exports rr_exports;
#endif

#ifdef STATIC_USRLOC
	extern struct module_exports usrloc_exports;
#endif

#ifdef STATIC_SL
	extern struct module_exports sl_exports;
#endif

#ifndef offsetof
#warning "use null pointer dereference for offsetof"
#define offsetof(st, m) \
		((size_t) ( (char *)&((st *)(0))->m - (char *)0 ))
#endif

int mod_response_cbk_no=0;
response_function* mod_response_cbks=0;

/* number of usec to wait before initializing a module */
static unsigned int modinit_delay = 0;

unsigned int set_modinit_delay(unsigned int v)
{
	unsigned int r;
	r =  modinit_delay;
	modinit_delay = v;
	return r;
}

/**
 * if bit 1 set, SIP worker processes handle RPC commands as well
 * if bit 2 set, RPC worker processes handle SIP commands as well
 */
static int child_sip_rpc_mode = 0;

#define CHILD_SIP_RPC	1<<0
#define CHILD_RPC_SIP	1<<1

void set_child_sip_rpc_mode(void)
{
	child_sip_rpc_mode |= CHILD_SIP_RPC;
}

void set_child_rpc_sip_mode(void)
{
	child_sip_rpc_mode |= CHILD_RPC_SIP;
}

int is_rpc_worker(int rank)
{
	if(rank==PROC_RPC
			|| (rank>PROC_MAIN && (child_sip_rpc_mode&CHILD_SIP_RPC)!=0))
		return 1;
	return 0;
}

int is_sip_worker(int rank)
{
	if(rank>PROC_MAIN
			|| ((rank==PROC_RPC || rank==PROC_NOCHLDINIT)
					&& (child_sip_rpc_mode&CHILD_RPC_SIP)!=0))
		return 1;
	return 0;
}

/* initializes statically built (compiled in) modules*/
int register_builtin_modules()
{
	int ret;

	ret=0;
#ifdef STATIC_TM
	ret=register_module(MODULE_INTERFACE_VER, &tm_exports,"built-in", 0);
	if (ret<0) return ret;
#endif

#ifdef STATIC_EXEC
	ret=register_module(MODULE_INTERFACE_VER, &exec_exports,"built-in", 0);
	if (ret<0) return ret;
#endif

#ifdef STATIC_MAXFWD
	ret=register_module(MODULE_INTERFACE_VER, &maxfwd_exports, "built-in", 0);
	if (ret<0) return ret;
#endif

#ifdef STATIC_AUTH
	ret=register_module(MODULE_INTERFACE_VER, &auth_exports, "built-in", 0);
	if (ret<0) return ret;
#endif

#ifdef STATIC_RR
	ret=register_module(MODULE_INTERFACE_VER, &rr_exports, "built-in", 0);
	if (ret<0) return ret;
#endif

#ifdef STATIC_USRLOC
	ret=register_module(MODULE_INTERFACE_VER, &usrloc_exports, "built-in", 0);
	if (ret<0) return ret;
#endif

#ifdef STATIC_SL
	ret=register_module(MODULE_INTERFACE_VER, &sl_exports, "built-in", 0);
	if (ret<0) return ret;
#endif

	return ret;
}



/** convert cmd exports to current format.
  * @param ver - module interface versions (0 == ser, 1 == kam).
  * @param src - null terminated array of cmd exports
  *              (either ser_cmd_export_t or kam_cmd_export_t, depending
  *               on ver).
  * @param mod - pointer to module exports structure.
  * @return - pkg_malloc'ed null terminated sr_cmd_export_v31_t array with
  *           the converted cmd exports  or 0 on error.
  */
static sr31_cmd_export_t* sr_cmd_exports_convert(unsigned ver,
													void* src, void* mod)
{
	int i, n;
	ser_cmd_export_t* ser_cmd;
	kam_cmd_export_t* kam_cmd;
	sr31_cmd_export_t* ret;
	
	ser_cmd = 0;
	kam_cmd = 0;
	ret = 0;
	n = 0;
	/* count the number of elements */
	if (ver == 0) {
		ser_cmd = src;
		for (; ser_cmd[n].name; n++);
	} else if (ver == 1) {
		kam_cmd = src;
		for (; kam_cmd[n].name; n++);
	} else goto error; /* unknown interface version */
	/* alloc & init new array */
	ret = pkg_malloc(sizeof(*ret)*(n+1));
	memset(ret, 0, sizeof(*ret)*(n+1));
	/* convert/copy */
	for (i=0; i < n; i++) {
		if (ver == 0) {
			ret[i].name = ser_cmd[i].name;
			ret[i].function = ser_cmd[i].function;
			ret[i].param_no = ser_cmd[i].param_no;
			ret[i].fixup = ser_cmd[i].fixup;
			ret[i].free_fixup = 0; /* no present in ser  <= 2.1 */
			ret[i].flags = ser_cmd[i].flags;
		} else {
			ret[i].name = kam_cmd[i].name;
			ret[i].function = kam_cmd[i].function;
			ret[i].param_no = kam_cmd[i].param_no;
			ret[i].fixup = kam_cmd[i].fixup;
			ret[i].free_fixup = kam_cmd[i].free_fixup;
			ret[i].flags = kam_cmd[i].flags;
		}
		/* 3.1+ specific stuff */
		ret[i].fixup_flags = 0;
		ret[i].module_exports = mod;
		/* fill known free fixups */
		if (ret[i].fixup && ret[i].free_fixup == 0)
			ret[i].free_fixup = get_fixup_free(ret[i].fixup);
	}
	return ret;
error:
	return 0;
}



/* registers a module,  register_f= module register  functions
 * returns <0 on error, 0 on success */
static int register_module(unsigned ver, union module_exports_u* e,
					char* path, void* handle)
{
	int ret, i;
	struct sr_module* mod;
	char defmod[64];

	ret=-1;

	/* add module to the list */
	if ((mod=pkg_malloc(sizeof(struct sr_module)))==0){
		LM_ERR("memory allocation failure\n");
		ret=E_OUT_OF_MEM;
		goto error;
	}
	memset(mod,0, sizeof(struct sr_module));
	mod->path=path;
	mod->handle=handle;
	mod->orig_mod_interface_ver=ver;
	/* convert exports to sr31 format */
	if (ver == 0) {
		/* ser <= 3.0 */
		mod->exports.name = e->v0.name;
		if (e->v0.cmds) {
			mod->exports.cmds = sr_cmd_exports_convert(ver, e->v0.cmds, mod);
			if (mod->exports.cmds == 0) {
				LM_ERR("failed to convert module command exports to 3.1 format"
						" for module \"%s\" (%s), interface version %d\n",
						mod->exports.name, mod->path, ver);
				ret = E_UNSPEC;
				goto error;
			}
		}
		mod->exports.params = e->v0.params;
		mod->exports.init_f = e->v0.init_f;
		mod->exports.response_f = e->v0.response_f;
		mod->exports.destroy_f = e->v0.destroy_f;
		mod->exports.onbreak_f = e->v0.onbreak_f;
		mod->exports.init_child_f = e->v0.init_child_f;
		mod->exports.dlflags = 0; /* not used in ser <= 3.0 */
		mod->exports.rpc_methods = e->v0.rpc_methods;
		/* the rest are 0, not used in ser */
	} else if (ver == 1) {
		/* kamailio <= 3.0 */
		mod->exports.name = e->v1.name;
		if (e->v1.cmds) {
			mod->exports.cmds = sr_cmd_exports_convert(ver, e->v1.cmds, mod);
			if (mod->exports.cmds == 0) {
				LM_ERR("failed to convert module command exports to 3.1 format"
						" for module \"%s\" (%s), interface version %d\n",
						mod->exports.name, mod->path, ver);
				ret = E_UNSPEC;
				goto error;
			}
		}
		mod->exports.params = e->v1.params;
		mod->exports.init_f = e->v1.init_f;
		mod->exports.response_f = e->v1.response_f;
		mod->exports.destroy_f = e->v1.destroy_f;
		mod->exports.onbreak_f = 0; /* not used in k <= 3.0 */
		mod->exports.init_child_f = e->v1.init_child_f;
		mod->exports.dlflags = e->v1.dlflags;
		mod->exports.rpc_methods = 0; /* not used in k <= 3.0 */
		mod->exports.stats = e->v1.stats;
		mod->exports.mi_cmds = e->v1.mi_cmds;
		mod->exports.items = e->v1.items;
		mod->exports.procs = e->v1.procs;
	} else {
		LM_ERR("unsupported module interface version %d\n", ver);
		ret = E_UNSPEC;
		goto error;
	}

	if (mod->exports.items) {
		/* register module pseudo-variables for kamailio modules */
		LM_DBG("register PV from: %s\n", mod->exports.name);
		if (register_pvars_mod(mod->exports.name, mod->exports.items)!=0) {
			LM_ERR("failed to register pseudo-variables for module %s (%s)\n",
				mod->exports.name, path);
			ret = E_UNSPEC;
			goto error;
		}
	}
	if (mod->exports.rpc_methods){
		/* register rpcs for ser modules */
		i=rpc_register_array(mod->exports.rpc_methods);
		if (i<0){
			LM_ERR("failed to register RPCs for module %s (%s)\n",
					mod->exports.name, path);
			ret = E_UNSPEC;
			goto error;
		}else if (i>0){
			LM_ERR("%d duplicate RPCs name detected while registering RPCs"
					" declared in module %s (%s)\n",
					i, mod->exports.name, path);
			ret = E_UNSPEC;
			goto error;
		}
		/* i==0 => success */
	}

	/* add cfg define for each module: MOD_modulename */
	if(strlen(mod->exports.name)>=60) {
		LM_ERR("too long module name: %s\n", mod->exports.name);
		goto error;
	}
	strcpy(defmod, "MOD_");
	strcat(defmod, mod->exports.name);
	pp_define_set_type(0);
	if(pp_define(strlen(defmod), defmod)<0) {
		LM_ERR("unable to set cfg define for module: %s\n",
				mod->exports.name);
		goto error;
	}

	/* link module in the list */
	mod->next=modules;
	modules=mod;
	return 0;
error:
	if (mod)
		pkg_free(mod);
	return ret;
}

#ifndef DLSYM_PREFIX
/* define it to null */
#define DLSYM_PREFIX
#endif

static inline int version_control(void *handle, char *path)
{
	char **m_ver;
	char **m_flags;
	char* error;

	m_ver=(char **)dlsym(handle, DLSYM_PREFIX "module_version");
	if ((error=(char *)dlerror())!=0) {
		LM_ERR("no version info in module <%s>: %s\n", path, error);
		return 0;
	}
	m_flags=(char **)dlsym(handle, DLSYM_PREFIX "module_flags");
	if ((error=(char *)dlerror())!=0) {
		LM_ERR("no compile flags info in module <%s>: %s\n", path, error);
		return 0;
	}
	if (!m_ver || !(*m_ver)) {
		LM_ERR("no version in module <%s>\n", path );
		return 0;
	}
	if (!m_flags || !(*m_flags)) {
		LM_ERR("no compile flags in module <%s>\n", path );
		return 0;
	}

	if (strcmp(SER_FULL_VERSION, *m_ver)==0){
		if (strcmp(SER_COMPILE_FLAGS, *m_flags)==0)
			return 1;
		else {
			LM_ERR("module compile flags mismatch for %s "
						" \ncore: %s \nmodule: %s\n",
						path, SER_COMPILE_FLAGS, *m_flags);
			return 0;
		}
	}
	LM_ERR("module version mismatch for %s; "
		"core: %s; module: %s\n", path, SER_FULL_VERSION, *m_ver );
	return 0;
}

/**
 * \brief load a sr module
 * 
 * tries to load the module specified by mod_path.
 * If mod_path is 'modname' or 'modname.so' then
 *  \<MODS_DIR\>/\<modname\>.so will be tried and if this fails
 *  \<MODS_DIR\>/\<modname\>/\<modname\>.so
 * If mod_path contain a '/' it is assumed to be the 
 * path to the module and tried first. If fails and mod_path is not
 * absolute path (not starting with '/') then will try:
 * \<MODS_DIR\>/mod_path
 * @param mod_path path or module name
 * @return 0 on success , <0 on error
 */
int load_module(char* mod_path)
{
	void* handle;
	char* error;
	mod_register_function mr;
	union module_exports_u* exp;
	unsigned* mod_if_ver;
	struct sr_module* t;
	struct stat stat_buf;
	str modname;
	char* mdir;
	char* nxt_mdir;
	char* path;
	int mdir_len;
	int len;
	int dlflags;
	int new_dlflags;
	int retries;
	int path_type;

#ifndef RTLD_NOW
/* for openbsd */
#define RTLD_NOW DL_LAZY
#endif
	path=mod_path;
	path_type = 0;
	modname.s = path;
	modname.len = strlen(mod_path);
	if(modname.len>3 && strcmp(modname.s+modname.len-3, ".so")==0) {
		path_type = 1;
		modname.len -= 3;
	}
	if (!strchr(path, '/'))
		path_type |= 2;
	if((path_type&2) || path[0] != '/') {
		/* module name was given, we try to construct the path */
		mdir=mods_dir; /* search path */
		do{
			nxt_mdir=strchr(mdir, ':');
			if (nxt_mdir) mdir_len=(int)(nxt_mdir-mdir);
			else mdir_len=strlen(mdir);
			
			if(path_type&2) {
				/* try path <MODS_DIR>/<modname>.so */
				path = (char*)pkg_malloc(mdir_len + 1 /* "/" */ +
									modname.len + 3 /* ".so" */ + 1);
				if (path==0) goto error;
				memcpy(path, mdir, mdir_len);
				len = mdir_len;
				if (len != 0 && path[len - 1] != '/'){
					path[len]='/';
					len++;
				}
				path[len]=0;
				strcat(path, modname.s);
				if(!(path_type&1))
					strcat(path, ".so");

				if (stat(path, &stat_buf) == -1) {
					DBG("load_module: module file not found <%s>\n", path);
					pkg_free(path);

					/* try path <MODS_DIR>/<modname>/<modname>.so */
					path = (char*)pkg_malloc(
						mdir_len + 1 /* "/" */ +
						modname.len + 1 /* "/" */ +
						modname.len + 3 /* ".so" */ + 1);
					if (path==0) goto error;
					memcpy(path, mdir, mdir_len);
					len = mdir_len;
					if (len != 0 && path[len - 1] != '/') {
						path[len]='/';
						len++;
					}
					path[len]=0;
					strncat(path, modname.s, modname.len);
					strcat(path, "/");
					strcat(path, modname.s);
					if(!(path_type&1))
						strcat(path, ".so");

					if (stat(path, &stat_buf) == -1) {
						DBG("load_module: module file not found <%s>\n", path);
						pkg_free(path);
						path=0;
					}
				}
			} else {
				/* try mod_path - S compat */
				if(path==mod_path) {
					if (stat(path, &stat_buf) == -1) {
						DBG("load_module: module file not found <%s>\n", path);
						path=0;
					}
				}
				if(path==0) {
					/* try path <MODS_DIR>/mod_path - K compat */
					path = (char*)pkg_malloc(mdir_len + 1 /* "/" */ +
									strlen(mod_path) + 1);
					if (path==0) goto error;
					memcpy(path, mdir, mdir_len);
					len = mdir_len;
					if (len != 0 && path[len - 1] != '/'){
						path[len]='/';
						len++;
					}
					path[len]=0;
					strcat(path, mod_path);

					if (stat(path, &stat_buf) == -1) {
						DBG("load_module: module file not found <%s>\n", path);
						pkg_free(path);
						path=0;
					}
				}
			}
			mdir=nxt_mdir?nxt_mdir+1:0;
		}while(path==0 && mdir);
		if (path==0){
			LM_ERR("could not find module <%.*s> in <%s>\n",
						modname.len, modname.s, mods_dir);
			goto error;
		}
	}
	DBG("load_module: trying to load <%s>\n", path);

	retries=2;
	dlflags=RTLD_NOW;
reload:
	handle=dlopen(path, dlflags); /* resolve all symbols now */
	if (handle==0){
		LM_ERR("could not open module <%s>: %s\n", path, dlerror());
		goto error;
	}

	for(t=modules;t; t=t->next){
		if (t->handle==handle){
			LM_WARN("attempting to load the same module twice (%s)\n", path);
			goto skip;
		}
	}
	/* version control */
	if (!version_control(handle, path)) {
		exit(-1);
	}
	mod_if_ver = (unsigned *)dlsym(handle,
									DLSYM_PREFIX "module_interface_ver");
	if ( (error =(char*)dlerror())!=0 ){
		LM_ERR("no module interface version in module <%s>\n", path );
		goto error1;
	}
	/* launch register */
	mr = (mod_register_function)dlsym(handle, DLSYM_PREFIX "mod_register");
	if (((error =(char*)dlerror())==0) && mr) {
		/* no error call it */
		new_dlflags=dlflags;
		if (mr(path, &new_dlflags, 0, 0)!=0) {
			LM_ERR("%s: mod_register failed\n", path);
			goto error1;
		}
		if (new_dlflags!=dlflags && new_dlflags!=0) {
			/* we have to reload the module */
			dlclose(handle);
			dlflags=new_dlflags;
			retries--;
			if (retries>0) goto reload;
			LM_ERR("%s: cannot agree on the dlflags\n", path);
			goto error;
		}
	}
	exp = (union module_exports_u*)dlsym(handle, DLSYM_PREFIX "exports");
	if ( (error =(char*)dlerror())!=0 ){
		LM_ERR("%s\n", error);
		goto error1;
	}
	/* hack to allow for kamailio style dlflags inside exports */
	if (*mod_if_ver == 1) {
		new_dlflags = exp->v1.dlflags;
		if (new_dlflags!=dlflags && new_dlflags!=DEFAULT_DLFLAGS) {
			/* we have to reload the module */
			dlclose(handle);
			DEBUG("%s: exports dlflags interface is deprecated and it will not"
					" be supported in newer versions; consider using"
					" mod_register() instead\n", path);
			dlflags=new_dlflags;
			retries--;
			if (retries>0) goto reload;
			LM_ERR("%s: cannot agree on the dlflags\n", path);
			goto error;
		}
	}
	if (register_module(*mod_if_ver, exp, path, handle)<0) goto error1;
	return 0;

error1:
	dlclose(handle);
error:
skip:
	if (path && path!=mod_path)
		pkg_free(path);
	return -1;
}



/* searches the module list for function name in module mod and returns 
 *  a pointer to the "name" function record union or 0 if not found
 * sets also *mod_if_ver to the original module interface version.
 * mod==0 is a wildcard matching all modules
 * flags parameter is OR value of all flags that must match
 */
sr31_cmd_export_t* find_mod_export_record(char* mod, char* name,
											int param_no, int flags,
											unsigned* mod_if_ver)
{
	struct sr_module* t;
	sr31_cmd_export_t* cmd;

	for(t=modules;t;t=t->next){
		if (mod!=0 && (strcmp(t->exports.name, mod) !=0))
			continue;
		if (t->exports.cmds)
			for(cmd=&t->exports.cmds[0]; cmd->name; cmd++) {
				if((strcmp(name, cmd->name) == 0) &&
					((cmd->param_no == param_no) ||
					 (cmd->param_no==VAR_PARAM_NO)) &&
					((cmd->flags & flags) == flags)
				){
					DBG("find_export_record: found <%s> in module %s [%s]\n",
						name, t->exports.name, t->path);
					*mod_if_ver=t->orig_mod_interface_ver;
					return cmd;
				}
			}
	}
	DBG("find_export_record: <%s> not found \n", name);
	return 0;
}



/* searches the module list for function name and returns 
 *  a pointer to the "name" function record union or 0 if not found
 * sets also *mod_if_ver to the module interface version (needed to know
 * which member of the union should be accessed v0 or v1)
 * mod==0 is a wildcard matching all modules
 * flags parameter is OR value of all flags that must match
 */
sr31_cmd_export_t* find_export_record(char* name,
											int param_no, int flags,
											unsigned* mod_if_ver)
{
	return find_mod_export_record(0, name, param_no, flags, mod_if_ver);
}



cmd_function find_export(char* name, int param_no, int flags)
{
	sr31_cmd_export_t* cmd;
	unsigned mver;
	
	cmd = find_export_record(name, param_no, flags, &mver);
	return cmd?cmd->function:0;
}


rpc_export_t* find_rpc_export(char* name, int flags)
{
	return rpc_lookup((char*)name, strlen(name));
}


/*
 * searches the module list and returns pointer to "name" function in module
 * "mod"
 * 0 if not found
 * flags parameter is OR value of all flags that must match
 */
cmd_function find_mod_export(char* mod, char* name, int param_no, int flags)
{
	sr31_cmd_export_t* cmd;
	unsigned mver;

	cmd=find_mod_export_record(mod, name, param_no, flags, &mver);
	if (cmd)
		return cmd->function;
	
	DBG("find_mod_export: <%s> in module <%s> not found\n", name, mod);
	return 0;
}


struct sr_module* find_module_by_name(char* mod) {
	struct sr_module* t;

	for(t = modules; t; t = t->next) {
		if (strcmp(mod, t->exports.name) == 0) {
			return t;
		}
	}
	DBG("find_module_by_name: module <%s> not found\n", mod);
	return 0;
}


/*!
 * \brief Find a parameter with given type
 * \param mod module
 * \param name parameter name
 * \param type_mask parameter mask
 * \param param_type parameter type
 * \return parameter address in memory, if there is no such parameter, NULL is returned
 */
void* find_param_export(struct sr_module* mod, char* name,
						modparam_t type_mask, modparam_t *param_type)
{
	param_export_t* param;

	if (!mod)
		return 0;
	for(param = mod->exports.params ;param && param->name ; param++) {
		if ((strcmp(name, param->name) == 0) &&
			((param->type & PARAM_TYPE_MASK(type_mask)) != 0)) {
			DBG("find_param_export: found <%s> in module %s [%s]\n",
				name, mod->exports.name, mod->path);
			*param_type = param->type;
			return param->param_pointer;
		}
	}
	DBG("find_param_export: parameter <%s> not found in module <%s>\n",
			name, mod->exports.name);
	return 0;
}


void destroy_modules()
{
	struct sr_module* t, *foo;

	/* call first destroy function from each module */
	t=modules;
	while(t) {
		foo=t->next;
		if (t->exports.destroy_f){
			t->exports.destroy_f();
		}
		t=foo;
	}
	/* free module exports structures */
	t=modules;
	while(t) {
		foo=t->next;
		pkg_free(t);
		t=foo;
	}
	modules=0;
	if (mod_response_cbks){
		pkg_free(mod_response_cbks);
		mod_response_cbks=0;
	}
}

#ifdef NO_REVERSE_INIT

/*
 * Initialize all loaded modules, the initialization
 * is done *AFTER* the configuration file is parsed
 */
int init_modules(void)
{
	struct sr_module* t;

	if(async_task_init()<0)
		return -1;

	for(t = modules; t; t = t->next) {
		if (t->exports.init_f) {
			if (t->exports.init_f() != 0) {
				LM_ERR("Error while initializing module %s\n", t->exports.name);
				return -1;
			}
			/* delay next module init, if configured */
			if(unlikely(modinit_delay>0))
				sleep_us(modinit_delay);
		}
		if (t->exports.response_f)
			mod_response_cbk_no++;
	}
	mod_response_cbks=pkg_malloc(mod_response_cbk_no * 
									sizeof(response_function));
	if (mod_response_cbks==0){
		LM_ERR("memory allocation failure for %d response_f callbacks\n",
					mod_response_cbk_no);
		return -1;
	}
	for (t=modules, i=0; t && (i<mod_response_cbk_no); t=t->next) {
		if (t->exports.response_f) {
			mod_response_cbks[i]=t->exports.response_f;
			i++;
		}
	}
	return 0;
}



/*
 * per-child initialization
 */
int init_child(int rank)
{
	struct sr_module* t;
	char* type;

	switch(rank) {
	case PROC_MAIN:     type = "PROC_MAIN";     break;
	case PROC_TIMER:    type = "PROC_TIMER";    break;
	case PROC_FIFO:     type = "PROC_FIFO";     break;
	case PROC_TCP_MAIN: type = "PROC_TCP_MAIN"; break;
	default:            type = "CHILD";         break;
	}
	DBG("init_child: initializing %s with rank %d\n", type, rank);

	if(async_task_child_init(rank)<0)
		return -1;

	for(t = modules; t; t = t->next) {
		if (t->exports.init_child_f) {
			if ((t->exports.init_child_f(rank)) < 0) {
				LM_ERR("Initialization of child %d failed\n", rank);
				return -1;
			}
		}
	}
	return 0;
}

#else


/* recursive module child initialization; (recursion is used to
   process the module linear list in the same order in
   which modules are loaded in config file
*/

static int init_mod_child( struct sr_module* m, int rank )
{
	if (m) {
		/* iterate through the list; if error occurs,
		   propagate it up the stack
		 */
		if (init_mod_child(m->next, rank)!=0) return -1;
		if (m->exports.init_child_f) {
			DBG("DEBUG: init_mod_child (%d): %s\n", rank, m->exports.name);
			if (m->exports.init_child_f(rank)<0) {
				LM_ERR("Error while initializing module %s (%s)\n",
							m->exports.name, m->path);
				return -1;
			} else {
				/* module correctly initialized */
				return 0;
			}
		}
		/* no init function -- proceed with success */
		return 0;
	} else {
		/* end of list */
		return 0;
	}
}


/*
 * per-child initialization
 */
int init_child(int rank)
{
	if(async_task_child_init(rank)<0)
		return -1;

	return init_mod_child(modules, rank);
}



/* recursive module initialization; (recursion is used to
   process the module linear list in the same order in
   which modules are loaded in config file
*/

static int init_mod( struct sr_module* m )
{
	if (m) {
		/* iterate through the list; if error occurs,
		   propagate it up the stack
		 */
		if (init_mod(m->next)!=0) return -1;
			if (m->exports.init_f) {
				DBG("DEBUG: init_mod: %s\n", m->exports.name);
				if (m->exports.init_f()!=0) {
					LM_ERR("Error while initializing module %s (%s)\n",
								m->exports.name, m->path);
					return -1;
				} else {
					/* module correctly initialized */
					return 0;
				}
			}
			/* no init function -- proceed with success */
			return 0;
	} else {
		/* end of list */
		return 0;
	}
}

/*
 * Initialize all loaded modules, the initialization
 * is done *AFTER* the configuration file is parsed
 */
int init_modules(void)
{
	struct sr_module* t;
	int i;
	
	if(async_task_init()<0)
		return -1;

	i = init_mod(modules);
	if(i!=0)
		return i;

	for(t = modules; t; t = t->next)
		if (t->exports.response_f)
			mod_response_cbk_no++;
	mod_response_cbks=pkg_malloc(mod_response_cbk_no * 
									sizeof(response_function));
	if (mod_response_cbks==0){
		LM_ERR("memory allocation failure for %d response_f callbacks\n", mod_response_cbk_no);
		return -1;
	}
	for (t=modules, i=0; t && (i<mod_response_cbk_no); t=t->next)
		if (t->exports.response_f) {
			mod_response_cbks[i]=t->exports.response_f;
			i++;
		}
	
	return 0;
}

#endif


action_u_t *fixup_get_param(void **cur_param, int cur_param_no,
							int required_param_no)
{
	action_u_t *a;
	/* cur_param points to a->u.string, get pointer to a */
	a = (void*) ((char *)cur_param - offsetof(action_u_t, u.string));
	return a + required_param_no - cur_param_no;
}

int fixup_get_param_count(void **cur_param, int cur_param_no)
{
	action_u_t *a;
	a = fixup_get_param(cur_param, cur_param_no, 0);
	if (a)
		return a->u.number;
	else
		return -1;
}



/** get a pointer to a parameter internal type.
 * @param param
 * @return pointer to the parameter internal type.
 */
action_param_type* fixup_get_param_ptype(void** param)
{
	action_u_t* a;
	a = (void*)((char*)param - offsetof(action_u_t, u.string));
	return &a->type;
}


/** get a parameter internal type.
 * @see fixup_get_param_ptype().
 * @return paramter internal type.
 */
action_param_type fixup_get_param_type(void** param)
{
	return *fixup_get_param_ptype(param);
}



/* fixes flag params (resolves possible named flags)
 * use PARAM_USE_FUNC|PARAM_STRING as a param. type and create
 * a wrapper function that does just:
 * return fix_flag(type, val, "my_module", "my_param", &flag_var)
 * see also param_func_t.
 */
int fix_flag( modparam_t type, void* val,
					char* mod_name, char* param_name, int* flag)
{
	int num;
	int err;
	int f, len;
	char* s;
	char *p;

	if ((type & PARAM_STRING)==0){
		LM_CRIT("%s: fix_flag(%s): bad parameter type\n",
					mod_name, param_name);
		return -1;
	}
	s=(char*)val;
	len=strlen(s);
	f=-1;
	/* try to see if it's a number */
	num = str2s(s, len, &err);
	if (err != 0) {
		/* see if it's in the name:<no> format */
		p=strchr(s, ':');
		if (p){
			f= str2s(p+1, strlen(p+1), &err);
			if (err!=0){
				LM_ERR("%s: invalid %s format: \"%s\"",
						mod_name, param_name, s);
				return -1;
			}
			*p=0;
		}
		if ((num=get_flag_no(s, len))<0){
			/* not declared yet, declare it */
			num=register_flag(s, f);
		}
		if (num<0){
			LM_ERR("%s: bad %s %s\n", mod_name, param_name, s);
			return -1;
		} else if ((f>0) && (num!=f)){
			LM_ERR("%s: flag %s already defined"
					" as %d (and not %d), using %s:%d\n",
					mod_name, s, num, f, s, num);
		}
	}
	*flag=num;
	return 0;
}

/*
 * Common function parameter fixups
 */

/** Generic parameter fixup function.
 *  Creates a fparam_t structure.
 *  @param type  contains allowed parameter types
 *  @param param is the parameter that will be fixed-up
 *
 * @return
 *    0 on success, 
 *    1 if the param doesn't match the specified type
 *    <0 on failure
 */
int fix_param(int type, void** param)
{
	fparam_t* p;
	str name, s;
	int num;
	int err;

	p = (fparam_t*)pkg_malloc(sizeof(fparam_t));
	if (!p) {
		LM_ERR("No memory left\n");
		return E_OUT_OF_MEM;
	}
	memset(p, 0, sizeof(fparam_t));
	p->orig = *param;
	
	switch(type) {
		case FPARAM_UNSPEC:
			LM_ERR("Invalid type value\n");
			goto error;
		case FPARAM_STRING:
			p->v.asciiz = *param;
			/* no break */
		case FPARAM_STR:
			p->v.str.s = (char*)*param;
			p->v.str.len = strlen(p->v.str.s);
			p->fixed = &p->v;
			break;
		case FPARAM_INT:
			s.s = (char*)*param;
			s.len = strlen(s.s);
			err = str2sint(&s, &num);
			if (err == 0) {
				p->v.i = (int)num;
			} else {
				/* Not a number */
				pkg_free(p);
				return 1;
			}
			p->fixed = (void*)(long)num;
			break;
		case FPARAM_REGEX:
			if ((p->v.regex = pkg_malloc(sizeof(regex_t))) == 0) {
				LM_ERR("No memory left\n");
				goto error;
			}
			if (regcomp(p->v.regex, *param,
						REG_EXTENDED|REG_ICASE|REG_NEWLINE)) {
				pkg_free(p->v.regex);
				p->v.regex=0;
				/* not a valid regex */
				goto no_match;
			}
			p->fixed = p->v.regex;
			break;
		case FPARAM_AVP:
			name.s = (char*)*param;
			name.len = strlen(name.s);
			trim(&name);
			if (!name.len || name.s[0] != '$') {
				/* Not an AVP identifier */
				goto no_match;
			}
			name.s++;
			name.len--;
			if (parse_avp_ident(&name, &p->v.avp) < 0) {
				/* invalid avp identifier (=> no match) */
				goto no_match;
			}
			p->fixed = &p->v;
			break;
		case FPARAM_SELECT:
			name.s = (char*)*param;
			name.len = strlen(name.s);
			trim(&name);
			if (!name.len || name.s[0] != '@') {
				/* Not a select identifier */
				goto no_match;
			}
			if (parse_select(&name.s, &p->v.select) < 0) {
				LM_ERR("Error while parsing select identifier\n");
				goto error;
			}
			p->fixed = &p->v;
			break;
		case FPARAM_SUBST:
			s.s = *param;
			s.len = strlen(s.s);
			p->v.subst = subst_parser(&s);
			if (!p->v.subst) {
				LM_ERR("Error while parsing regex substitution\n");
				goto error;
			}
			p->fixed = &p->v;
			break;
		case FPARAM_PVS:
			name.s = (char*)*param;
			name.len = strlen(name.s);
			trim(&name);
			if (!name.len || name.s[0] != '$'){
				/* not a pvs identifier */
				goto no_match;
			}
			p->v.pvs=pkg_malloc(sizeof(pv_spec_t));
			if (p->v.pvs==0){
				LM_ERR("out of memory while parsing pv_spec_t\n");
				goto error;
			}
			if (pv_parse_spec2(&name, p->v.pvs, 1)==0){
				/* not a valid pvs identifier (but it might be an avp) */
				pkg_free(p->v.pvs);
				p->v.pvs=0;
				goto no_match;
			}
			p->fixed = p->v.pvs;
			break;
		case FPARAM_PVE:
			name.s = (char*)*param;
			name.len = strlen(name.s);
			if (pv_parse_format(&name, &p->v.pve)<0){
				LM_ERR("bad PVE format: \"%.*s\"\n", name.len, name.s);
				goto error;
			}
			p->fixed = &p->v;
			break;
	}
	
	p->type = type;
	*param = (void*)p;
	return 0;
	
no_match:
	pkg_free(p);
	return 1;
error:
	pkg_free(p);
	return E_UNSPEC;
}



/** fparam_t free function.
 *  Frees the "content" of a fparam, but not the fparam itself.
 *  Note: it doesn't free fp->orig!
 *  Assumes pkg_malloc'ed content.
 *  @param fp -  fparam to be freed
 *
 */
void fparam_free_contents(fparam_t* fp)
{

	if (fp==0)
		return;
	switch(fp->type) {
		case FPARAM_UNSPEC:
		case FPARAM_STRING: /* asciiz string, not str */
		case FPARAM_INT:
		case FPARAM_STR:
			/* nothing to do */
			break;
		case FPARAM_REGEX:
			if (fp->v.regex){
				regfree(fp->v.regex);
				pkg_free(fp->v.regex);
				fp->v.regex=0;
			}
			break;
		case FPARAM_AVP:
			free_avp_name(&fp->v.avp.flags, &fp->v.avp.name);
			break;
		case FPARAM_SELECT:
			if (fp->v.select){
				free_select(fp->v.select);
				fp->v.select=0;
			}
			break;
		case FPARAM_SUBST:
			if (fp->v.subst){
				subst_expr_free(fp->v.subst);
				fp->v.subst=0;
			}
			break;
		case FPARAM_PVS:
			if (fp->v.pvs){
				pv_spec_free(fp->v.pvs);
				fp->v.pvs=0;
			}
			break;
		case FPARAM_PVE:
			if (fp->v.pve){
				pv_elem_free_all(fp->v.pve);
				fp->v.pve=0;
			}
			break;
	}
}


/**
 * @brief Generic free fixup type function for a fixed fparam
 * 
 * Generic free fixup type function for a fixed fparam. It will free whatever
 * was allocated during the initial fparam fixup and restore the original param
 * value.
 * @param param freed parameters
 */
void fparam_free_restore(void** param)
{
	fparam_t *fp;
	void *orig;
	
	fp = *param;
	orig = fp->orig;
	fp->orig = 0;
	fparam_free_contents(fp);
	pkg_free(fp);
	*param = orig;
}



/** fix a param to one of the given types (mask).
  *
  * @param types - bitmap of the allowed types (e.g. FPARAM_INT|FPARAM_STR)
  * @param param - value/result
  * @return - 0 on success, -1 on error, 1 if param doesn't
  *           match any of the types
  */
int fix_param_types(int types, void** param)
{
	int ret;
	int t;
	
	if (fixup_get_param_type(param) == STRING_RVE_ST &&
			(types & (FPARAM_INT|FPARAM_STR|FPARAM_STRING))) {
		/* if called with a RVE already converted to string =>
		   don't try AVP, PVAR or SELECT (to avoid double
		   deref., e.g.: $foo="$bar"; f($foo) ) */
		types &= ~ (FPARAM_AVP|FPARAM_PVS|FPARAM_SELECT|FPARAM_PVE);
	}
	for (t=types & ~(types-1); types; types&=(types-1), t=types & ~(types-1)){
		if ((ret=fix_param(t, param))<=0) return ret;
	}
	return E_UNSPEC;
}



/*
 * Fixup variable string, the parameter can be
 * AVP, SELECT, or ordinary string. AVP and select
 * identifiers will be resolved to their values during
 * runtime
 *
 * The parameter value will be converted to fparam structure
 * This function returns -1 on an error
 */
int fixup_var_str_12(void** param, int param_no)
{
	int ret;
	if (fixup_get_param_type(param) != STRING_RVE_ST) {
		/* if called with a RVE already converted to string =>
		   don't try AVP, PVAR or SELECT (to avoid double
		   deref., e.g.: $foo="$bar"; f($foo) ) */
		if ((ret = fix_param(FPARAM_PVS, param)) <= 0) return ret;
		if ((ret = fix_param(FPARAM_AVP, param)) <= 0) return ret;
		if ((ret = fix_param(FPARAM_SELECT, param)) <= 0) return ret;
	}
	if ((ret = fix_param(FPARAM_STR, param)) <= 0) return ret;
	LM_ERR("Error while fixing parameter, PV, AVP, SELECT, and str conversions"
			" failed\n");
	return -1;
}

/* Same as fixup_var_str_12 but applies to the 1st parameter only */
int fixup_var_str_1(void** param, int param_no)
{
	if (param_no == 1) return fixup_var_str_12(param, param_no);
	else return 0;
}

/* Same as fixup_var_str_12 but applies to the 2nd parameter only */
int fixup_var_str_2(void** param, int param_no)
{
	if (param_no == 2) return fixup_var_str_12(param, param_no);
	else return 0;
}

/** fixup variable-pve-only-string.
 * The parameter can be a PVE (pv based format string)
 * or string.
 * non-static PVEs  identifiers will be resolved to
 * their values during runtime.
 * The parameter value will be converted to fparam structure
 * @param  param - double pointer to param, as for normal fixup functions.
 * @param  param_no - parameter number, ignored.
 * @return -1 on an error, 0 on success.
 */
int fixup_var_pve_12(void** param, int param_no)
{
	int ret;
	fparam_t* fp;
	if (fixup_get_param_type(param) != STRING_RVE_ST) {
		/* if called with a RVE already converted to string =>
		   don't try PVE again (to avoid double
		   deref., e.g.: $foo="$bar"; f($foo) ) */
		if ((ret = fix_param(FPARAM_PVE, param)) <= 0) {
			if (ret < 0)
				return ret;
			/* check if it resolved to a dynamic or "static" PVE.
			   If the resulting PVE is static (normal string), discard
			   it and use the normal string fixup (faster at runtime) */
			fp = (fparam_t*)*param;
			if (fp->v.pve->spec == 0 || fp->v.pve->spec->getf == 0)
				fparam_free_restore(param); /* fallback to STR below */
			else
				return ret; /* dynamic PVE => return */
		}
		
	}
	if ((ret = fix_param(FPARAM_STR, param)) <= 0) return ret;
	LM_ERR("Error while fixing parameter - PVE or str conversions failed\n");
	return -1;
}



/** fixup variable-pve-string.
 * The parameter can be a PVAR, AVP, SELECT, PVE (pv based format string)
 * or string.
 * PVAR, AVP and select and non-static PVEs  identifiers will be resolved to
 * their values during runtime.
 * The parameter value will be converted to fparam structure
 * @param  param - double pointer to param, as for normal fixup functions.
 * @param  param_no - parameter number, ignored.
 * @return -1 on an error, 0 on success.
 */
int fixup_var_pve_str_12(void** param, int param_no)
{
	int ret;
	fparam_t* fp;
	if (fixup_get_param_type(param) != STRING_RVE_ST) {
		/* if called with a RVE already converted to string =>
		   don't try AVP, PVAR, SELECT or PVE again (to avoid double
		   deref., e.g.: $foo="$bar"; f($foo) ) */
		if ((ret = fix_param(FPARAM_PVS, param)) <= 0) return ret;
		if ((ret = fix_param(FPARAM_AVP, param)) <= 0) return ret;
		if ((ret = fix_param(FPARAM_SELECT, param)) <= 0) return ret;
		if ((ret = fix_param(FPARAM_PVE, param)) <= 0) {
			if (ret < 0)
				return ret;
			/* check if it resolved to a dynamic or "static" PVE.
			   If the resulting PVE is static (normal string), discard
			   it and use the normal string fixup (faster at runtime) */
			fp = (fparam_t*)*param;
			if (fp->v.pve->spec == 0 || fp->v.pve->spec->getf == 0)
				fparam_free_restore(param); /* fallback to STR below */
			else
				return ret; /* dynamic PVE => return */
		}
		
	}
	if ((ret = fix_param(FPARAM_STR, param)) <= 0) return ret;
	LM_ERR("Error while fixing parameter, PV, AVP, SELECT, and str conversions"
			" failed\n");
	return -1;
}

/* Same as fixup_var_pve_str_12 but applies to the 1st parameter only */
int fixup_var_pve_str_1(void** param, int param_no)
{
	if (param_no == 1) return fixup_var_pve_str_12(param, param_no);
	else return 0;
}

/* Same as fixup_var_pve_str_12 but applies to the 2nd parameter only */
int fixup_var_pve_str_2(void** param, int param_no)
{
	if (param_no == 2) return fixup_var_pve_str_12(param, param_no);
	else return 0;
}



/*
 * Fixup variable integer, the parameter can be
 * AVP, SELECT, or ordinary integer. AVP and select
 * identifiers will be resolved to their values and
 * converted to int if necessary during runtime
 *
 * The parameter value will be converted to fparam structure
 * This function returns -1 on an error
 */
int fixup_var_int_12(void** param, int param_no)
{
	int ret;
	if (fixup_get_param_type(param) != STRING_RVE_ST) {
		/* if called with a RVE already converted to string =>
		   don't try AVP, PVAR or SELECT (to avoid double
		   deref., e.g.: $foo="$bar"; f($foo) ) */
		if ((ret = fix_param(FPARAM_PVS, param)) <= 0) return ret;
		if ((ret = fix_param(FPARAM_AVP, param)) <= 0) return ret;
		if ((ret = fix_param(FPARAM_SELECT, param)) <= 0) return ret;
	}
	if ((ret = fix_param(FPARAM_INT, param)) <= 0) return ret;
	LM_ERR("Error while fixing parameter, PV, AVP, SELECT, and int conversions"
			" failed\n");
	return -1;
}

/* Same as fixup_var_int_12 but applies to the 1st parameter only */
int fixup_var_int_1(void** param, int param_no)
{
	if (param_no == 1) return fixup_var_int_12(param, param_no);
	else return 0;
}

/* Same as fixup_var_int_12 but applies to the 2nd parameter only */
int fixup_var_int_2(void** param, int param_no)
{
	if (param_no == 2) return fixup_var_int_12(param, param_no);
	else return 0;
}


/*
 * The parameter must be a regular expression which must compile, the
 * parameter will be converted to compiled regex
 */
int fixup_regex_12(void** param, int param_no)
{
	int ret;

	if ((ret = fix_param(FPARAM_REGEX, param)) <= 0) return ret;
	LM_ERR("Error while compiling regex in function parameter\n");
	return -1;
}

/* Same as fixup_regex_12 but applies to the 1st parameter only */
int fixup_regex_1(void** param, int param_no)
{
	if (param_no == 1) return fixup_regex_12(param, param_no);
	else return 0;
}

/* Same as fixup_regex_12 but applies to the 2nd parameter only */
int fixup_regex_2(void** param, int param_no)
{
	if (param_no == 2) return fixup_regex_12(param, param_no);
	else return 0;
}

/*
 * The string parameter will be converted to integer
 */
int fixup_int_12(void** param, int param_no)
{
	int ret;

	if ((ret = fix_param(FPARAM_INT, param)) <= 0) return ret;
	LM_ERR("Cannot function parameter to integer\n");
	return -1;

}

/* Same as fixup_int_12 but applies to the 1st parameter only */
int fixup_int_1(void** param, int param_no)
{
	if (param_no == 1) return fixup_int_12(param, param_no);
	else return 0;
}

/* Same as fixup_int_12 but applies to the 2nd parameter only */
int fixup_int_2(void** param, int param_no)
{
	if (param_no == 2) return fixup_int_12(param, param_no);
	else return 0;
}

/*
 * Parse the parameter as static string, do not resolve
 * AVPs or selects, convert the parameter to str structure
 */
int fixup_str_12(void** param, int param_no)
{
	int ret;

	if ((ret = fix_param(FPARAM_STR, param)) <= 0) return ret;
	LM_ERR("Cannot function parameter to string\n");
	return -1;
}

/* Same as fixup_str_12 but applies to the 1st parameter only */
int fixup_str_1(void** param, int param_no)
{
	if (param_no == 1) return fixup_str_12(param, param_no);
	else return 0;
}

/* Same as fixup_str_12 but applies to the 2nd parameter only */
int fixup_str_2(void** param, int param_no)
{
	if (param_no == 2) return fixup_str_12(param, param_no);
	else return 0;
}



/** Get the function parameter value as string.
 *  @return  0 - Success
 *          -1 - Cannot get value
 */
int get_str_fparam(str* dst, struct sip_msg* msg, fparam_t* param)
{
	int_str val;
	int ret;
	avp_t* avp;
	pv_value_t pv_val;
	
	switch(param->type) {
		case FPARAM_REGEX:
		case FPARAM_UNSPEC:
		case FPARAM_INT:
			return -1;
		case FPARAM_STRING:
			dst->s = param->v.asciiz;
			dst->len = strlen(param->v.asciiz);
			break;
		case FPARAM_STR:
			*dst = param->v.str;
			break;
		case FPARAM_AVP:
			avp = search_first_avp(param->v.avp.flags, param->v.avp.name,
									&val, 0);
			if (unlikely(!avp)) {
				DBG("Could not find AVP from function parameter '%s'\n",
						param->orig);
				return -1;
			}
			if (likely(avp->flags & AVP_VAL_STR)) {
				*dst = val.s;
			} else {
		 		/* The caller does not know of what type the AVP will be so
				 * convert int AVPs into string here
				 */
				dst->s = int2str(val.n, &dst->len);
			}
			break;
		case FPARAM_SELECT:
			ret = run_select(dst, param->v.select, msg);
			if (unlikely(ret < 0 || ret > 0)) return -1;
			break;
		case FPARAM_PVS:
			if (likely((pv_get_spec_value(msg, param->v.pvs, &pv_val)==0) &&
					   ((pv_val.flags&(PV_VAL_NULL|PV_VAL_STR))==PV_VAL_STR))){
					*dst=pv_val.rs;
			}else{
				LM_ERR("Could not convert PV to str\n");
				return -1;
			}
			break;
		case FPARAM_PVE:
			dst->s=pv_get_buffer();
			dst->len=pv_get_buffer_size();
			if (unlikely(pv_printf(msg, param->v.pve, dst->s, &dst->len)!=0)){
				LM_ERR("Could not convert the PV-formated string to str\n");
				dst->len=0;
				return -1;
			};
			break;
	}
	return 0;
}


/** Get the function parameter value as integer.
 *  @return  0 - Success
 *          -1 - Cannot get value
 */
int get_int_fparam(int* dst, struct sip_msg* msg, fparam_t* param)
{
	int_str val;
	int ret;
	avp_t* avp;
	str tmp;
	pv_value_t pv_val;

	switch(param->type) {
		case FPARAM_INT:
			*dst = param->v.i;
			return 0;
		case FPARAM_REGEX:
		case FPARAM_UNSPEC:
		case FPARAM_STRING:
		case FPARAM_STR:
			return -1;
		case FPARAM_AVP:
			avp = search_first_avp(param->v.avp.flags, param->v.avp.name,
									&val, 0);
			if (unlikely(!avp)) {
				DBG("Could not find AVP from function parameter '%s'\n",
						param->orig);
				return -1;
			}
			if (avp->flags & AVP_VAL_STR) {
				if (str2int(&val.s, (unsigned int*)dst) < 0) {
					LM_ERR("Could not convert AVP string value to int\n");
					return -1;
				}
			} else {
				*dst = val.n;
			}
			break;
		case FPARAM_SELECT:
			ret = run_select(&tmp, param->v.select, msg);
			if (unlikely(ret < 0 || ret > 0)) return -1;
			if (unlikely(str2int(&tmp, (unsigned int*)dst) < 0)) {
				LM_ERR("Could not convert select result to int\n");
				return -1;
			}
			break;
		case FPARAM_PVS:
			if (likely((pv_get_spec_value(msg, param->v.pvs, &pv_val)==0) &&
					   ((pv_val.flags&(PV_VAL_NULL|PV_VAL_INT))==PV_VAL_INT))){
					*dst=pv_val.ri;
			}else{
				LM_ERR("Could not convert PV to int\n");
				return -1;
			}
			break;
		case FPARAM_PVE:
			return -1;
	}
	return 0;
}

/** Get the function parameter value as string or/and integer (if possible).
 *  @return  0 - Success
 *          -1 - Cannot get value
 */
int get_is_fparam(int* i_dst, str* s_dst, struct sip_msg* msg, fparam_t* param, unsigned int *flags)
{
	int_str val;
	int ret;
	avp_t* avp;
	str tmp;
	pv_value_t pv_val;

	*flags = 0;
	switch(param->type) {
		case FPARAM_INT:
			*i_dst = param->v.i;
			*flags |= PARAM_INT;
			return 0;
		case FPARAM_REGEX:
		case FPARAM_UNSPEC:
		case FPARAM_STRING:
			s_dst->s = param->v.asciiz;
			s_dst->len = strlen(param->v.asciiz);
			*flags |= PARAM_STR;
			break;
		case FPARAM_STR:
			*s_dst = param->v.str;
			*flags |= PARAM_STR;
			break;
		case FPARAM_AVP:
			avp = search_first_avp(param->v.avp.flags, param->v.avp.name,
									&val, 0);
			if (unlikely(!avp)) {
				DBG("Could not find AVP from function parameter '%s'\n",
						param->orig);
				return -1;
			}
			if (avp->flags & AVP_VAL_STR) {
				*s_dst = val.s;
				*flags |= PARAM_STR;
				if (str2int(&val.s, (unsigned int*)i_dst) < 0) {
					LM_ERR("Could not convert AVP string value to int\n");
					return -1;
				}
			} else {
				*i_dst = val.n;
				*flags |= PARAM_INT;
			}
			break;
		case FPARAM_SELECT:
			ret = run_select(&tmp, param->v.select, msg);
			if (unlikely(ret < 0 || ret > 0)) return -1;
			if (unlikely(str2int(&tmp, (unsigned int*)i_dst) < 0)) {
				LM_ERR("Could not convert select result to int\n");
				return -1;
			}
			*flags |= PARAM_INT;
			break;
		case FPARAM_PVS:
			if (likely(pv_get_spec_value(msg, param->v.pvs, &pv_val)==0)) {
				if ((pv_val.flags&(PV_VAL_NULL|PV_VAL_INT))==PV_VAL_INT){
					*i_dst=pv_val.ri;
					*flags |= PARAM_INT;
				}
				if ((pv_val.flags&(PV_VAL_NULL|PV_VAL_STR))==PV_VAL_STR){
					*s_dst=pv_val.rs;
					*flags |= PARAM_STR;
				}
			}else{
				LM_ERR("Could not get PV\n");
				return -1;
			}
			break;
		case FPARAM_PVE:
			s_dst->s=pv_get_buffer();
			s_dst->len=pv_get_buffer_size();
			if (unlikely(pv_printf(msg, param->v.pve, s_dst->s, &s_dst->len)!=0)){
				LM_ERR("Could not convert the PV-formated string to str\n");
				s_dst->len=0;
				return -1;
			}
			*flags |= PARAM_STR;
			break;
	}

	/* Let's convert to int, if possible */
	if (!(*flags & PARAM_INT) && (*flags & PARAM_STR) && str2sint(s_dst, i_dst) == 0)
		*flags |= PARAM_INT;

	if (!*flags) return -1;

	return 0;
}

/**
 * Retrieve the compiled RegExp.
 * @return: 0 for success, negative on error.
 */
int get_regex_fparam(regex_t *dst, struct sip_msg* msg, fparam_t* param)
{
	switch (param->type) {
		case FPARAM_REGEX:
			*dst = *param->v.regex;
			return 0;
		default:
			LM_ERR("unexpected parameter type (%d), instead of regexp.\n", 
					param->type);
	}
	return -1;
}



/** generic free fixup function for "pure" fparam type fixups.
 * @param  param - double pointer to param, as for normal fixup functions.
 * @param  param_no - parameter number, ignored.
 * @return 0 on success (always).
 */
int fixup_free_fparam_all(void** param, int param_no)
{
	fparam_free_restore(param);
	return 0;
}



/** generic free fixup function for "pure"  first parameter fparam type fixups.
 * @param  param - double pointer to param, as for normal fixup functions.
 * @param  param_no - parameter number: the function will work only for
 *                     param_no == 1 (first parameter).
 * @return 0 on success (always).
 */
int fixup_free_fparam_1(void** param, int param_no)
{
	if (param_no == 1)
		fparam_free_restore(param);
	return 0;
}



/** generic free fixup function for "pure"  2nd parameter fparam type fixups.
 * @param  param - double pointer to param, as for normal fixup functions.
 * @param  param_no - parameter number: the function will work only for
 *                     param_no == 2 (2nd parameter).
 * @return 0 on success (always).
 */
int fixup_free_fparam_2(void** param, int param_no)
{
	if (param_no == 2)
		fparam_free_restore(param);
	return 0;
}



/** returns true if a fixup is a fparam_t* one.
 * Used to automatically detect "pure" fparam fixups that can be used with non
 * contant RVEs.
 * @param f - function pointer
 * @return 1 for fparam fixups, 0 for others.
 */
int is_fparam_rve_fixup(fixup_function f)
{
	if (f == fixup_var_str_12 ||
		f == fixup_var_str_1 ||
		f == fixup_var_str_2 ||
		f == fixup_var_pve_str_12 ||
		f == fixup_var_pve_str_1 ||
		f == fixup_var_pve_str_2 ||
		f == fixup_var_int_12 ||
		f == fixup_var_int_1 ||
		f == fixup_var_int_2 ||
		f == fixup_int_12 ||
		f == fixup_int_1 ||
		f == fixup_int_2 ||
		f == fixup_str_12 ||
		f == fixup_str_1 ||
		f == fixup_str_2 ||
		f == fixup_regex_12 ||
		f == fixup_regex_1 ||
		f == fixup_regex_2
		)
		return 1;
	return 0;
}


/**
 * @brief returns the corresponding fixup_free* for various known fixup types
 * 
 * Returns the corresponding fixup_free* for various known fixup types.
 * Used to automatically fill in free_fixup* functions.
 * @param f fixup function pointer
 * @return free fixup function pointer on success, 0 on failure (unknown
 * fixup or no free fixup function).
 */
free_fixup_function get_fixup_free(fixup_function f)
{
	free_fixup_function ret;
	/* "pure" fparam, all parameters */
	if (f == fixup_var_str_12 ||
		f == fixup_var_pve_str_12 ||
		f == fixup_var_int_12 ||
		f == fixup_int_12 ||
		f == fixup_str_12 ||
		f == fixup_regex_12)
		return fixup_free_fparam_all;
	
	/* "pure" fparam, 1st parameter */
	if (f == fixup_var_str_1 ||
		f == fixup_var_pve_str_1 ||
		f == fixup_var_int_1 ||
		f == fixup_int_1 ||
		f == fixup_str_1 ||
		f == fixup_regex_1)
		return fixup_free_fparam_1;
	
	/* "pure" fparam, 2nd parameters */
	if (f == fixup_var_str_2 ||
		f == fixup_var_pve_str_2 ||
		f == fixup_var_int_2 ||
		f == fixup_int_2 ||
		f == fixup_str_2 ||
		f == fixup_regex_2)
		return fixup_free_fparam_2;
	
	/* mod_fix.h kamailio style fixups */
	if ((ret = mod_fix_get_fixup_free(f)) != 0)
		return ret;
	
	/* unknown */
	return 0;
}