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