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