sipcapture: added sip_capture_forward(uri)
[sip-router] / src / modules / sipcapture / sipcapture.c
1 /*
2  * sipcapture module - helper module to capture sip messages
3  *
4  * Copyright (C) 2011-2015 Alexandr Dubovikov (alexandr.dubovikov@gmail.com)
5  *
6  * This file is part of Kamailio, a free SIP server.
7  *
8  * Kamailio is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version
12  *
13  * Kamailio is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
21  *
22  */
23
24 /*! \file
25  * sipcapture module - helper module to capture sip messages
26  *
27  */
28
29
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <time.h>
34 #include <sys/ioctl.h>
35 #include <sys/types.h>
36 #include <sys/socket.h>
37 #include <netinet/in.h>
38 #include <net/if.h>
39 #include <netdb.h>
40 #include <arpa/inet.h>
41
42 /* BPF structure */
43 #ifdef __OS_linux
44 #include <linux/filter.h>
45 #endif
46
47 #ifndef __USE_BSD
48 #define __USE_BSD /* on linux use bsd version of iphdr (more portable) */
49 #endif                    /* __USE_BSD */
50 #include <netinet/ip.h>
51 #define __FAVOR_BSD /* on linux use bsd version of udphdr (more portable) */
52 #include <netinet/udp.h>
53
54 #include "../../core/sr_module.h"
55 #include "../../core/dprint.h"
56 #include "../../core/events.h"
57 #include "../../core/ut.h"
58 #include "../../core/ip_addr.h"
59 #include "../../core/mem/mem.h"
60 #include "../../core/mem/shm_mem.h"
61 #include "../../core/rpc.h"
62 #include "../../core/rpc_lookup.h"
63 #include "../../lib/srdb1/db.h"
64 #include "../../core/parser/contact/parse_contact.h"
65 #include "../../core/parser/parse_content.h"
66 #include "../../core/parser/parse_from.h"
67 #include "../../core/parser/parse_uri.h"
68 #include "../../core/parser/digest/digest.h"
69 #include "../../core/parser/parse_ppi_pai.h"
70 #include "../../core/forward.h"
71 #include "../../core/pvar.h"
72 #include "../../core/str.h"
73 #include "../../core/onsend.h"
74 #include "../../core/resolve.h"
75 #include "../../core/receive.h"
76 #include "../../core/mod_fix.h"
77 #include "../../core/rand/kam_rand.h"
78 #include "../../core/kemi.h"
79 #include "sipcapture.h"
80 #include "hash_mode.h"
81 #include "hep.h"
82
83 #ifdef STATISTICS
84 #include "../../core/counters.h"
85 #endif
86
87
88 #include "../topoh/api.h"
89
90 MODULE_VERSION
91
92
93 #define ETHHDR 14 /* sizeof of ethhdr structure */
94
95 #define EMPTY_STR(val) \
96         val.s = "";        \
97         val.len = 0;
98
99 #define TABLE_LEN 256
100
101 #define NR_KEYS 44
102 #define RTCP_NR_KEYS 12
103
104 #define MAX_HEADERS 16
105
106 /*multiple table mode*/
107 enum e_mt_mode
108 {
109         mode_random = 1,
110         mode_hash,
111         mode_round_robin,
112         mode_error
113 };
114
115
116 typedef struct _capture_mode_data
117 {
118         unsigned int id;
119         str name;
120         str db_url;
121         db1_con_t *db_con;
122         db_func_t db_funcs;
123         str *table_names;
124         unsigned int no_tables;
125         enum e_mt_mode mtmode;
126         enum hash_source hash_source;
127         unsigned int rr_idx;
128         stat_var *sipcapture_req;
129         stat_var *sipcapture_rpl;
130         struct _capture_mode_data *next;
131 } _capture_mode_data_t;
132
133 _capture_mode_data_t *capture_modes_root = NULL;
134 _capture_mode_data_t *capture_def = NULL;
135
136 /* module function prototypes */
137 static int mod_init(void);
138 static int sipcapture_init_rpc(void);
139 static int child_init(int rank);
140 static void destroy(void);
141 static int sipcapture_fixup(void **param, int param_no);
142 static int reportcapture_fixup(void **param, int param_no);
143 static int float2int_fixup(void **param, int param_no);
144
145 static int pv_get_hep(sip_msg_t *msg, pv_param_t *param, pv_value_t *res);
146 static int pv_parse_hep_name(pv_spec_p sp, str *in);
147
148 static int sip_capture(sip_msg_t *msg, str *dtable,
149                 _capture_mode_data_t *cm_data);
150 static int report_capture(sip_msg_t *msg, str *_table, str *_corr, str *_data);
151 static int w_sip_capture0(sip_msg_t *_m, char *_p1, char *_p2);
152 static int w_sip_capture1(sip_msg_t *_m, char *_table, char *_p2);
153 static int w_sip_capture2(sip_msg_t *_m, char *_table, char *_cmdata);
154 static int w_sip_capture(struct sip_msg *_m, char *_table,
155                 _capture_mode_data_t *_cm_data);
156 static int w_report_capture1(sip_msg_t *_m, char *_table, char *_p2);
157 static int w_report_capture2(sip_msg_t *_m, char *_table, char *_corr);
158 static int w_report_capture3(sip_msg_t *_m, char *_table, char *_corr,
159                 char *_data);
160 static int w_float2int(sip_msg_t *_m, char *_val, char *_coof);
161
162 static int w_sip_capture_forward(sip_msg_t *_m, char *_dst, char *_p2);
163
164 static int sipcapture_parse_aleg_callid_headers();
165 int parse_aleg_callid_headers(str *headers_str, str *headers);
166
167 int init_rawsock_children(void);
168 int extract_host_port(void);
169 int raw_capture_socket(struct ip_addr *ip, str *iface, int port_start,
170                 int port_end, int proto);
171 int raw_capture_rcv_loop(int rsock, int port1, int port2, int ipip);
172 static int nosip_hep_msg(sr_event_param_t *evp);
173
174 static int hep_version(struct sip_msg *msg);
175
176
177 static str db_url = str_init(DEFAULT_DB_URL);
178 static str table_name = str_init("sip_capture");
179 static str hash_source = str_init("call_id");
180 static str table_time_sufix = str_init("%Y%m%D");
181 static str mt_mode = str_init("rand");
182 static str date_column = str_init("date");
183 static str micro_ts_column = str_init("micro_ts");
184 static str method_column = str_init("method");
185 static str reply_reason_column = str_init("reply_reason");
186 static str correlation_column = str_init("correlation_id");
187 static str ruri_column = str_init("ruri");
188 static str ruri_user_column = str_init("ruri_user");
189 static str ruri_domain_column = str_init("ruri_domain");
190 static str from_user_column = str_init("from_user");
191 static str from_domain_column = str_init("from_domain");
192 static str from_tag_column = str_init("from_tag");
193 static str to_user_column = str_init("to_user");
194 static str to_domain_column = str_init("to_domain");
195 static str to_tag_column = str_init("to_tag");
196 static str pid_user_column = str_init("pid_user");
197 static str contact_user_column = str_init("contact_user");
198 static str auth_user_column = str_init("auth_user");
199 static str callid_column = str_init("callid");
200 static str callid_aleg_column = str_init("callid_aleg");
201 static str via_1_column = str_init("via_1");
202 static str via_1_branch_column = str_init("via_1_branch");
203 static str cseq_column = str_init("cseq");
204 static str diversion_column = str_init("diversion");
205 static str reason_column = str_init("reason");
206 static str content_type_column = str_init("content_type");
207 static str authorization_column = str_init("auth");
208 static str user_agent_column = str_init("user_agent");
209 static str source_ip_column = str_init("source_ip");
210 static str source_port_column = str_init("source_port");
211 static str dest_ip_column = str_init("destination_ip");
212 static str dest_port_column = str_init("destination_port");
213 static str contact_ip_column = str_init("contact_ip");
214 static str contact_port_column = str_init("contact_port");
215 static str orig_ip_column = str_init("originator_ip");
216 static str orig_port_column = str_init("originator_port");
217 static str rtp_stat_column = str_init("rtp_stat");
218 static str proto_column = str_init("proto");
219 static str family_column = str_init("family");
220 static str type_column = str_init("type");
221 static str node_column = str_init("node");
222 static str msg_column = str_init("msg");
223 static str custom_field1_column = str_init("custom_field1");
224 static str custom_field2_column = str_init("custom_field2");
225 static str custom_field3_column = str_init("custom_field3");
226 static str capture_node = str_init("homer01");
227 static str star_contact = str_init("*");
228 static str callid_aleg_header = str_init("X-CID");
229 static str custom_field1_header = str_init("Mac");
230 static str custom_field2_header = str_init("IP");
231 static str custom_field3_header = str_init("Port");
232
233
234 int raw_sock_desc = -1; /* raw socket used for ip packets */
235 unsigned int raw_sock_children = 1;
236 int capture_on = 0;
237 int ipip_capture_on = 0;
238 int moni_capture_on = 0;
239 int moni_port_start = 0;
240 int moni_port_end = 0;
241 int *capture_on_flag = NULL;
242 int db_insert_mode = 0;
243 int promisc_on = 0;
244 int bpf_on = 0;
245 int hep_capture_on = 0;
246 int insert_retries = 0;
247 int insert_retry_timeout = 60;
248 int hep_offset = 0;
249 str raw_socket_listen = {0, 0};
250 str raw_interface = {0, 0};
251 char *authkey = NULL, *correlation_id = NULL;
252 str callid_aleg_headers[MAX_HEADERS];
253 int n_callid_aleg_headers = 0;
254 str sc_event_callback = STR_NULL;
255
256 struct ifreq ifr; /* interface structure */
257
258 /* by default nonsip_hook is inactive */
259 static int nonsip_hook = 0;
260 static int hep_route_no = -1;
261
262 static int sc_topoh_unmask = 0;
263 static topoh_api_t thb = {0};
264
265 #ifdef __OS_linux
266 /* Linux socket filter */
267 /* tcpdump -s 0 udp and portrange 5060-5090 -dd */
268 static struct sock_filter BPF_code[] = {
269         {0x28, 0, 0, 0x0000000c}, {0x15, 0, 7, 0x000086dd},
270         {0x30, 0, 0, 0x00000014}, {0x15, 0, 18, 0x00000011},
271         {0x28, 0, 0, 0x00000036}, {0x35, 0, 1, 0x000013c4},
272         {0x25, 0, 14, 0x000013e2}, {0x28, 0, 0, 0x00000038},
273         {0x35, 11, 13, 0x000013c4}, {0x15, 0, 12, 0x00000800},
274         {0x30, 0, 0, 0x00000017}, {0x15, 0, 10, 0x00000011},
275         {0x28, 0, 0, 0x00000014}, {0x45, 8, 0, 0x00001fff},
276         {0xb1, 0, 0, 0x0000000e}, {0x48, 0, 0, 0x0000000e},
277         {0x35, 0, 1, 0x000013c4}, {0x25, 0, 3, 0x000013e2},
278         {0x48, 0, 0, 0x00000010}, {0x35, 0, 2, 0x000013c4},
279         {0x25, 1, 0, 0x000013e2}, {0x6, 0, 0, 0x0000ffff},
280         {0x6, 0, 0, 0x00000000},
281 };
282 #endif
283
284 //db1_con_t *db_con = NULL;             /*!< database connection */
285 //db_func_t db_funcs;                   /*!< Database functions */
286
287 //str* table_names = NULL;
288
289 unsigned int no_tables = 0;
290
291 enum e_mt_mode mtmode = mode_random;
292 enum hash_source source = hs_error;
293
294 //unsigned int rr_idx = 0;
295
296 struct hep_timeinfo *heptime;
297
298 /*! \brief
299  * Exported functions
300  */
301 static cmd_export_t cmds[] = {
302         {"sip_capture", (cmd_function)w_sip_capture0, 0, 0, 0,
303                 ANY_ROUTE},
304         {"sip_capture", (cmd_function)w_sip_capture1, 1, sipcapture_fixup, 0,
305                 ANY_ROUTE},
306         {"sip_capture", (cmd_function)w_sip_capture2, 2, sipcapture_fixup, 0,
307                 ANY_ROUTE},
308         {"report_capture", (cmd_function)w_report_capture1, 1,
309                 reportcapture_fixup, 0, ANY_ROUTE},
310         {"report_capture", (cmd_function)w_report_capture2, 2,
311                 reportcapture_fixup, 0, ANY_ROUTE},
312         {"report_capture", (cmd_function)w_report_capture3, 3,
313                 reportcapture_fixup, 0, ANY_ROUTE},
314         {"float2int", (cmd_function)w_float2int, 2, float2int_fixup, 0,
315                 ANY_ROUTE},
316         {"sip_capture_forward", (cmd_function)w_sip_capture_forward, 1,
317                 fixup_spve_null, 0, ANY_ROUTE},
318         {0, 0, 0, 0, 0, 0}};
319
320
321 static pv_export_t mod_pvs[] = {
322         {{"hep", sizeof("hep") - 1}, PVT_OTHER, pv_get_hep, 0,
323                 pv_parse_hep_name, 0, 0, 0},
324         {{0, 0}, 0, 0, 0, 0, 0, 0, 0}
325 };
326
327 int capture_mode_param(modparam_t type, void *val);
328
329 /*! \brief
330  * Exported parameters
331  */
332 static param_export_t params[] = {
333         {"db_url", PARAM_STR, &db_url},
334         {"table_name", PARAM_STR, &table_name},
335         {"hash_source", PARAM_STR, &hash_source},
336         {"mt_mode", PARAM_STR, &mt_mode},
337         {"date_column", PARAM_STR, &date_column},
338         {"micro_ts_column", PARAM_STR, &micro_ts_column},
339         {"method_column", PARAM_STR, &method_column},
340         {"correlation_column", PARAM_STR, &correlation_column.s},
341         {"reply_reason_column", PARAM_STR, &reply_reason_column},
342         {"ruri_column", PARAM_STR, &ruri_column},
343         {"ruri_user_column", PARAM_STR, &ruri_user_column},
344         {"ruri_domain_column", PARAM_STR, &ruri_domain_column},
345         {"from_user_column", PARAM_STR, &from_user_column},
346         {"from_domain_column", PARAM_STR, &from_domain_column},
347         {"from_tag_column", PARAM_STR, &from_tag_column},
348         {"to_user_column", PARAM_STR, &to_user_column},
349         {"to_domain_column", PARAM_STR, &to_domain_column},
350         {"to_tag_column", PARAM_STR, &to_tag_column},
351         {"pid_user_column", PARAM_STR, &pid_user_column},
352         {"contact_user_column", PARAM_STR, &contact_user_column},
353         {"auth_user_column", PARAM_STR, &auth_user_column},
354         {"callid_column", PARAM_STR, &callid_column},
355         {"callid_aleg_column", PARAM_STR, &callid_aleg_column},
356         {"via_1_column", PARAM_STR, &via_1_column},
357         {"via_1_branch_column", PARAM_STR, &via_1_branch_column},
358         {"cseq_column", PARAM_STR, &cseq_column},
359         {"diversion_column", PARAM_STR, &diversion_column},
360         {"reason_column", PARAM_STR, &reason_column},
361         {"content_type_column", PARAM_STR, &content_type_column},
362         {"authorization_column", PARAM_STR, &authorization_column},
363         {"user_agent_column", PARAM_STR, &user_agent_column},
364         {"source_ip_column", PARAM_STR, &source_ip_column},
365         {"source_port_column", PARAM_STR, &source_port_column},
366         {"destination_ip_column", PARAM_STR, &dest_ip_column},
367         {"destination_port_column", PARAM_STR, &dest_port_column},
368         {"contact_ip_column", PARAM_STR, &contact_ip_column},
369         {"contact_port_column", PARAM_STR, &contact_port_column},
370         {"originator_ip_column", PARAM_STR, &orig_ip_column},
371         {"originator_port_column", PARAM_STR, &orig_port_column},
372         {"proto_column", PARAM_STR, &proto_column},
373         {"family_column", PARAM_STR, &family_column},
374         {"rtp_stat_column", PARAM_STR, &rtp_stat_column},
375         {"type_column", PARAM_STR, &type_column},
376         {"node_column", PARAM_STR, &node_column},
377         {"msg_column", PARAM_STR, &msg_column},
378         {"custom_field1_column", PARAM_STR, &custom_field1_column},
379         {"custom_field2_column", PARAM_STR, &custom_field2_column},
380         {"custom_field3_column", PARAM_STR, &custom_field3_column},
381         {"capture_on", INT_PARAM, &capture_on},
382         {"capture_node", PARAM_STR, &capture_node},
383         {"raw_sock_children", INT_PARAM, &raw_sock_children},
384         {"hep_capture_on", INT_PARAM, &hep_capture_on},
385         {"raw_socket_listen", PARAM_STR, &raw_socket_listen},
386         {"raw_ipip_capture_on", INT_PARAM, &ipip_capture_on},
387         {"raw_moni_capture_on", INT_PARAM, &moni_capture_on},
388         {"db_insert_mode", INT_PARAM, &db_insert_mode},
389         {"raw_interface", PARAM_STR, &raw_interface},
390         {"promiscious_on", INT_PARAM, &promisc_on},
391         {"raw_moni_bpf_on", INT_PARAM, &bpf_on},
392         {"callid_aleg_header", PARAM_STR, &callid_aleg_header},
393         {"custom_field1_header", PARAM_STR, &custom_field1_header},
394         {"custom_field2_header", PARAM_STR, &custom_field2_header},
395         {"custom_field3_header", PARAM_STR, &custom_field3_header},
396         {"capture_mode", PARAM_STRING | USE_FUNC_PARAM,
397                 (void *)capture_mode_param},
398         {"insert_retries", INT_PARAM, &insert_retries},
399         {"insert_retry_timeout", INT_PARAM, &insert_retry_timeout},
400         {"table_time_sufix", PARAM_STR, &table_time_sufix},
401         {"topoh_unmask", PARAM_INT, &sc_topoh_unmask},
402         {"nonsip_hook", PARAM_INT, &nonsip_hook},
403         {"event_callback", PARAM_STR, &sc_event_callback},
404         {0, 0, 0}
405 };
406
407
408 #ifdef STATISTICS
409 /*
410 stat_var* sipcapture_req;
411 stat_var* sipcapture_rpl;
412
413 stat_export_t sipcapture_stats[] = {
414         {"captured_requests" ,  0,  &sipcapture_req  },
415         {"captured_replies"  ,  0,  &sipcapture_rpl  },
416         {0,0,0}
417 };
418 */
419 stat_export_t *sipcapture_stats = NULL;
420 #endif
421
422 /*! \brief module exports */
423 struct module_exports exports = {
424         "sipcapture", DEFAULT_DLFLAGS, /*!< dlopen flags */
425         cmds,                                              /*!< Exported functions */
426         params,                                            /*!< Exported parameters */
427 #ifdef STATISTICS
428         //      sipcapture_stats,  /*!< exported statistics */
429         0,
430 #else
431         0, /*!< exported statistics */
432 #endif
433         0,                 /*!< exported MI functions */
434         mod_pvs,   /*!< exported pseudo-variables */
435         0,                 /*!< extra processes */
436         mod_init,  /*!< module initialization function */
437         0,                 /*!< response function */
438         destroy,   /*!< destroy function */
439         child_init /*!< child initialization function */
440 };
441
442
443 /* returns number of tables if successful
444  * <0 if failed
445  */
446 int parse_table_names(str table_name, str **table_names)
447 {
448
449         char *p = NULL;
450         unsigned int no_tables;
451         char *table_name_cpy;
452         unsigned int i;
453
454         /*parse and save table names*/
455         no_tables = 1;
456         i = 0;
457
458         str *names;
459
460         table_name_cpy = (char *)pkg_malloc(sizeof(char) * table_name.len + 1);
461         if(table_name_cpy == NULL) {
462                 LM_ERR("no more pkg memory left\n");
463                 return -1;
464         }
465         memcpy(table_name_cpy, table_name.s, table_name.len);
466         table_name_cpy[table_name.len] = '\0';
467
468         p = table_name_cpy;
469
470         while(*p) {
471                 if(*p == '|') {
472                         no_tables++;
473                 }
474                 p++;
475         }
476
477         names = (str *)pkg_malloc(sizeof(str) * no_tables);
478         if(names == NULL) {
479                 LM_ERR("no more pkg memory left\n");
480                 pkg_free(table_name_cpy);
481                 return -1;
482         }
483         p = strtok(table_name_cpy, "| \t");
484         while(p != NULL) {
485                 LM_INFO("INFO: table name:%s\n", p);
486                 names[i].len = strlen(p);
487                 names[i].s = (char *)pkg_malloc(sizeof(char) * names[i].len);
488                 memcpy(names[i].s, p, names[i].len);
489                 i++;
490                 p = strtok(NULL, "| \t");
491         }
492
493         pkg_free(table_name_cpy);
494
495         *table_names = names;
496
497         return no_tables;
498 }
499
500 /* checks for some missing fields*/
501 int check_capture_mode(_capture_mode_data_t *n)
502 {
503
504
505         if(!n->db_url.s || !n->db_url.len) {
506                 LM_ERR("db_url not set\n");
507                 goto error;
508         }
509
510         if(!n->mtmode) {
511                 LM_ERR("mt_mode not set\n");
512                 goto error;
513         } else if(!n->no_tables || !n->table_names) {
514                 LM_ERR("table names not set\n");
515                 goto error;
516         }
517         return 0;
518
519 error:
520         LM_ERR("parsing capture_mode: not all needed parameters are set. Please "
521                         "check again\n");
522         return -1;
523 }
524
525 int capture_mode_set_params(_capture_mode_data_t *n, str *params)
526 {
527
528
529         param_t *params_list = NULL;
530         param_hooks_t phooks;
531         param_t *pit = NULL;
532         db_func_t db_funcs;
533
534         str s;
535         LM_DBG("to tokenize: [%.*s]\n", params->len, params->s);
536         if(n == NULL || params == NULL)
537                 return -1;
538         s = *params;
539
540         if(parse_params(&s, CLASS_ANY, &phooks, &params_list) < 0)
541                 return -1;
542         for(pit = params_list; pit; pit = pit->next) {
543                 LM_DBG("parameter is [%.*s]\n", pit->name.len, pit->name.s);
544                 LM_DBG("parameter value is [%.*s]\n", pit->body.len, pit->body.s);
545                 if(pit->name.len == 6
546                                 && strncmp(pit->name.s, "db_url", pit->name.len) == 0) {
547
548                         n->db_url.len = pit->body.len;
549                         n->db_url.s = (char *)pkg_malloc(sizeof(char) * n->db_url.len);
550                         if(!n->db_url.s) {
551                                 LM_ERR("no more pkg memory\n");
552                                 goto error;
553                         }
554                         memcpy(n->db_url.s, pit->body.s, n->db_url.len);
555
556                         if(db_bind_mod(&n->db_url, &db_funcs)) {
557
558                                 LM_ERR("parsing capture_mode: could not bind db funcs for "
559                                                 "url:[%.*s]\n",
560                                                 n->db_url.len, n->db_url.s);
561                                 goto error;
562                         }
563                         n->db_funcs = db_funcs;
564
565                         if(!DB_CAPABILITY(n->db_funcs, DB_CAP_INSERT)) {
566                                 LM_ERR("parsing capture_mode: database modules does not "
567                                                 "provide all functions needed"
568                                                 " by module\n");
569                                 goto error;
570                         }
571
572                 }
573
574                 else if(pit->name.len == 10
575                                 && strncmp(pit->name.s, "table_name", pit->name.len) == 0) {
576                         if((int)(n->no_tables =
577                                                 parse_table_names(pit->body, &n->table_names))
578                                         < 0) {
579                                 LM_ERR("parsing capture_mode: table name parsing failed\n");
580                                 goto error;
581                         }
582
583                 } else if(pit->name.len == 7
584                                 && strncmp(pit->name.s, "mt_mode", pit->name.len) == 0) {
585
586                         if(pit->body.len == 4
587                                         && strncmp(pit->body.s, "rand", pit->body.len) == 0) {
588                                 n->mtmode = mode_random;
589                         } else if(pit->body.len == 11
590                                         && strncmp(pit->body.s, "round_robin", pit->body.len)
591                                         == 0) {
592                                 n->mtmode = mode_round_robin;
593                         } else if(pit->body.len == 4
594                                         && strncmp(pit->body.s, "hash", pit->body.len) == 0) {
595                                 n->mtmode = mode_hash;
596                         } else {
597                                 LM_ERR("parsing capture_mode: capture mode not recognized: "
598                                                 "[%.*s]\n",
599                                                 pit->body.len, pit->body.s);
600                                 goto error;
601                         }
602                 } else if(pit->name.len == 11
603                                 && strncmp(pit->name.s, "hash_source", pit->name.len) == 0) {
604                         if((n->hash_source = get_hash_source(pit->body.s)) == hs_error) {
605                                 LM_ERR("parsing capture_mode: hash source unrecognized: "
606                                                 "[%.*s]\n",
607                                                 pit->body.len, pit->body.s);
608                                 goto error;
609                         }
610                 }
611         }
612         if(n->mtmode == mode_hash
613                         && (n->hash_source == 0 || n->hash_source == hs_error)) {
614                 LM_WARN("Hash mode set, but no hash source provided for [%.*s]. Will "
615                                 "consider hashing by call id.\n",
616                                 n->name.len, n->name.s);
617                 n->hash_source = hs_call_id;
618         }
619
620         if(check_capture_mode(n)) {
621                 goto error;
622         }
623
624         return 0;
625
626 error:
627         if(n->db_url.s) {
628                 pkg_free(n->db_url.s);
629         }
630         return -1;
631 }
632
633 void *capture_mode_init(str *name, str *params)
634 {
635
636         _capture_mode_data_t *n = NULL;
637         unsigned int id;
638
639         if(!name || name->len == 0) {
640                 LM_ERR("capture_mode name is empty\n");
641                 goto error;
642         }
643         if(!params || params->len == 0) {
644                 LM_ERR("capture_mode params are empty\n");
645                 goto error;
646         }
647         id = core_case_hash(name, 0, 0);
648         n = (_capture_mode_data_t *)pkg_malloc(sizeof(_capture_mode_data_t));
649         if(!n) {
650                 LM_ERR("no more pkg memory\n");
651                 goto error;
652         }
653         memset(n, 0, sizeof(_capture_mode_data_t));
654         n->id = id;
655         n->name.len = name->len;
656         n->name.s = (char *)pkg_malloc(sizeof(char) * n->name.len);
657         if(!n->name.s) {
658                 LM_ERR("no more pkg memory\n");
659                 goto error;
660         }
661         memcpy(n->name.s, name->s, n->name.len);
662         n->table_names = (str *)pkg_malloc(sizeof(str));
663         if(!n->table_names) {
664                 LM_ERR("no more pkg memory\n");
665                 goto error;
666         }
667
668
669         if(capture_mode_set_params(n, params) < 0) {
670                 LM_ERR("capture mode parsing failed\n");
671                 goto error;
672         }
673
674         n->next = capture_modes_root;
675         capture_modes_root = n;
676         return n;
677
678 error:
679         if(n) {
680                 if(n->name.s) {
681                         pkg_free(n->name.s);
682                 }
683                 if(n->table_names) {
684                         pkg_free(n->table_names);
685                 }
686                 pkg_free(n);
687         }
688         return 0;
689 }
690
691 /*parse name=>param1=>val1;param2=>val2;..*/
692 int capture_mode_param(modparam_t type, void *val)
693 {
694
695
696         str name;
697         str in;
698         str tok;
699         char *p;
700
701         in.s = val;
702         in.len = strlen(in.s);
703         p = in.s;
704
705         while(p < in.s + in.len
706                         && (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r'))
707                 p++;
708         if(p > in.s + in.len || *p == '\0')
709                 goto error;
710         name.s = p;
711         while(p < in.s + in.len) {
712                 if(*p == '=' || *p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
713                         break;
714                 p++;
715         }
716
717         if(p > in.s + in.len || *p == '\0')
718                 goto error;
719         name.len = p - name.s;
720         if(*p != '=') {
721                 while(p < in.s + in.len
722                                 && (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r'))
723                         p++;
724                 if(p > in.s + in.len || *p == '\0' || *p != '=')
725                         goto error;
726         }
727         p++;
728         if(*p != '>')
729                 goto error;
730         p++;
731         while(p < in.s + in.len
732                         && (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r'))
733                 p++;
734         tok.s = p;
735         tok.len = in.len + (int)(in.s - p);
736
737         LM_DBG("capture_mode name: [%.*s] data: [%.*s]\n", name.len, name.s,
738                         tok.len, tok.s);
739         if(!capture_mode_init(&name, &tok)) {
740                 return -1;
741         }
742         return 0;
743
744 error:
745         LM_ERR("invalid parameter [%.*s] at [%d]\n", in.len, in.s, (int)(p - in.s));
746         return -1;
747 }
748
749
750 /*! \brief Initialize sipcapture module */
751 static int mod_init(void)
752 {
753         struct ip_addr *ip = NULL;
754         char *def_params = NULL;
755         sr_kemi_eng_t *keng = NULL;
756
757 #ifdef STATISTICS
758         int cnt = 0;
759         int i = 0;
760         char *stat_name = NULL;
761         _capture_mode_data_t *c = NULL;
762         int def;
763 #endif
764
765         if(sipcapture_init_rpc() != 0) {
766                 LM_ERR("failed to register RPC commands\n");
767                 return -1;
768         }
769
770         if(sc_topoh_unmask == 1) {
771                 /* bind the topoh API */
772                 if(topoh_load_api(&thb) != 0) {
773                         LM_ERR("cannot bind to topoh API\n");
774                         return -1;
775                 }
776         }
777
778         /* Check the table name - if table_name is empty and no capture modes
779          * are defined, then error*/
780         if(!table_name.len && capture_modes_root == NULL) {
781                 LM_ERR("ERROR: sipcapture: mod_init: table_name is not defined or "
782                                 "empty\n");
783                 return -1;
784         }
785
786
787         /*create a default capture mode using the default parameters*/
788         def_params = (char *)pkg_malloc(
789                         snprintf(NULL, 0,
790                                 "db_url=%s;table_name=%s;mt_mode=%s;hash_source=%s",
791                                 db_url.s, table_name.s, mt_mode.s, hash_source.s)
792                         + 1);
793         sprintf(def_params, "db_url=%s;table_name=%s;mt_mode=%s;hash_source=%s",
794                         db_url.s, table_name.s, mt_mode.s, hash_source.s);
795
796         str def_name, def_par;
797         def_name.s = strdup("default");
798         def_name.len = 7;
799         def_par.s = def_params;
800         def_par.len = strlen(def_params);
801
802         LM_DBG("def_params is: %s\n", def_params);
803
804
805         if((capture_def = capture_mode_init(&def_name, &def_par)) == NULL) {
806                 LM_WARN("Default capture mode configuration failed. Suppose "
807                                 "sip_capture calls will use other defined capture modes.\n");
808         }
809
810         pkg_free(def_params);
811
812         if(sipcapture_parse_aleg_callid_headers() < 0) {
813                 return -1;
814         }
815
816
817 #ifdef STATISTICS
818
819         int route_no;
820         c = capture_modes_root;
821         while(c) {
822                 cnt++;
823                 c = c->next;
824         }
825         /*requests and replies for each mode + 1 zero-filled stat_export */
826         stat_export_t *stats =
827                 (stat_export_t *)shm_malloc(sizeof(stat_export_t) * cnt * 2 + 1);
828
829         c = capture_modes_root;
830
831         while(c) {
832                 /*for the default capture_mode, don't add it's name to the stat name*/
833                 def = (capture_def && c == capture_def) ? 1 : 0;
834                 stat_name = (char *)shm_malloc(
835                                 sizeof(char)
836                                 * (snprintf(NULL, 0,
837                                                 (def) ? "captured_requests%.*s"
838                                                 : "captured_requests[%.*s]",
839                                                 (def) ? 0 : c->name.len, (def) ? "" : c->name.s)
840                                         + 1));
841                 sprintf(stat_name,
842                                 (def) ? "captured_requests%.*s" : "captured_requests[%.*s]",
843                                 (def) ? 0 : c->name.len, (def) ? "" : c->name.s);
844                 stats[i].name = stat_name;
845                 stats[i].flags = 0;
846                 stats[i].stat_pointer = &c->sipcapture_req;
847                 i++;
848                 stat_name = (char *)shm_malloc(
849                                 sizeof(char)
850                                 * (snprintf(NULL, 0,
851                                                 (def) ? "captured_replies%.*s"
852                                                 : "captured_replies[%.*s]",
853                                                 (def) ? 0 : c->name.len, (def) ? "" : c->name.s)
854                                         + 1));
855                 sprintf(stat_name,
856                                 (def) ? "captured_replies%.*s" : "captured_replies[%.*s]",
857                                 (def) ? 0 : c->name.len, (def) ? "" : c->name.s);
858                 stats[i].name = stat_name;
859                 stats[i].flags = 0;
860                 stats[i].stat_pointer = &c->sipcapture_rpl;
861                 i++;
862                 c = c->next;
863         }
864         stats[i].name = 0;
865         stats[i].flags = 0;
866         stats[i].stat_pointer = 0;
867
868         sipcapture_stats = stats;
869
870         /* register statistics */
871         if(register_module_stats(exports.name, sipcapture_stats) != 0) {
872                 LM_ERR("failed to register core statistics\n");
873                 return -1;
874         }
875 #endif
876
877         kam_srand(time(NULL));
878
879
880         if(db_insert_mode) {
881                 LM_INFO("INFO: sipcapture: mod_init: you have enabled INSERT DELAYED \
882                                 Make sure your DB can support it\n");
883         }
884
885         capture_on_flag = (int *)shm_malloc(sizeof(int));
886         if(capture_on_flag == NULL) {
887                 LM_ERR("no more shm memory left\n");
888                 return -1;
889         }
890
891         *capture_on_flag = capture_on;
892
893         if(nonsip_hook) {
894                 if(sc_event_callback.s == NULL || sc_event_callback.len <= 0) {
895                         route_no = route_get(&event_rt, "sipcapture:request");
896                         if(route_no == -1) {
897                                 LM_ERR("failed to find event_route[sipcapture:request]\n");
898                                 return -1;
899                         }
900
901                         if(event_rt.rlist[route_no] == 0) {
902                                 LM_ERR("event_route[sipcapture:request] is empty\n");
903                                 return -1;
904                         }
905
906                         hep_route_no = route_no;
907                 } else {
908                         hep_route_no = -1;
909                         keng = sr_kemi_eng_get();
910                         if(keng == NULL) {
911                                 LM_DBG("event callback (%s) set, but no cfg engine\n",
912                                                 sc_event_callback.s);
913                                 return -1;
914                         }
915                 }
916
917                 if(sr_event_register_cb(SREV_RCV_NOSIP, nosip_hep_msg) < 0) {
918                         LM_ERR("failed to register SREV_RCV_NOSIP event\n");
919                         return -1;
920                 }
921         } else {
922                 /* register DGRAM event */
923                 if(sr_event_register_cb(SREV_NET_DGRAM_IN, hep_msg_received) < 0) {
924                         LM_ERR("failed to register SREV_NET_DGRAM_IN event\n");
925                         return -1;
926                 }
927         }
928
929         if(ipip_capture_on && moni_capture_on) {
930                 LM_ERR("only one RAW mode is supported. Please disable ipip_capture_on "
931                                 "or moni_capture_on\n");
932                 return -1;
933         }
934
935         if((insert_retries < 0) || (insert_retries > 500)) {
936                 LM_ERR("insert_retries should be a value between 0 and 500\n");
937                 return -1;
938         }
939
940         if((0 == insert_retries) && (insert_retry_timeout != 0)) {
941                 LM_ERR("insert_retry_timeout has no meaning when insert_retries is not "
942                                 "set\n");
943         }
944
945         if((insert_retry_timeout < 0) || (insert_retry_timeout > 300)) {
946                 LM_ERR("insert_retry_timeout should be a value between 0 and 300\n");
947                 return -1;
948         }
949
950         /* raw processes for IPIP encapsulation */
951         if(ipip_capture_on || moni_capture_on) {
952                 register_procs(raw_sock_children);
953
954                 if(extract_host_port()
955                                 && (((ip = str2ip(&raw_socket_listen)) == NULL)
956                                         && ((ip = str2ip6(&raw_socket_listen)) == NULL))) {
957                         LM_ERR("sipcapture mod_init: bad RAW IP: %.*s\n",
958                                         raw_socket_listen.len, raw_socket_listen.s);
959                         return -1;
960                 }
961
962                 if(moni_capture_on && !moni_port_start) {
963                         LM_ERR("ERROR:sipcapture:mod_init: Please define port/portrange"
964                                         " in 'raw_socket_listen', before activate"
965                                         " monitoring capture\n");
966                         return -1;
967                 }
968
969                 raw_sock_desc = raw_capture_socket(raw_socket_listen.len ? ip : 0,
970                                 raw_interface.len ? &raw_interface : 0, moni_port_start,
971                                 moni_port_end, ipip_capture_on ? IPPROTO_IPIP : htons(0x0800));
972
973                 if(raw_sock_desc < 0) {
974                         LM_ERR("could not initialize raw udp socket:"
975                                         " %s (%d)\n",
976                                         strerror(errno), errno);
977                         if(errno == EPERM)
978                                 LM_ERR("could not initialize raw socket on startup"
979                                                 " due to inadequate permissions, please"
980                                                 " restart as root or with CAP_NET_RAW\n");
981
982                         return -1;
983                 }
984
985                 if(promisc_on && raw_interface.len) {
986
987                         memset(&ifr, 0, sizeof(ifr));
988                         memcpy(ifr.ifr_name, raw_interface.s, raw_interface.len);
989
990
991 #ifdef __OS_linux
992                         if(ioctl(raw_sock_desc, SIOCGIFFLAGS, &ifr) < 0) {
993                                 LM_ERR("could not get flags from interface [%.*s]:"
994                                                 " %s (%d)\n",
995                                                 raw_interface.len, raw_interface.s, strerror(errno),
996                                                 errno);
997                                 goto error;
998                         }
999
1000                         ifr.ifr_flags |= IFF_PROMISC;
1001
1002                         if(ioctl(raw_sock_desc, SIOCSIFFLAGS, &ifr) < 0) {
1003                                 LM_ERR("could not set PROMISC flag to interface [%.*s]:"
1004                                                 " %s (%d)\n",
1005                                                 raw_interface.len, raw_interface.s, strerror(errno),
1006                                                 errno);
1007                                 goto error;
1008                         }
1009 #endif
1010                 }
1011         }
1012
1013         return 0;
1014 #ifdef __OS_linux
1015 error:
1016         if(raw_sock_desc)
1017                 close(raw_sock_desc);
1018         return -1;
1019 #endif
1020 }
1021
1022 static int sipcapture_fixup(void **param, int param_no)
1023 {
1024
1025         _capture_mode_data_t *con;
1026
1027         str val;
1028         unsigned int id;
1029
1030         if(param_no == 1) {
1031                 return fixup_var_pve_str_12(param, 1);
1032         }
1033         if(param_no == 2) {
1034
1035                 val.s = (char *)*param;
1036                 val.len = strlen((char *)*param);
1037
1038
1039                 con = capture_modes_root;
1040                 id = core_case_hash(&val, 0, 0);
1041                 while(con) {
1042                         if(id == con->id && con->name.len == val.len
1043                                         && strncmp(con->name.s, val.s, val.len) == 0) {
1044                                 *param = (void *)con;
1045                                 LM_DBG("found capture mode :[%.*s]\n", con->name.len,
1046                                                 con->name.s);
1047                                 return 0;
1048                         }
1049                         con = con->next;
1050                 }
1051
1052                 LM_ERR("no capture mode found\n");
1053                 return -1;
1054         }
1055
1056         return 0;
1057 }
1058
1059 static int reportcapture_fixup(void **param, int param_no)
1060 {
1061
1062         if(param_no == 1) {
1063                 return fixup_var_pve_str_12(param, 1);
1064         }
1065         if(param_no == 2) {
1066                 return fixup_var_pve_str_12(param, 1);
1067         }
1068         if(param_no == 3) {
1069                 return fixup_var_pve_str_12(param, 1);
1070         }
1071
1072         return 0;
1073 }
1074
1075 static int float2int_fixup(void **param, int param_no)
1076 {
1077
1078         if(param_no == 1) {
1079                 return fixup_var_pve_str_12(param, 1);
1080         }
1081         if(param_no == 2) {
1082                 return fixup_var_pve_str_12(param, 1);
1083         }
1084
1085         return 0;
1086 }
1087
1088
1089 static int w_float2int(sip_msg_t *_m, char *_val, char *_coof)
1090 {
1091         str value = {0};
1092         str coof = {0};
1093         int ret = 0;
1094
1095         if(_val != NULL && (get_str_fparam(&value, _m, (fparam_t *)_val) < 0)) {
1096                 LM_ERR("invalid table parameter [%s] [%s]\n", _val, value.s);
1097                 return -1;
1098         }
1099
1100         if(_coof != NULL && (get_str_fparam(&coof, _m, (fparam_t *)_coof) < 0)) {
1101                 LM_ERR("invalid data parameter [%s] [%s]\n", _coof, coof.s);
1102                 return -1;
1103         }
1104
1105         if(value.s == NULL || coof.s == NULL)
1106                 return -1;
1107
1108         ret = (int)(atof(value.s) * atoi(coof.s));
1109
1110         return ret ? ret : -1;
1111 }
1112
1113 static int ki_float2int(sip_msg_t *_m, str *_val, str *_coof)
1114 {
1115         int ret = 0;
1116
1117         if(_val == NULL || _val->s == NULL || _val->len <= 0
1118                         || _coof == NULL || _coof->s == NULL || _coof->len <= 0)
1119                 return -1;
1120
1121         ret = (int)(atof(_val->s) * atoi(_coof->s));
1122
1123         return ret ? ret : -1;
1124 }
1125
1126 static int w_sip_capture(sip_msg_t *_m, char *_table,
1127                 _capture_mode_data_t *cm_data)
1128 {
1129         str table = {0};
1130
1131         if(_table != NULL && (get_str_fparam(&table, _m, (fparam_t *)_table) < 0)) {
1132                 LM_ERR("invalid table parameter [%s] [%s]\n", _table, table.s);
1133                 return -1;
1134         }
1135
1136         return sip_capture(_m, (table.len > 0) ? &table : NULL, cm_data);
1137 }
1138
1139 static int w_sip_capture0(sip_msg_t *_m, char *_p1, char *_p2)
1140 {
1141         return w_sip_capture(_m, NULL, NULL);
1142 }
1143
1144 static int w_sip_capture1(sip_msg_t *_m, char *_table, char *_p2)
1145 {
1146         return w_sip_capture(_m, _table, NULL);
1147 }
1148
1149 static int w_sip_capture2(sip_msg_t *_m, char *_table, char *_cmdata)
1150 {
1151         return w_sip_capture(_m, _table, (_capture_mode_data_t*)_cmdata);
1152 }
1153
1154 static int ki_sip_capture_mode(sip_msg_t *_m, str *_table, str *_cmdata)
1155 {
1156         _capture_mode_data_t *pcmdata = NULL;
1157         unsigned int id;
1158
1159         if(_cmdata != NULL && _cmdata->len > 0) {
1160                 pcmdata = capture_modes_root;
1161                 id = core_case_hash(_cmdata, 0, 0);
1162                 while(pcmdata) {
1163                         if(id == pcmdata->id && pcmdata->name.len == _cmdata->len
1164                                         && strncmp(pcmdata->name.s, _cmdata->s, _cmdata->len) == 0) {
1165                                 break;
1166                         }
1167                         pcmdata = pcmdata->next;
1168                 }
1169                 if(pcmdata) {
1170                         LM_DBG("found capture mode: [%.*s]\n", _cmdata->len, _cmdata->s);
1171                 } else {
1172                         LM_ERR("not found capture mode: [%.*s]\n", _cmdata->len, _cmdata->s);
1173                         return -1;
1174                 }
1175         }
1176
1177         return sip_capture(_m, (_table != NULL && _table->len > 0) ? _table : NULL,
1178                         pcmdata);
1179 }
1180
1181 static int ki_sip_capture(sip_msg_t *_m)
1182 {
1183         return sip_capture(_m, NULL, NULL);
1184 }
1185
1186 static int ki_sip_capture_table(sip_msg_t *_m, str *_table)
1187 {
1188         return sip_capture(_m, _table, NULL);
1189 }
1190
1191 static int w_report_capture1(sip_msg_t *_m, char *_table, char *_p2)
1192 {
1193         return w_report_capture3(_m, _table, NULL, NULL);
1194 }
1195
1196 static int w_report_capture2(sip_msg_t *_m, char *_table, char *_corr)
1197 {
1198         return w_report_capture3(_m, _table, _corr, NULL);
1199 }
1200
1201 static int w_report_capture3(sip_msg_t *_m, char *_table, char *_corr,
1202                 char *_data)
1203 {
1204         str table = {0};
1205         str corr = {0};
1206         str data = {0};
1207
1208         if(_table != NULL && (get_str_fparam(&table, _m, (fparam_t *)_table) < 0)) {
1209                 LM_ERR("invalid table parameter [%s] [%s]\n", _table, table.s);
1210                 return -1;
1211         }
1212
1213         if(_corr != NULL && (get_str_fparam(&corr, _m, (fparam_t *)_corr) < 0)) {
1214                 LM_ERR("invalid corr parameter [%s] [%s]\n", _corr, corr.s);
1215                 return -1;
1216         }
1217
1218         if(_data != NULL && (get_str_fparam(&data, _m, (fparam_t *)_data) < 0)) {
1219
1220
1221                 LM_ERR("invalid data parameter [%s] [%s]\n", _data, data.s);
1222                 return -1;
1223         }
1224
1225         /* workaround for data function */
1226         if(data.len > 0 && !strncmp(data.s, "report_capture", data.len))
1227                 data.len = 0;
1228
1229         return report_capture(_m, (table.len > 0) ? &table : NULL,
1230                         (corr.len > 0) ? &corr : NULL, (data.len > 0) ? &data : NULL);
1231 }
1232
1233
1234 static int ki_report_capture_data(sip_msg_t *_m, str *_table, str *_cid,
1235                 str *_data)
1236 {
1237         /* workaround for data function */
1238         if(_data!=NULL && _data->len > 0 && _data->len == 14
1239                         && !strncmp(_data->s, "report_capture", 14)) {
1240                 return report_capture(_m,
1241                                 (_table!=NULL && _table->len > 0) ? _table : NULL,
1242                                 (_cid != NULL && _cid->len > 0) ? _cid : NULL, NULL);
1243
1244         } else {
1245                 return report_capture(_m,
1246                                 (_table!=NULL && _table->len > 0) ? _table : NULL,
1247                                 (_cid != NULL && _cid->len > 0) ? _cid : NULL,
1248                                 (_data != NULL && _data->len > 0) ? _data : NULL);
1249
1250         }
1251 }
1252
1253 static int ki_report_capture(sip_msg_t *_m, str *_table)
1254 {
1255         return ki_report_capture_data(_m, _table, NULL, NULL);
1256 }
1257
1258 static int ki_report_capture_cid(sip_msg_t *_m, str *_table, str *_cid)
1259 {
1260         return ki_report_capture_data(_m, _table, _cid, NULL);
1261 }
1262
1263 int extract_host_port(void)
1264 {
1265         if(raw_socket_listen.len) {
1266                 char *p1, *p2;
1267                 p1 = raw_socket_listen.s;
1268
1269                 if((p1 = strrchr(p1, ':')) != 0) {
1270                         *p1 = '\0';
1271                         p1++;
1272                         p2 = p1;
1273                         if((p2 = strrchr(p2, '-')) != 0) {
1274                                 p2++;
1275                                 moni_port_end = atoi(p2);
1276                                 p1[strlen(p1) - strlen(p2) - 1] = '\0';
1277                         }
1278                         moni_port_start = atoi(p1);
1279                         raw_socket_listen.len = strlen(raw_socket_listen.s);
1280                 }
1281                 return 1;
1282         }
1283         return 0;
1284 }
1285
1286
1287 static int child_init(int rank)
1288 {
1289
1290         _capture_mode_data_t *c;
1291
1292         if(rank == PROC_MAIN && (ipip_capture_on || moni_capture_on)) {
1293                 if(init_rawsock_children() < 0)
1294                         return -1;
1295         }
1296
1297         if(rank == PROC_INIT || rank == PROC_MAIN || rank == PROC_TCP_MAIN)
1298                 return 0; /* do nothing for the main process */
1299
1300
1301         c = capture_modes_root;
1302
1303         while(c) {
1304                 if(!c->db_url.s || !c->db_url.len) {
1305                         LM_ERR("DB URL not set for capture mode:[%.*s]\n", c->name.len,
1306                                         c->name.s);
1307                         return -1;
1308                 }
1309                 c->db_con = c->db_funcs.init(&c->db_url);
1310                 if(!c->db_con) {
1311                         LM_ERR("unable to connect to database [%.*s] from capture_mode "
1312                                         "param.\n",
1313                                         c->db_url.len, c->db_url.s);
1314                         return -1;
1315                 }
1316                 if(c->mtmode == mode_round_robin && rank > 0) {
1317                         c->rr_idx = rank % c->no_tables;
1318                 }
1319                 c = c->next;
1320         }
1321
1322
1323         heptime = (struct hep_timeinfo *)pkg_malloc(sizeof(struct hep_timeinfo));
1324         if(heptime == NULL) {
1325                 LM_ERR("no more pkg memory left\n");
1326                 return -1;
1327         }
1328
1329         heptime->tv_sec = 0;
1330
1331         return 0;
1332 }
1333
1334 /*
1335  * RAW IPIP || Monitoring listeners
1336  */
1337 int init_rawsock_children(void)
1338 {
1339         int i;
1340         pid_t pid;
1341
1342         for(i = 0; i < raw_sock_children; i++) {
1343                 pid = fork_process(PROC_UNIXSOCK, "homer raw socket", 1);
1344                 if(pid < 0) {
1345                         ERR("Unable to fork: %s\n", strerror(errno));
1346                         return -1;
1347                 } else if(pid == 0) { /* child */
1348                         raw_capture_rcv_loop(raw_sock_desc, moni_port_start, moni_port_end,
1349                                         moni_capture_on ? 0 : 1);
1350                 }
1351                 /* Parent */
1352         }
1353
1354         DBG("Raw IPIP socket server successfully initialized\n");
1355         return 1;
1356 }
1357
1358
1359 static void destroy(void)
1360 {
1361         //if (capture_def->db_con!=NULL)
1362         //      capture_def->db_funcs.close(capture_def->db_con);
1363
1364         /*free content from the linked list*/
1365         _capture_mode_data_t *c;
1366         _capture_mode_data_t *c0;
1367
1368         c = capture_modes_root;
1369
1370         while(c) {
1371                 c0 = c->next;
1372                 if(c->name.s) {
1373                         pkg_free(c->name.s);
1374                 }
1375                 if(c->db_url.s) {
1376                         pkg_free(c->db_url.s);
1377                 }
1378                 if(c->db_con) {
1379                         c->db_funcs.close(c->db_con);
1380                 }
1381                 if(c->table_names) {
1382                         pkg_free(c->table_names);
1383                 }
1384
1385                 pkg_free(c);
1386                 c = c0;
1387         }
1388
1389         if(capture_on_flag)
1390                 shm_free(capture_on_flag);
1391
1392         if(heptime)
1393                 pkg_free(heptime);
1394
1395         if(raw_sock_desc > 0) {
1396                 if(promisc_on && raw_interface.len) {
1397 #ifdef __OS_linux
1398                         ifr.ifr_flags &= ~(IFF_PROMISC);
1399
1400                         if(ioctl(raw_sock_desc, SIOCSIFFLAGS, &ifr) < 0) {
1401                                 LM_ERR("destroy: could not remove PROMISC flag from interface "
1402                                                 "[%.*s]:"
1403                                                 " %s (%d)\n",
1404                                                 raw_interface.len, raw_interface.s, strerror(errno),
1405                                                 errno);
1406                         }
1407 #endif
1408                 }
1409                 close(raw_sock_desc);
1410         }
1411
1412
1413         //      if (table_names){
1414         //              pkg_free(table_names);
1415         //      }
1416 }
1417
1418 static int sip_capture_prepare(sip_msg_t *msg)
1419 {
1420         /* We need parse all headers */
1421         if(parse_headers(msg, HDR_CALLID_F | HDR_EOH_F, 0) != 0) {
1422                 LM_ERR("cannot parse headers\n");
1423                 return 0;
1424         }
1425
1426         return 0;
1427 }
1428
1429 static int sip_capture_store(struct _sipcapture_object *sco, str *dtable,
1430                 _capture_mode_data_t *cm_data)
1431 {
1432         db_key_t db_keys[NR_KEYS];
1433         db_val_t db_vals[NR_KEYS];
1434
1435         str tmp, corrtmp, ntab;
1436         int ii = 0;
1437         int ret = 0;
1438         int counter = 0;
1439         db_insert_f insert;
1440         time_t retry_failed_time = 0;
1441         struct tm capt_ts;
1442         str ocallid;
1443
1444         /* new */
1445         str *table = NULL;
1446         _capture_mode_data_t *c = NULL;
1447         char strftime_buf[128];
1448         time_t tvsec_;
1449
1450         c = (cm_data) ? cm_data : capture_def;
1451         if(!c) {
1452                 LM_ERR("no connection mode available to store data\n");
1453                 return -1;
1454         }
1455
1456         if(sco == NULL) {
1457                 LM_DBG("invalid parameter\n");
1458                 return -1;
1459         }
1460
1461         if(sc_topoh_unmask == 1) {
1462                 if(thb.unmask_callid(&sco->callid, &ocallid) == 0) {
1463                         sco->callid = ocallid;
1464                 }
1465         }
1466
1467         if(correlation_id) {
1468                 corrtmp.s = correlation_id;
1469                 corrtmp.len = strlen(correlation_id);
1470         }
1471
1472         db_keys[0] = &date_column;
1473         db_vals[0].type = DB1_DATETIME;
1474         db_vals[0].nul = 0;
1475         db_vals[0].val.time_val = (sco->tmstamp / 1000000);
1476
1477         db_keys[1] = &micro_ts_column;
1478         db_vals[1].type = DB1_BIGINT;
1479         db_vals[1].nul = 0;
1480         db_vals[1].val.ll_val = sco->tmstamp;
1481
1482         db_keys[2] = &method_column;
1483         db_vals[2].type = DB1_STR;
1484         db_vals[2].nul = 0;
1485         db_vals[2].val.str_val = sco->method;
1486
1487         db_keys[3] = &reply_reason_column;
1488         db_vals[3].type = DB1_STR;
1489         db_vals[3].nul = 0;
1490         db_vals[3].val.str_val = sco->reply_reason;
1491
1492         db_keys[4] = &ruri_column;
1493         db_vals[4].type = DB1_STR;
1494         db_vals[4].nul = 0;
1495         db_vals[4].val.str_val = sco->ruri;
1496
1497         db_keys[5] = &ruri_user_column;
1498         db_vals[5].type = DB1_STR;
1499         db_vals[5].nul = 0;
1500         db_vals[5].val.str_val = sco->ruri_user;
1501
1502         db_keys[6] = &from_user_column;
1503         db_vals[6].type = DB1_STR;
1504         db_vals[6].nul = 0;
1505         db_vals[6].val.str_val = sco->from_user;
1506
1507         db_keys[7] = &from_tag_column;
1508         db_vals[7].type = DB1_STR;
1509         db_vals[7].nul = 0;
1510         db_vals[7].val.str_val = sco->from_tag;
1511
1512         db_keys[8] = &to_user_column;
1513         db_vals[8].type = DB1_STR;
1514         db_vals[8].nul = 0;
1515         db_vals[8].val.str_val = sco->to_user;
1516
1517         db_keys[9] = &to_tag_column;
1518         db_vals[9].type = DB1_STR;
1519         db_vals[9].nul = 0;
1520         db_vals[9].val.str_val = sco->to_tag;
1521
1522         db_keys[10] = &pid_user_column;
1523         db_vals[10].type = DB1_STR;
1524         db_vals[10].nul = 0;
1525         db_vals[10].val.str_val = sco->pid_user;
1526
1527         db_keys[11] = &contact_user_column;
1528         db_vals[11].type = DB1_STR;
1529         db_vals[11].nul = 0;
1530         db_vals[11].val.str_val = sco->contact_user;
1531
1532         db_keys[12] = &auth_user_column;
1533         db_vals[12].type = DB1_STR;
1534         db_vals[12].nul = 0;
1535         db_vals[12].val.str_val = sco->auth_user;
1536
1537         db_keys[13] = &callid_column;
1538         db_vals[13].type = DB1_STR;
1539         db_vals[13].nul = 0;
1540         db_vals[13].val.str_val = sco->callid;
1541
1542         db_keys[14] = &callid_aleg_column;
1543         db_vals[14].type = DB1_STR;
1544         db_vals[14].nul = 0;
1545         db_vals[14].val.str_val = sco->callid_aleg;
1546
1547         db_keys[15] = &via_1_column;
1548         db_vals[15].type = DB1_STR;
1549         db_vals[15].nul = 0;
1550         db_vals[15].val.str_val = sco->via_1;
1551
1552         db_keys[16] = &via_1_branch_column;
1553         db_vals[16].type = DB1_STR;
1554         db_vals[16].nul = 0;
1555         db_vals[16].val.str_val = sco->via_1_branch;
1556
1557         db_keys[17] = &cseq_column;
1558         db_vals[17].type = DB1_STR;
1559         db_vals[17].nul = 0;
1560         db_vals[17].val.str_val = sco->cseq;
1561
1562         db_keys[18] = &reason_column;
1563         db_vals[18].type = DB1_STR;
1564         db_vals[18].nul = 0;
1565         db_vals[18].val.str_val = sco->reason;
1566
1567         db_keys[19] = &content_type_column;
1568         db_vals[19].type = DB1_STR;
1569         db_vals[19].nul = 0;
1570         db_vals[19].val.str_val = sco->content_type;
1571
1572         db_keys[20] = &authorization_column;
1573         db_vals[20].type = DB1_STR;
1574         db_vals[20].nul = 0;
1575         db_vals[20].val.str_val = sco->authorization;
1576
1577         db_keys[21] = &user_agent_column;
1578         db_vals[21].type = DB1_STR;
1579         db_vals[21].nul = 0;
1580         db_vals[21].val.str_val = sco->user_agent;
1581
1582         db_keys[22] = &source_ip_column;
1583         db_vals[22].type = DB1_STR;
1584         db_vals[22].nul = 0;
1585         db_vals[22].val.str_val = sco->source_ip;
1586
1587         db_keys[23] = &source_port_column;
1588         db_vals[23].type = DB1_INT;
1589         db_vals[23].nul = 0;
1590         db_vals[23].val.int_val = sco->source_port;
1591
1592         db_keys[24] = &dest_ip_column;
1593         db_vals[24].type = DB1_STR;
1594         db_vals[24].nul = 0;
1595         db_vals[24].val.str_val = sco->destination_ip;
1596
1597         db_keys[25] = &dest_port_column;
1598         db_vals[25].type = DB1_INT;
1599         db_vals[25].nul = 0;
1600         db_vals[25].val.int_val = sco->destination_port;
1601
1602         db_keys[26] = &contact_ip_column;
1603         db_vals[26].type = DB1_STR;
1604         db_vals[26].nul = 0;
1605         db_vals[26].val.str_val = sco->contact_ip;
1606
1607         db_keys[27] = &contact_port_column;
1608         db_vals[27].type = DB1_INT;
1609         db_vals[27].nul = 0;
1610         db_vals[27].val.int_val = sco->contact_port;
1611
1612         db_keys[28] = &orig_ip_column;
1613         db_vals[28].type = DB1_STR;
1614         db_vals[28].nul = 0;
1615         db_vals[28].val.str_val = sco->originator_ip;
1616
1617         db_keys[29] = &orig_port_column;
1618         db_vals[29].type = DB1_INT;
1619         db_vals[29].nul = 0;
1620         db_vals[29].val.int_val = sco->originator_port;
1621
1622         db_keys[30] = &proto_column;
1623         db_vals[30].type = DB1_INT;
1624         db_vals[30].nul = 0;
1625         db_vals[30].val.int_val = sco->proto;
1626
1627         db_keys[31] = &family_column;
1628         db_vals[31].type = DB1_INT;
1629         db_vals[31].nul = 0;
1630         db_vals[31].val.int_val = sco->family;
1631
1632         db_keys[32] = &rtp_stat_column;
1633         db_vals[32].type = DB1_STR;
1634         db_vals[32].nul = 0;
1635         db_vals[32].val.str_val = sco->rtp_stat;
1636
1637         db_keys[33] = &type_column;
1638         db_vals[33].type = DB1_INT;
1639         db_vals[33].nul = 0;
1640         db_vals[33].val.int_val = sco->type;
1641
1642         db_keys[34] = &node_column;
1643         db_vals[34].type = DB1_STR;
1644         db_vals[34].nul = 0;
1645         db_vals[34].val.str_val = sco->node;
1646
1647         db_keys[35] = &correlation_column;
1648         db_vals[35].type = DB1_STR;
1649         db_vals[35].nul = 0;
1650         db_vals[35].val.str_val = (correlation_id) ? corrtmp : sco->callid;
1651
1652         db_keys[36] = &from_domain_column;
1653         db_vals[36].type = DB1_STR;
1654         db_vals[36].nul = 0;
1655         db_vals[36].val.str_val = sco->from_domain;
1656
1657         db_keys[37] = &to_domain_column;
1658         db_vals[37].type = DB1_STR;
1659         db_vals[37].nul = 0;
1660         db_vals[37].val.str_val = sco->to_domain;
1661
1662         db_keys[38] = &ruri_domain_column;
1663         db_vals[38].type = DB1_STR;
1664         db_vals[38].nul = 0;
1665         db_vals[38].val.str_val = sco->ruri_domain;
1666
1667         db_keys[39] = &diversion_column;
1668         db_vals[39].type = DB1_STR;
1669         db_vals[39].nul = 0;
1670         db_vals[39].val.str_val = sco->diversion;
1671
1672         db_keys[40] = &msg_column;
1673         db_vals[40].type = DB1_BLOB;
1674         db_vals[40].nul = 0;
1675
1676         /*we don't have empty spaces now */
1677         tmp.s = sco->msg.s;
1678         tmp.len = sco->msg.len;
1679
1680         db_vals[40].val.blob_val = tmp;
1681
1682         db_keys[41] = &custom_field1_column;
1683         db_vals[41].type = DB1_STR;
1684         db_vals[41].nul = 0;
1685         db_vals[41].val.str_val = sco->custom1;
1686
1687         db_keys[42] = &custom_field2_column;
1688         db_vals[42].type = DB1_STR;
1689         db_vals[42].nul = 0;
1690         db_vals[42].val.str_val = sco->custom2;
1691
1692         db_keys[43] = &custom_field3_column;
1693         db_vals[43].type = DB1_STR;
1694         db_vals[43].nul = 0;
1695         db_vals[43].val.str_val = sco->custom3;
1696
1697         if(dtable) {
1698                 table = dtable;
1699         } else if(c->no_tables > 0) {
1700
1701                 if(c->mtmode == mode_hash) {
1702                         ii = hash_func(sco, c->hash_source, c->no_tables);
1703                         if(ii < 0) {
1704                                 LM_ERR("hashing failed\n");
1705                                 return -1;
1706                         }
1707                         LM_DBG("hash idx is:%d\n", ii);
1708                 } else if(c->mtmode == mode_random) {
1709                         ii = kam_rand() % c->no_tables;
1710                         LM_DBG("rand idx is:%d\n", ii);
1711                 } else if(c->mtmode == mode_round_robin) {
1712                         ii = c->rr_idx;
1713                         c->rr_idx = (c->rr_idx + 1) % c->no_tables;
1714                         LM_DBG("round robin idx is:%d\n", ii);
1715                 }
1716                 table = &c->table_names[ii];
1717         } else {
1718                 table = &table_name;
1719         }
1720
1721         tvsec_ = (time_t)(sco->tmstamp / 1000000);
1722         if(gmtime_r(&tvsec_, &capt_ts) == NULL) {
1723                 LM_ERR("unable to set time to attributes\n");
1724                 return -1;
1725         }
1726
1727         ntab.len = strftime(strftime_buf, sizeof(strftime_buf), table->s, &capt_ts);
1728         ntab.s = strftime_buf;
1729
1730         table = &ntab;
1731
1732         /* check dynamic table */
1733         LM_DBG("insert into homer table [1]: [%.*s]\n", table->len, table->s);
1734         c->db_funcs.use_table(c->db_con, table);
1735
1736         LM_DBG("storing info...\n");
1737
1738         if(db_insert_mode == 1 && c->db_funcs.insert_delayed != NULL)
1739                 insert = c->db_funcs.insert_delayed;
1740         else if(db_insert_mode == 2 && c->db_funcs.insert_async != NULL)
1741                 insert = c->db_funcs.insert_async;
1742         else
1743                 insert = c->db_funcs.insert;
1744         ret = insert(c->db_con, db_keys, db_vals, NR_KEYS);
1745
1746         if(ret < 0) {
1747                 LM_DBG("failed to insert into database(first attempt)\n");
1748                 if(insert_retries != 0) {
1749                         counter = 0;
1750                         while((ret = insert(c->db_con, db_keys, db_vals, NR_KEYS)) < 0) {
1751                                 counter++;
1752                                 if(1 == counter) //first failed retry
1753                                         retry_failed_time = time(NULL);
1754
1755                                 if((counter > insert_retries)
1756                                                 || (time(NULL) - retry_failed_time
1757                                                         > insert_retry_timeout)) {
1758                                         LM_ERR("failed to insert into database(second attempt)\n");
1759                                         break;
1760                                 }
1761                         }
1762                 }
1763         }
1764         if(ret < 0)
1765                 goto error;
1766 #ifdef STATISTICS
1767         update_stat(sco->stat, 1);
1768 #endif
1769
1770         return 1;
1771 error:
1772         return -1;
1773 }
1774
1775 static int sip_capture(sip_msg_t *msg, str *_table,
1776                 _capture_mode_data_t *cm_data)
1777 {
1778         struct _sipcapture_object sco;
1779         struct sip_uri from, to, contact;
1780         struct hdr_field *hook1 = NULL;
1781         hdr_field_t *tmphdr[7];
1782         contact_body_t *cb = 0;
1783         char buf_ip[IP_ADDR_MAX_STR_SIZE + 12];
1784         char *port_str = NULL, *tmp = NULL;
1785         struct timeval tvb;
1786         struct timezone tz;
1787         char tmp_node[100];
1788
1789         LM_DBG("CAPTURE DEBUG...\n");
1790
1791         gettimeofday(&tvb, &tz);
1792
1793         if(msg == NULL) {
1794                 LM_DBG("nothing to capture\n");
1795                 return -1;
1796         }
1797         memset(&sco, 0, sizeof(struct _sipcapture_object));
1798
1799
1800         if(capture_on_flag == NULL || *capture_on_flag == 0) {
1801                 LM_DBG("capture off...\n");
1802                 return -1;
1803         }
1804
1805         if(sip_capture_prepare(msg) < 0)
1806                 return -1;
1807
1808         if(msg->first_line.type == SIP_REQUEST) {
1809
1810                 if(parse_sip_msg_uri(msg) < 0)
1811                         return -1;
1812
1813                 sco.method = msg->first_line.u.request.method;
1814                 EMPTY_STR(sco.reply_reason);
1815
1816                 sco.ruri = msg->first_line.u.request.uri;
1817                 sco.ruri_user = msg->parsed_uri.user;
1818                 sco.ruri_domain = msg->parsed_uri.host;
1819         } else if(msg->first_line.type == SIP_REPLY) {
1820                 sco.method = msg->first_line.u.reply.status;
1821                 sco.reply_reason = msg->first_line.u.reply.reason;
1822
1823                 EMPTY_STR(sco.ruri);
1824                 EMPTY_STR(sco.ruri_user);
1825                 EMPTY_STR(sco.ruri_domain);
1826         } else {
1827                 LM_ERR("unknown type [%i]\n", msg->first_line.type);
1828                 EMPTY_STR(sco.method);
1829                 EMPTY_STR(sco.reply_reason);
1830                 EMPTY_STR(sco.ruri);
1831                 EMPTY_STR(sco.ruri_user);
1832         }
1833
1834         if(heptime && heptime->tv_sec != 0) {
1835                 sco.tmstamp = (unsigned long long)heptime->tv_sec * 1000000
1836                         + heptime->tv_usec; /* micro ts */
1837                 snprintf(tmp_node, 100, "%.*s:%lu", capture_node.len, capture_node.s,
1838                                 (unsigned long)heptime->captid);
1839                 sco.node.s = tmp_node;
1840                 sco.node.len = strlen(tmp_node);
1841         } else {
1842                 sco.tmstamp = (unsigned long long)tvb.tv_sec * 1000000
1843                         + tvb.tv_usec; /* micro ts */
1844                 sco.node = capture_node;
1845         }
1846
1847         /* Parse FROM */
1848         if(msg->from) {
1849
1850                 if(parse_from_header(msg) != 0) {
1851                         LOG(L_ERR, "ERROR: eval_elem: bad or missing"
1852                                         " From: header\n");
1853                         return -1;
1854                 }
1855
1856                 if(parse_uri(get_from(msg)->uri.s, get_from(msg)->uri.len, &from) < 0) {
1857                         LOG(L_ERR, "ERROR: do_action: bad from dropping"
1858                                         " packet\n");
1859                         return -1;
1860                 }
1861
1862                 sco.from_user = from.user;
1863                 sco.from_domain = from.host;
1864                 sco.from_tag = get_from(msg)->tag_value;
1865         } else {
1866                 EMPTY_STR(sco.from_user);
1867                 EMPTY_STR(sco.from_domain);
1868                 EMPTY_STR(sco.from_tag);
1869         }
1870
1871         /* Parse TO */
1872         if(msg->to) {
1873
1874                 if(parse_uri(get_to(msg)->uri.s, get_to(msg)->uri.len, &to) < 0) {
1875                         LOG(L_ERR, "ERROR: do_action: bad to dropping"
1876                                         " packet\n");
1877                         return -1;
1878                 }
1879
1880                 sco.to_user = to.user;
1881                 sco.to_domain = to.host;
1882                 if(get_to(msg)->tag_value.len)
1883                         sco.to_tag = get_to(msg)->tag_value;
1884                 else {
1885                         EMPTY_STR(sco.to_tag);
1886                 }
1887         } else {
1888                 EMPTY_STR(sco.to_user);
1889                 EMPTY_STR(sco.to_domain);
1890                 EMPTY_STR(sco.to_tag);
1891         }
1892
1893         /* Call-id */
1894         if(msg->callid)
1895                 sco.callid = msg->callid->body;
1896         else {
1897                 EMPTY_STR(sco.callid);
1898         }
1899
1900         /* P-Asserted-Id */
1901         if((parse_pai_header(msg) == 0) && (msg->pai) && (msg->pai->parsed)) {
1902                 to_body_t *pai = get_pai(msg)->id; /* This returns the first entry */
1903                 if((pai->parsed_uri.user.s == NULL)
1904                                 && (parse_uri(pai->uri.s, pai->uri.len, &pai->parsed_uri)
1905                                         < 0)) {
1906                         LM_DBG("DEBUG: do_action: bad pai: method:[%.*s] CID: [%.*s]\n",
1907                                         sco.method.len, sco.method.s, sco.callid.len, sco.callid.s);
1908                 } else {
1909                         LM_DBG("PARSE PAI: (%.*s)\n", pai->uri.len, pai->uri.s);
1910                         sco.pid_user = pai->parsed_uri.user;
1911                 }
1912         } else if((parse_ppi_header(msg) == 0) && (msg->ppi)
1913                         && (msg->ppi->parsed)) {
1914                 to_body_t *ppi = get_ppi(msg)->id; /* This returns the first entry */
1915                 if((ppi->parsed_uri.user.s == NULL)
1916                                 && (parse_uri(ppi->uri.s, ppi->uri.len, &ppi->parsed_uri)
1917                                         < 0)) {
1918                         LM_DBG("DEBUG: do_action: bad ppi: method:[%.*s] CID: [%.*s]\n",
1919                                         sco.method.len, sco.method.s, sco.callid.len, sco.callid.s);
1920                 } else {
1921                         LM_DBG("PARSE PPI: (%.*s)\n", ppi->uri.len, ppi->uri.s);
1922                         sco.pid_user = ppi->parsed_uri.user;
1923                 }
1924         } else {
1925                 EMPTY_STR(sco.pid_user);
1926         }
1927
1928         /* Auth headers */
1929         if(msg->proxy_auth != NULL)
1930                 hook1 = msg->proxy_auth;
1931         else if(msg->authorization != NULL)
1932                 hook1 = msg->authorization;
1933
1934         if(hook1) {
1935                 if(parse_credentials(hook1) == 0)
1936                         sco.auth_user =
1937                                 ((auth_body_t *)(hook1->parsed))->digest.username.user;
1938                 else {
1939                         EMPTY_STR(sco.auth_user);
1940                 }
1941         } else {
1942                 EMPTY_STR(sco.auth_user);
1943         }
1944
1945         if(msg->contact) {
1946
1947                 if(msg->contact->parsed == 0 && parse_contact(msg->contact) == -1) {
1948                         LOG(L_ERR, "assemble_msg: error while parsing <Contact:> header\n");
1949                         return -1;
1950                 }
1951
1952                 cb = (contact_body_t *)msg->contact->parsed;
1953
1954                 if(cb) {
1955                         if(cb->contacts) {
1956                                 if(parse_uri(
1957                                                         cb->contacts->uri.s, cb->contacts->uri.len, &contact)
1958                                                 < 0) {
1959                                         LOG(L_ERR, "ERROR: do_action: bad contact dropping"
1960                                                         " packet\n");
1961                                         return -1;
1962                                 }
1963                         } else {
1964                                 if(cb->star) { /* in the case Contact is "*" */
1965                                         memset(&contact, 0, sizeof(contact));
1966                                         contact.user.s = star_contact.s;
1967                                         contact.user.len = star_contact.len;
1968                                 } else {
1969                                         LOG(L_NOTICE, "Invalid contact\n");
1970                                         memset(&contact, 0, sizeof(contact));
1971                                 }
1972                         }
1973                 }
1974         }
1975
1976         /* callid_aleg - default is X-CID but configurable via modul params */
1977         EMPTY_STR(sco.callid_aleg);
1978         int index;
1979         for(index = 0; index < n_callid_aleg_headers; index++) {
1980                 if((tmphdr[0] = get_hdr_by_name(msg, callid_aleg_headers[index].s,
1981                                                 callid_aleg_headers[index].len))
1982                                 != NULL) {
1983                         LM_DBG("MATCHED header %.*s\n", callid_aleg_headers[index].len,
1984                                         callid_aleg_headers[index].s);
1985                         sco.callid_aleg = tmphdr[0]->body;
1986                         break;
1987                 }
1988         }
1989
1990         /* VIA 1 */
1991         sco.via_1 = msg->h_via1->body;
1992
1993         /* Via branch */
1994         if(msg->via1->branch)
1995                 sco.via_1_branch = msg->via1->branch->value;
1996         else {
1997                 EMPTY_STR(sco.via_1_branch);
1998         }
1999
2000         /* CSEQ */
2001         if(msg->cseq)
2002                 sco.cseq = msg->cseq->body;
2003         else {
2004                 EMPTY_STR(sco.cseq);
2005         }
2006
2007         /* Reason */
2008         if((tmphdr[1] = get_hdr_by_name(msg, "Reason", 6)) != NULL) {
2009                 sco.reason = tmphdr[1]->body;
2010         } else {
2011                 EMPTY_STR(sco.reason);
2012         }
2013
2014         /* Diversion */
2015         if(msg->diversion)
2016                 sco.diversion = msg->diversion->body;
2017         else {
2018                 EMPTY_STR(sco.diversion);
2019         }
2020
2021         /* Content-type */
2022         if(msg->content_type)
2023                 sco.content_type = msg->content_type->body;
2024         else {
2025                 EMPTY_STR(sco.content_type);
2026         }
2027
2028         /* User-Agent */
2029         if(msg->user_agent)
2030                 sco.user_agent = msg->user_agent->body;
2031         else {
2032                 EMPTY_STR(sco.user_agent);
2033         }
2034
2035         /* Contact */
2036         if(msg->contact && cb) {
2037                 sco.contact_ip = contact.host;
2038                 str2int(&contact.port, (unsigned int *)&sco.contact_port);
2039                 sco.contact_user = contact.user;
2040         } else {
2041                 EMPTY_STR(sco.contact_ip);
2042                 sco.contact_port = 0;
2043                 EMPTY_STR(sco.contact_user);
2044         }
2045
2046         /* X-OIP */
2047         if((tmphdr[2] = get_hdr_by_name(msg, "X-OIP", 5)) != NULL) {
2048                 sco.originator_ip = tmphdr[2]->body;
2049                 /* Originator port. Should be parsed from XOIP header as ":" param */
2050                 tmp = strchr(tmphdr[2]->body.s, ':');
2051                 if(tmp) {
2052                         *tmp = '\0';
2053                         port_str = tmp + 1;
2054                         sco.originator_port = strtol(port_str, NULL, 10);
2055                 } else
2056                         sco.originator_port = 0;
2057         } else {
2058                 EMPTY_STR(sco.originator_ip);
2059                 sco.originator_port = 0;
2060         }
2061
2062         /* X-RTP-Stat-Add */
2063         if((tmphdr[3] = get_hdr_by_name(msg, "X-RTP-Stat-Add", 14)) != NULL) {
2064                 sco.rtp_stat = tmphdr[3]->body;
2065         }
2066         /* X-RTP-Stat-T38 */
2067         else if((tmphdr[3] = get_hdr_by_name(msg, "X-RTP-Stat-T38", 14)) != NULL) {
2068                 sco.rtp_stat = tmphdr[3]->body;
2069         }
2070         /* X-RTP-Stat */
2071         else if((tmphdr[3] = get_hdr_by_name(msg, "X-RTP-Stat", 10)) != NULL) {
2072                 sco.rtp_stat = tmphdr[3]->body;
2073         }
2074         /* P-RTP-Stat */
2075         else if((tmphdr[3] = get_hdr_by_name(msg, "P-RTP-Stat", 10)) != NULL) {
2076                 sco.rtp_stat = tmphdr[3]->body;
2077         }
2078         /* X-Siemens-RTP-stats */
2079         else if((tmphdr[3] = get_hdr_by_name(msg, "X-Siemens-RTP-stats", 19))
2080                         != NULL) {
2081                 sco.rtp_stat = tmphdr[3]->body;
2082         }
2083         /* X-NG-RTP-STATS */
2084         else if((tmphdr[3] = get_hdr_by_name(msg, "X-NG-RTP-STATS", 14)) != NULL) {
2085                 sco.rtp_stat = tmphdr[3]->body;
2086         }
2087         /* RTP-RxStat */
2088         else if((tmphdr[3] = get_hdr_by_name(msg, "RTP-RxStat", 10)) != NULL) {
2089                 sco.rtp_stat = tmphdr[3]->body;
2090         } else {
2091                 EMPTY_STR(sco.rtp_stat);
2092         }
2093
2094         /* Custom - field1 */
2095         if(custom_field1_header.len > 0
2096                         && (tmphdr[4] = get_hdr_by_name(
2097                                         msg, custom_field1_header.s, custom_field1_header.len))
2098                         != NULL) {
2099                 sco.custom1 = tmphdr[4]->body;
2100         } else {
2101                 EMPTY_STR(sco.custom1);
2102         }
2103
2104         /* Custom - field2 */
2105         if(custom_field2_header.len > 0
2106                         && (tmphdr[5] = get_hdr_by_name(
2107                                         msg, custom_field2_header.s, custom_field2_header.len))
2108                         != NULL) {
2109                 sco.custom2 = tmphdr[5]->body;
2110         } else {
2111                 EMPTY_STR(sco.custom2);
2112         }
2113
2114         /* Custom - field3 */
2115         if(custom_field3_header.len > 0
2116                         && (tmphdr[6] = get_hdr_by_name(
2117                                         msg, custom_field3_header.s, custom_field3_header.len))
2118                         != NULL) {
2119                 sco.custom3 = tmphdr[6]->body;
2120         } else {
2121                 EMPTY_STR(sco.custom3);
2122         }
2123
2124         /* PROTO TYPE */
2125         sco.proto = msg->rcv.proto;
2126
2127         /* FAMILY TYPE */
2128         sco.family = msg->rcv.src_ip.af;
2129
2130         /* MESSAGE TYPE */
2131         sco.type = msg->first_line.type;
2132
2133         /* MSG */
2134         sco.msg.s = msg->buf;
2135         sco.msg.len = msg->len;
2136         //EMPTY_STR(sco.msg);
2137
2138         /* IP source and destination */
2139
2140         strcpy(buf_ip, ip_addr2a(&msg->rcv.src_ip));
2141         sco.source_ip.s = buf_ip;
2142         sco.source_ip.len = strlen(buf_ip);
2143         sco.source_port = msg->rcv.src_port;
2144
2145         /*source ip*/
2146         sco.destination_ip.s = ip_addr2a(&msg->rcv.dst_ip);
2147         sco.destination_ip.len = strlen(sco.destination_ip.s);
2148         sco.destination_port = msg->rcv.dst_port;
2149
2150
2151         LM_DBG("src_ip: [%.*s]\n", sco.source_ip.len, sco.source_ip.s);
2152         LM_DBG("dst_ip: [%.*s]\n", sco.destination_ip.len, sco.destination_ip.s);
2153
2154         LM_DBG("dst_port: [%d]\n", sco.destination_port);
2155         LM_DBG("src_port: [%d]\n", sco.source_port);
2156
2157 #ifdef STATISTICS
2158         if(msg->first_line.type == SIP_REPLY) {
2159                 sco.stat = (cm_data) ? cm_data->sipcapture_rpl
2160                         : capture_def->sipcapture_rpl;
2161         } else {
2162                 sco.stat = (cm_data) ? cm_data->sipcapture_req
2163                         : capture_def->sipcapture_req;
2164         }
2165 #endif
2166         //LM_DBG("DONE");
2167         return sip_capture_store(&sco, _table, cm_data);
2168 }
2169
2170 #define capture_is_off(_msg) (capture_on_flag == NULL || *capture_on_flag == 0)
2171
2172
2173 /* Local raw socket */
2174 int raw_capture_socket(
2175                 struct ip_addr *ip, str *iface, int port_start, int port_end, int proto)
2176 {
2177
2178         int sock = -1;
2179         union sockaddr_union su;
2180
2181 #ifdef __OS_linux
2182         struct sock_fprog pf;
2183         char short_ifname[sizeof(int)];
2184         int ifname_len;
2185         char *ifname;
2186 #endif
2187         //0x0003 - all packets
2188         if(proto == IPPROTO_IPIP) {
2189                 sock = socket(PF_INET, SOCK_RAW, proto);
2190         }
2191 #ifdef __OS_linux
2192         else if(proto == htons(0x800)) {
2193                 sock = socket(PF_PACKET, SOCK_RAW, proto);
2194         }
2195 #endif
2196         else {
2197                 ERR("raw_capture_socket: LSF currently supported only on linux\n");
2198                 goto error;
2199         }
2200
2201         if(sock == -1)
2202                 goto error;
2203
2204 #ifdef __OS_linux
2205
2206         /* set socket options */
2207         if(iface && iface->s) {
2208
2209                 /* workaround for linux bug: arg to setsockopt must have at least
2210                  * sizeof(int) size or EINVAL would be returned */
2211                 if(iface->len < sizeof(int)) {
2212                         memcpy(short_ifname, iface->s, iface->len);
2213                         short_ifname[iface->len] = 0; /* make sure it's zero term */
2214                         ifname_len = sizeof(short_ifname);
2215                         ifname = short_ifname;
2216                 } else {
2217                         ifname_len = iface->len;
2218                         ifname = iface->s;
2219                 }
2220                 if(setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE, ifname, ifname_len)
2221                                 < 0) {
2222                         ERR("raw_socket: could not bind to %.*s: %s [%d]\n", iface->len,
2223                                         ZSW(iface->s), strerror(errno), errno);
2224                         goto error;
2225                 }
2226         }
2227
2228         if(bpf_on) {
2229
2230                 memset(&pf, 0, sizeof(pf));
2231                 pf.len = sizeof(BPF_code) / sizeof(BPF_code[0]);
2232                 pf.filter = (struct sock_filter *)BPF_code;
2233
2234                 if(!port_end)
2235                         port_end = port_start;
2236
2237                 /* Start PORT */
2238                 BPF_code[5] = (struct sock_filter)BPF_JUMP(0x35, port_start, 0, 1);
2239                 BPF_code[8] = (struct sock_filter)BPF_JUMP(0x35, port_start, 11, 13);
2240                 BPF_code[16] = (struct sock_filter)BPF_JUMP(0x35, port_start, 0, 1);
2241                 BPF_code[19] = (struct sock_filter)BPF_JUMP(0x35, port_start, 0, 2);
2242                 /* Stop PORT */
2243                 BPF_code[6] = (struct sock_filter)BPF_JUMP(0x25, port_end, 0, 14);
2244                 BPF_code[17] = (struct sock_filter)BPF_JUMP(0x25, port_end, 0, 3);
2245                 BPF_code[20] = (struct sock_filter)BPF_JUMP(0x25, port_end, 1, 0);
2246
2247                 /* Attach the filter to the socket */
2248                 if(setsockopt(sock, SOL_SOCKET, SO_ATTACH_FILTER, &pf, sizeof(pf))
2249                                 < 0) {
2250                         ERR(" setsockopt filter: [%s] [%d]\n", strerror(errno), errno);
2251                 }
2252         }
2253 #endif
2254
2255         if(ip && proto == IPPROTO_IPIP) {
2256                 init_su(&su, ip, 0);
2257                 if(bind(sock, &su.s, sockaddru_len(su)) == -1) {
2258                         ERR("raw_capture_socket: bind(%s) failed: %s [%d]\n", ip_addr2a(ip),
2259                                         strerror(errno), errno);
2260                         goto error;
2261                 }
2262         }
2263
2264         return sock;
2265
2266 error:
2267         if(sock != -1)
2268                 close(sock);
2269         return -1;
2270 }
2271
2272 /* Local raw receive loop */
2273 int raw_capture_rcv_loop(int rsock, int port1, int port2, int ipip)
2274 {
2275
2276
2277         static char buf[BUF_SIZE + 1];
2278         union sockaddr_union from;
2279         union sockaddr_union to;
2280         struct receive_info ri;
2281         int len;
2282         struct ip *iph;
2283         struct udphdr *udph;
2284         char *udph_start;
2285         unsigned short udp_len;
2286         int offset = 0;
2287         char *end;
2288         unsigned short dst_port;
2289         unsigned short src_port;
2290         struct ip_addr dst_ip, src_ip;
2291         struct socket_info *si = 0;
2292         int tmp_len;
2293
2294
2295         for(;;) {
2296
2297                 len = recvfrom(rsock, buf, BUF_SIZE, 0x20, 0, 0);
2298
2299                 if(len < 0) {
2300                         if(len == -1) {
2301                                 LOG(L_ERR, "ERROR: raw_moni_rcv_loop:recvfrom: %s [%d]\n",
2302                                                 strerror(errno), errno);
2303                                 if((errno == EINTR) || (errno == EWOULDBLOCK))
2304                                         continue;
2305                         } else {
2306                                 DBG("raw_moni_rcv_loop: recvfrom error: %d\n", len);
2307                                 continue;
2308                         }
2309                 }
2310
2311                 end = buf + len;
2312
2313                 offset = ipip ? sizeof(struct ip) : ETHHDR;
2314
2315                 if(unlikely(len
2316                                         < (sizeof(struct ip) + sizeof(struct udphdr) + offset))) {
2317                         DBG("received small packet: %d. Ignore it\n", len);
2318                         continue;
2319                 }
2320
2321                 iph = (struct ip *)(buf + offset);
2322
2323                 offset += iph->ip_hl * 4;
2324
2325                 udph_start = buf + offset;
2326
2327                 udph = (struct udphdr *)udph_start;
2328                 offset += sizeof(struct udphdr);
2329
2330                 if(unlikely((buf + offset) > end)) {
2331                         continue;
2332                 }
2333
2334                 udp_len = ntohs(udph->uh_ulen);
2335                 if(unlikely((udph_start + udp_len) != end)) {
2336                         if((udph_start + udp_len) > end) {
2337                                 continue;
2338                         } else {
2339                                 DBG("udp length too small: %d/%d\n", (int)udp_len,
2340                                                 (int)(end - udph_start));
2341                                 continue;
2342                         }
2343                 }
2344
2345                 /* cut off the offset */
2346                 len -= offset;
2347
2348                 if(len < MIN_UDP_PACKET) {
2349                         DBG("raw_udp4_rcv_loop: probing packet received from\n");
2350                         continue;
2351                 }
2352
2353                 /* fill dst_port && src_port */
2354                 dst_port = ntohs(udph->uh_dport);
2355                 src_port = ntohs(udph->uh_sport);
2356
2357                 /* if the message has not alpha */
2358                 if(!isalnum((buf + offset)[0])) {
2359                         DBG("not alpha and not digit... skipping...\n");
2360                         continue;
2361                 }
2362
2363
2364                 DBG("PORT: [%d] and [%d]\n", port1, port2);
2365
2366                 if((!port1 && !port2) || (src_port >= port1 && src_port <= port2)
2367                                 || (dst_port >= port1 && dst_port <= port2)
2368                                 || (!port2 && (src_port == port1 || dst_port == port1))) {
2369
2370                         /*FIL IPs*/
2371                         dst_ip.af = AF_INET;
2372                         dst_ip.len = 4;
2373                         dst_ip.u.addr32[0] = iph->ip_dst.s_addr;
2374
2375                         /* fill dst_port */
2376                         ip_addr2su(&to, &dst_ip, dst_port);
2377
2378                         /* fill src_port */
2379                         src_ip.af = AF_INET;
2380                         src_ip.len = 4;
2381                         src_ip.u.addr32[0] = iph->ip_src.s_addr;
2382                         ip_addr2su(&from, &src_ip, src_port);
2383                         su_setport(&from, src_port);
2384
2385                         ri.src_su = from;
2386                         su2ip_addr(&ri.src_ip, &from);
2387                         ri.src_port = src_port;
2388                         su2ip_addr(&ri.dst_ip, &to);
2389                         ri.dst_port = dst_port;
2390                         ri.proto = PROTO_UDP;
2391
2392                         /* a little bit memory */
2393                         si = (struct socket_info *)pkg_malloc(sizeof(struct socket_info));
2394                         if(si == 0) {
2395                                 LOG(L_ERR, "ERROR: new_sock_info: memory allocation error\n");
2396                                 return 0;
2397                         }
2398
2399                         memset(si, 0, sizeof(struct socket_info));
2400                         si->address = ri.dst_ip;
2401                         si->socket = -1;
2402
2403                         /* set port & proto */
2404                         si->port_no = dst_port;
2405                         si->proto = PROTO_UDP;
2406                         si->flags = 0;
2407                         si->addr_info_lst = 0;
2408
2409                         si->port_no_str.s = int2str(si->port_no, &tmp_len);
2410                         si->port_no_str.len = tmp_len;
2411
2412                         si->address_str.s = ip_addr2a(&si->address);
2413                         ;
2414                         si->address_str.len = strlen(si->address_str.s);
2415
2416                         si->name.len = si->address_str.len;
2417                         si->name.s = si->address_str.s;
2418
2419                         ri.bind_address = si;
2420
2421
2422                         /* and now recieve message */
2423                         receive_msg(buf + offset, len, &ri);
2424                         if(si)
2425                                 pkg_free(si);
2426                 }
2427         }
2428
2429         return 0;
2430 }
2431
2432 static void sipcapture_rpc_status(rpc_t *rpc, void *c)
2433 {
2434         str status = {0, 0};
2435
2436         if(rpc->scan(c, "S", &status) < 1) {
2437                 rpc->fault(c, 500, "Not enough parameters (on, off or check)");
2438                 return;
2439         }
2440
2441         if(capture_on_flag == NULL) {
2442                 rpc->fault(c, 500, "Internal error");
2443                 return;
2444         }
2445
2446         if(strncasecmp(status.s, "on", strlen("on")) == 0) {
2447                 *capture_on_flag = 1;
2448                 rpc->rpl_printf(c, "Enabled");
2449                 return;
2450         }
2451         if(strncasecmp(status.s, "off", strlen("off")) == 0) {
2452                 *capture_on_flag = 0;
2453                 rpc->rpl_printf(c, "Disabled");
2454                 return;
2455         }
2456         if(strncasecmp(status.s, "check", strlen("check")) == 0) {
2457                 rpc->rpl_printf(c, *capture_on_flag ? "Enabled" : "Disabled");
2458                 return;
2459         }
2460         rpc->fault(c, 500, "Bad parameter (on, off or check)");
2461         return;
2462 }
2463
2464 static const char *sipcapture_status_doc[2] = {
2465         "Get status or turn on/off sipcapture.", 0};
2466
2467 rpc_export_t sipcapture_rpc[] = {
2468         {"sipcapture.status", sipcapture_rpc_status, sipcapture_status_doc, 0},
2469         {0, 0, 0, 0}
2470 };
2471
2472 static int sipcapture_init_rpc(void)
2473 {
2474         if(rpc_register_array(sipcapture_rpc) != 0) {
2475                 LM_ERR("failed to register RPC commands\n");
2476                 return -1;
2477         }
2478         return 0;
2479 }
2480
2481
2482 /* for rtcp and logging */
2483 int receive_logging_json_msg(char *buf, unsigned int len,
2484                 struct hep_generic_recv *hg, char *log_table)
2485 {
2486
2487
2488         db_key_t db_keys[RTCP_NR_KEYS];
2489         db_val_t db_vals[RTCP_NR_KEYS];
2490         struct _sipcapture_object sco;
2491         char ipstr_dst[INET6_ADDRSTRLEN], ipstr_src[INET6_ADDRSTRLEN];
2492         char tmp_node[100];
2493         struct timeval tvb;
2494         struct timezone tz;
2495         time_t epoch_time_as_time_t;
2496
2497         str tmp, corrtmp, table;
2498         _capture_mode_data_t *c = NULL;
2499
2500         c = capture_def;
2501         if(!c) {
2502                 LM_ERR("no connection mode available to store data\n");
2503                 return -1;
2504         }
2505
2506         if(!correlation_id || strlen(correlation_id) == 0) {
2507                 LM_ERR("no correlation id defined\n");
2508                 return -1;
2509         }
2510
2511         memset(&sco, 0, sizeof(struct _sipcapture_object));
2512         gettimeofday(&tvb, &tz);
2513
2514         /* PROTO TYPE */
2515         if(hg->ip_proto->data == IPPROTO_TCP)
2516                 sco.proto = PROTO_TCP;
2517         else if(hg->ip_proto->data == IPPROTO_UDP)
2518                 sco.proto = PROTO_UDP;
2519         /* FAMILY TYPE */
2520         sco.family = hg->ip_family->data;
2521
2522         /* IP source and destination */
2523
2524         if(hg->ip_family->data == AF_INET6) {
2525                 inet_ntop(AF_INET6, &(hg->hep_dst_ip6->data), ipstr_dst,
2526                                 INET6_ADDRSTRLEN);
2527                 inet_ntop(AF_INET6, &(hg->hep_src_ip6->data), ipstr_src,
2528                                 INET6_ADDRSTRLEN);
2529         } else if(hg->ip_family->data == AF_INET) {
2530                 inet_ntop(
2531                                 AF_INET, &(hg->hep_src_ip4->data), ipstr_src, INET_ADDRSTRLEN);
2532                 inet_ntop(
2533                                 AF_INET, &(hg->hep_dst_ip4->data), ipstr_dst, INET_ADDRSTRLEN);
2534         }
2535
2536
2537         /* type of proto */
2538         if(hg->proto_t->data == 5)
2539                 sco.type = 3;
2540         else if(hg->proto_t->data == 32)
2541                 sco.type = 2;
2542         else if(hg->proto_t->data == 99)
2543                 sco.type = 4;
2544         else if(hg->proto_t->data == 100)
2545                 sco.type = 5;
2546
2547
2548         /*source ip*/
2549         sco.source_ip.s = ipstr_src;
2550         sco.source_ip.len = strlen(ipstr_src);
2551         sco.source_port = ntohs(hg->src_port->data);
2552
2553         sco.destination_ip.s = ipstr_dst;
2554         sco.destination_ip.len = strlen(ipstr_dst);
2555         sco.destination_port = ntohs(hg->dst_port->data);
2556
2557         if(heptime && heptime->tv_sec != 0) {
2558                 sco.tmstamp = (unsigned long long)heptime->tv_sec * 1000000
2559                         + heptime->tv_usec; /* micro ts */
2560                 snprintf(tmp_node, 100, "%.*s:%lu", capture_node.len, capture_node.s,
2561                                 (unsigned long)heptime->captid);
2562                 sco.node.s = tmp_node;
2563                 sco.node.len = strlen(tmp_node);
2564                 epoch_time_as_time_t = heptime->tv_sec;
2565                 ;
2566         } else {
2567                 sco.tmstamp = (unsigned long long)tvb.tv_sec * 1000000
2568                         + tvb.tv_usec; /* micro ts */
2569                 sco.node = capture_node;
2570                 epoch_time_as_time_t = tvb.tv_sec;
2571         }
2572
2573         if(correlation_id) {
2574                 corrtmp.s = correlation_id;
2575                 corrtmp.len = strlen(correlation_id);
2576         }
2577
2578         db_keys[0] = &date_column;
2579         db_vals[0].type = DB1_DATETIME;
2580         db_vals[0].nul = 0;
2581         db_vals[0].val.time_val = epoch_time_as_time_t;
2582
2583         db_keys[1] = &micro_ts_column;
2584         db_vals[1].type = DB1_BIGINT;
2585         db_vals[1].nul = 0;
2586         db_vals[1].val.ll_val = sco.tmstamp;
2587
2588         db_keys[2] = &correlation_column;
2589         db_vals[2].type = DB1_STR;
2590         db_vals[2].nul = 0;
2591         db_vals[2].val.str_val = corrtmp;
2592
2593         db_keys[3] = &source_ip_column;
2594         db_vals[3].type = DB1_STR;
2595         db_vals[3].nul = 0;
2596         db_vals[3].val.str_val = sco.source_ip;
2597
2598         db_keys[4] = &source_port_column;
2599         db_vals[4].type = DB1_INT;
2600         db_vals[4].nul = 0;
2601         db_vals[4].val.int_val = sco.source_port;
2602
2603         db_keys[5] = &dest_ip_column;
2604         db_vals[5].type = DB1_STR;
2605         db_vals[5].nul = 0;
2606         db_vals[5].val.str_val = sco.destination_ip;
2607
2608         db_keys[6] = &dest_port_column;
2609         db_vals[6].type = DB1_INT;
2610         db_vals[6].nul = 0;
2611         db_vals[6].val.int_val = sco.destination_port;
2612
2613         db_keys[7] = &proto_column;
2614         db_vals[7].type = DB1_INT;
2615         db_vals[7].nul = 0;
2616         db_vals[7].val.int_val = sco.proto;
2617
2618         db_keys[8] = &family_column;
2619         db_vals[8].type = DB1_INT;
2620         db_vals[8].nul = 0;
2621         db_vals[8].val.int_val = sco.family;
2622
2623         db_keys[9] = &type_column;
2624         db_vals[9].type = DB1_INT;
2625         db_vals[9].nul = 0;
2626         db_vals[9].val.int_val = sco.type;
2627
2628         db_keys[10] = &node_column;
2629         db_vals[10].type = DB1_STR;
2630         db_vals[10].nul = 0;
2631         db_vals[10].val.str_val = sco.node;
2632
2633         db_keys[11] = &msg_column;
2634         db_vals[11].type = DB1_BLOB;
2635         db_vals[11].nul = 0;
2636
2637         tmp.s = buf;
2638         tmp.len = len;
2639
2640         db_vals[11].val.blob_val = tmp;
2641
2642         table.s = log_table;
2643         table.len = strlen(log_table);
2644
2645         c->db_funcs.use_table(c->db_con, &table);
2646
2647         if(db_insert_mode == 1 && c->db_funcs.insert_delayed != NULL) {
2648                 if(c->db_funcs.insert_delayed(c->db_con, db_keys, db_vals, RTCP_NR_KEYS)
2649                                 < 0) {
2650                         LM_ERR("failed to insert delayed into database\n");
2651                         goto error;
2652                 }
2653         } else if(db_insert_mode == 2 && c->db_funcs.insert_async != NULL) {
2654                 if(c->db_funcs.insert_async(c->db_con, db_keys, db_vals, RTCP_NR_KEYS)
2655                                 < 0) {
2656                         LM_ERR("failed to insert async into database\n");
2657                         goto error;
2658                 }
2659         } else if(c->db_funcs.insert(c->db_con, db_keys, db_vals, RTCP_NR_KEYS)
2660                         < 0) {
2661                 LM_ERR("failed to insert into database\n");
2662                 goto error;
2663         }
2664
2665
2666         return 1;
2667 error:
2668         return -1;
2669 }
2670
2671 static int report_capture(sip_msg_t *msg, str *_table, str *_corr, str *_data)
2672 {
2673         struct _sipcapture_object sco;
2674         db_key_t db_keys[RTCP_NR_KEYS];
2675         db_val_t db_vals[RTCP_NR_KEYS];
2676         char buf_ip[IP_ADDR_MAX_STR_SIZE + 12];
2677         struct timeval tvb;
2678         struct timezone tz;
2679         char tmp_node[100];
2680         time_t epoch_time_as_time_t;
2681         str corrtmp = STR_NULL, tmp;
2682
2683
2684         _capture_mode_data_t *c = NULL;
2685         c = capture_def;
2686         if(!c) {
2687                 LM_ERR("no connection mode available to store data\n");
2688                 return -1;
2689         }
2690
2691
2692         LM_DBG("CAPTURE DEBUG...\n");
2693
2694         gettimeofday(&tvb, &tz);
2695
2696         if(msg == NULL) {
2697                 LM_DBG("nothing to capture\n");
2698                 return -1;
2699         }
2700         memset(&sco, 0, sizeof(struct _sipcapture_object));
2701
2702         if(capture_on_flag == NULL || *capture_on_flag == 0) {
2703                 LM_DBG("capture off...\n");
2704                 return -1;
2705         }
2706
2707         sco.proto = msg->rcv.proto;
2708
2709         /* FAMILY TYPE */
2710         sco.family = msg->rcv.src_ip.af;
2711
2712         /* MESSAGE TYPE */
2713         sco.type = msg->first_line.type;
2714
2715         /* MSG */
2716         sco.msg.s = msg->buf;
2717         sco.msg.len = msg->len;
2718         //EMPTY_STR(sco.msg);
2719
2720         /* IP source and destination */
2721
2722         strcpy(buf_ip, ip_addr2a(&msg->rcv.src_ip));
2723         sco.source_ip.s = buf_ip;
2724         sco.source_ip.len = strlen(buf_ip);
2725         sco.source_port = msg->rcv.src_port;
2726
2727         /*source ip*/
2728         sco.destination_ip.s = ip_addr2a(&msg->rcv.dst_ip);
2729         sco.destination_ip.len = strlen(sco.destination_ip.s);
2730         sco.destination_port = msg->rcv.dst_port;
2731
2732
2733         if(heptime && heptime->tv_sec != 0) {
2734                 sco.tmstamp = (unsigned long long)heptime->tv_sec * 1000000
2735                         + heptime->tv_usec; /* micro ts */
2736                 snprintf(tmp_node, 100, "%.*s:%lu", capture_node.len, capture_node.s,
2737                                 (unsigned long)heptime->captid);
2738                 sco.node.s = tmp_node;
2739                 sco.node.len = strlen(tmp_node);
2740                 epoch_time_as_time_t = heptime->tv_sec;
2741         } else {
2742                 sco.tmstamp = (unsigned long long)tvb.tv_sec * 1000000
2743                         + tvb.tv_usec; /* micro ts */
2744                 sco.node = capture_node;
2745                 epoch_time_as_time_t = tvb.tv_sec;
2746         }
2747
2748         if(_corr && _corr->len > 0) {
2749                 corrtmp.s = _corr->s;
2750                 corrtmp.len = _corr->len;
2751         } else if(correlation_id) {
2752                 corrtmp.s = correlation_id;
2753                 corrtmp.len = strlen(correlation_id);
2754         }
2755
2756         db_keys[0] = &date_column;
2757         db_vals[0].type = DB1_DATETIME;
2758         db_vals[0].nul = 0;
2759         db_vals[0].val.time_val = epoch_time_as_time_t;
2760
2761         db_keys[1] = &micro_ts_column;
2762         db_vals[1].type = DB1_BIGINT;
2763         db_vals[1].nul = 0;
2764         db_vals[1].val.ll_val = sco.tmstamp;
2765
2766         db_keys[2] = &correlation_column;
2767         db_vals[2].type = DB1_STR;
2768         db_vals[2].nul = 0;
2769         db_vals[2].val.str_val = corrtmp;
2770
2771         db_keys[3] = &source_ip_column;
2772         db_vals[3].type = DB1_STR;
2773         db_vals[3].nul = 0;
2774         db_vals[3].val.str_val = sco.source_ip;
2775
2776         db_keys[4] = &source_port_column;
2777         db_vals[4].type = DB1_INT;
2778         db_vals[4].nul = 0;
2779         db_vals[4].val.int_val = sco.source_port;
2780
2781         db_keys[5] = &dest_ip_column;
2782         db_vals[5].type = DB1_STR;
2783         db_vals[5].nul = 0;
2784         db_vals[5].val.str_val = sco.destination_ip;
2785
2786         db_keys[6] = &dest_port_column;
2787         db_vals[6].type = DB1_INT;
2788         db_vals[6].nul = 0;
2789         db_vals[6].val.int_val = sco.destination_port;
2790
2791         db_keys[7] = &proto_column;
2792         db_vals[7].type = DB1_INT;
2793         db_vals[7].nul = 0;
2794         db_vals[7].val.int_val = sco.proto;
2795
2796         db_keys[8] = &family_column;
2797         db_vals[8].type = DB1_INT;
2798         db_vals[8].nul = 0;
2799         db_vals[8].val.int_val = sco.family;
2800
2801         db_keys[9] = &type_column;
2802         db_vals[9].type = DB1_INT;
2803         db_vals[9].nul = 0;
2804         db_vals[9].val.int_val = sco.type;
2805
2806         db_keys[10] = &node_column;
2807         db_vals[10].type = DB1_STR;
2808         db_vals[10].nul = 0;
2809         db_vals[10].val.str_val = sco.node;
2810
2811         db_keys[11] = &msg_column;
2812         db_vals[11].type = DB1_BLOB;
2813         db_vals[11].nul = 0;
2814
2815         if(_data && _data->len > 0) {
2816                 tmp.s = _data->s;
2817                 tmp.len = _data->len;
2818         } else {
2819                 /* MSG */
2820                 tmp.s = msg->buf;
2821                 tmp.len = msg->len;
2822         }
2823
2824         db_vals[11].val.blob_val = tmp;
2825
2826         c->db_funcs.use_table(c->db_con, _table);
2827
2828         if(c->db_funcs.insert(c->db_con, db_keys, db_vals, RTCP_NR_KEYS) < 0) {
2829                 LM_ERR("failed to insert into database\n");
2830                 goto error;
2831         }
2832
2833         return 1;
2834
2835 error:
2836         return -1;
2837 }
2838
2839 // Algorithm optimized by coudot
2840 int parse_aleg_callid_headers(str *headers_str, str *headers)
2841 {
2842         if(headers_str->len == 0) {
2843                 return 0;
2844         }
2845
2846         int index = 0;
2847         int begin = 0;
2848         int current = 0;
2849
2850         while((index < headers_str->len) && (current < MAX_HEADERS)) {
2851                 // End of headers string
2852                 if((index == headers_str->len - 1) && (headers_str->s[index] != ';')) {
2853                         headers[current].s = headers_str->s + begin;
2854                         headers[current].len = index + 1 - begin;
2855                         current++;
2856                         break;
2857                 } else if(headers_str->s[index] == ';') {
2858                         // Skip empty header
2859                         if(begin == index) {
2860                                 begin++;
2861                         } else {
2862                                 // Another header identified
2863                                 headers[current].s = headers_str->s + begin;
2864                                 headers[current].len = index - begin;
2865                                 current++;
2866                                 begin = index + 1;
2867                         }
2868                 }
2869                 // Move to next char
2870                 index++;
2871         }
2872
2873         // current now holds the number of headers
2874         return current;
2875 }
2876
2877 static int sipcapture_parse_aleg_callid_headers()
2878 {
2879         int i;
2880         n_callid_aleg_headers =
2881                 parse_aleg_callid_headers(&callid_aleg_header, callid_aleg_headers);
2882         LM_DBG("Number of headers:%d\n", n_callid_aleg_headers);
2883
2884         for(i = 0; i < n_callid_aleg_headers; i++) {
2885                 LM_DBG("Header: %.*s\n", callid_aleg_headers[i].len,
2886                                 callid_aleg_headers[i].s);
2887         }
2888
2889         return n_callid_aleg_headers;
2890 }
2891
2892
2893 static int nosip_hep_msg(sr_event_param_t *evp)
2894 {
2895         sip_msg_t *msg;
2896         char *buf;
2897         int len = 0;
2898         struct run_act_ctx ra_ctx;
2899         int ret = 0;
2900         int rtb;
2901         sr_kemi_eng_t *keng = NULL;
2902         str evname = str_init("sipcapture:request");
2903         struct hep_hdr *heph;
2904
2905         msg = (sip_msg_t *)evp->data;
2906
2907         buf = msg->buf;
2908         len = msg->len;
2909
2910         rtb = get_route_type();
2911         set_route_type(EVENT_ROUTE);
2912         if(hep_route_no>=-1) {
2913                 /* first send to route */
2914                 init_run_actions_ctx(&ra_ctx);
2915                 ret = run_actions(&ra_ctx, event_rt.rlist[hep_route_no], msg);
2916
2917                 if(ret != 1) {
2918                         LM_DBG("return code from event route: %d - skipping\n", ret);
2919                         set_route_type(rtb);
2920                         return ret;
2921                 }
2922         } else {
2923                 if(sc_event_callback.s == NULL || sc_event_callback.len <= 0) {
2924                         LM_ERR("no kemi callback set\n");
2925                         set_route_type(rtb);
2926                         return -1;
2927                 }
2928                 keng = sr_kemi_eng_get();
2929                 if(keng==NULL) {
2930                         LM_ERR("kemi engine not available\n");
2931                         set_route_type(rtb);
2932                         return -1;
2933                 }
2934                 if(keng->froute(msg, EVENT_ROUTE, &sc_event_callback, &evname) < 0) {
2935                         LM_ERR("error running event route kemi callback\n");
2936                         set_route_type(rtb);
2937                         return -1;
2938                 }
2939         }
2940         set_route_type(rtb);
2941
2942         /* hep_hdr */
2943         heph = (struct hep_hdr *)msg->buf;
2944
2945         if(heph->hp_v == 1 || heph->hp_v == 2) {
2946
2947                 LOG(L_ERR, "ERROR: HEP v 1/2: v:[%d] l:[%d]\n", heph->hp_v, heph->hp_l);
2948                 if((len = hepv2_message_parse(buf, len, msg)) < 0) {
2949                         LOG(L_ERR, "ERROR: during hepv2 parsing :[%d]\n", len);
2950                         return 0;
2951                 }
2952
2953                 buf = msg->buf + len;
2954                 len = msg->len - len;
2955
2956                 msg->buf = buf;
2957                 msg->len = len;
2958         } else if(!memcmp(msg->buf, "\x48\x45\x50\x33", 4)
2959                         || !memcmp(msg->buf, "\x45\x45\x50\x31", 4)) {
2960
2961                 if((len = hepv3_message_parse(buf, len, msg)) < 0) {
2962                         LOG(L_ERR, "ERROR: during hepv3 parsing :[%d]\n", len);
2963                         return 0;
2964                 }
2965
2966                 buf = msg->buf + len;
2967                 len = msg->len - len;
2968
2969                 msg->buf = buf;
2970                 msg->len = len;
2971         } else {
2972                 LOG(L_ERR, "ERROR: sipcapture:hep_msg_received: not supported version "
2973                                 "or bad length: v:[%d] l:[%d]\n",
2974                                 heph->hp_v, heph->hp_l);
2975                 return -1;
2976         }
2977
2978         if(parse_msg(buf, len, msg) != 0) {
2979                 LOG(L_ERR, "couldn't parse sip message\n");
2980                 return -1;
2981         }
2982
2983         return ret;
2984 }
2985
2986
2987 static int hep_version(struct sip_msg *msg)
2988 {
2989         struct hep_hdr *heph;
2990         /* hep_hdr */
2991         heph = (struct hep_hdr *)msg->buf;
2992
2993         if(heph->hp_v == 1 || heph->hp_v == 2)
2994                 return heph->hp_v;
2995         else if(!memcmp(msg->buf, "\x48\x45\x50\x33", 4)
2996                         || !memcmp(msg->buf, "\x45\x45\x50\x31", 4))
2997                 return 3;
2998
2999         return -1;
3000 }
3001
3002 static int fix_hex_int(str *s)
3003 {
3004
3005         unsigned int retval = 0;
3006
3007         if(!s->len || !s->s)
3008                 goto error;
3009
3010         if(s->len > 2)
3011                 if((s->s[0] == '0') && ((s->s[1] | 0x20) == 'x')) {
3012                         if(hexstr2int(s->s + 2, s->len - 2, &retval) != 0)
3013                                 goto error;
3014                         else
3015                                 return retval;
3016                 }
3017
3018         if(str2int(s, (unsigned int *)&retval) < 0)
3019                 goto error;
3020
3021
3022         return retval;
3023
3024 error:
3025         LM_ERR("Invalid value for hex: <%*s>!\n", s->len, s->s);
3026         return -1;
3027 }
3028
3029
3030 static int pv_parse_hep_name(pv_spec_p sp, str *in)
3031 {
3032         int valchunk = 0;
3033
3034         if(sp == NULL || in == NULL || in->len <= 0)
3035                 return -1;
3036
3037         LM_DBG("REQUEST, PRE, %.*s\n", in->len, in->s);
3038
3039         switch(in->len) {
3040                 case 5: {
3041                                         if((valchunk = fix_hex_int(in)) > 0)
3042                                                 sp->pvp.pvn.u.isname.name.n = valchunk;
3043                                         else
3044                                                 goto error;
3045                                 } break;
3046                 case 6: {
3047                                         if(!strncmp(in->s, "src_ip", 6))
3048                                                 sp->pvp.pvn.u.isname.name.n = 2;
3049                                         else if(!strncmp(in->s, "dst_ip", 6))
3050                                                 sp->pvp.pvn.u.isname.name.n = 3;
3051                                         else
3052                                                 goto error;
3053                                 } break;
3054                 case 7: {
3055                                         if(!strncmp(in->s, "version", 7))
3056                                                 sp->pvp.pvn.u.isname.name.n = 0;
3057                                         else
3058                                                 goto error;
3059                                 } break;
3060                 default:
3061                                 goto error;
3062         }
3063         sp->pvp.pvn.type = PV_NAME_INTSTR;
3064         sp->pvp.pvn.u.isname.type = 0;
3065
3066         return 0;
3067
3068 error:
3069         LM_ERR("unknown hep name %.*s\n", in->len, in->s);
3070         return -1;
3071 }
3072
3073
3074 static int pv_get_hep(struct sip_msg *msg, pv_param_t *param, pv_value_t *res)
3075 {
3076         static char sc_buf_ip[IP_ADDR_MAX_STR_SIZE + 12];
3077         int sc_buf_ip_len;
3078
3079         if(param == NULL)
3080                 return -1;
3081
3082         switch(param->pvn.u.isname.name.n) {
3083                 case 0:
3084                         return pv_get_uintval(msg, param, res, hep_version(msg));
3085                 case 1:
3086                         return pv_get_uintval(msg, param, res, hep_version(msg));
3087                 case 2:
3088                         sc_buf_ip_len = ip_addr2sbuf(
3089                                         &msg->rcv.src_ip, sc_buf_ip, sizeof(sc_buf_ip) - 1);
3090                         sc_buf_ip[sc_buf_ip_len] = 0;
3091                         return pv_get_strlval(msg, param, res, sc_buf_ip, sc_buf_ip_len);
3092                 case 3:
3093                         sc_buf_ip_len = ip_addr2sbuf(
3094                                         &msg->rcv.dst_ip, sc_buf_ip, sizeof(sc_buf_ip) - 1);
3095                         sc_buf_ip[sc_buf_ip_len] = 0;