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