modules/sipcapture HEPv3 implementation. ALPHA!!! The final version will be after...
[sip-router] / modules / sipcapture / sipcapture.c
1 /* 
2  * $Id$ 
3  *
4  * sipcapture module - helper module to capture sip messages
5  *
6  * Copyright (C) 2011 Alexandr Dubovikov (QSC AG) (alexandr.dubovikov@gmail.com)
7  *
8  * This file is part of Kamailio, a free SIP server.
9  *
10  * Kamailio is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version
14  *
15  * Kamailio is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License 
21  * along with this program; if not, write to the Free Software 
22  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23  *
24  */
25
26 /*! \file
27  * sipcapture module - helper module to capture sip messages
28  *
29  */
30
31
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <time.h>
36 #include <sys/ioctl.h>
37 #include <sys/types.h>
38 #include <sys/socket.h>
39 #include <netinet/in.h>
40 #include <net/if.h> 
41 #include <netdb.h>
42
43 /* BPF structure */
44 #ifdef __OS_linux
45 #include <linux/filter.h>
46 #endif
47
48 #ifndef __USE_BSD
49 #define __USE_BSD  /* on linux use bsd version of iphdr (more portable) */
50 #endif /* __USE_BSD */
51 #include <netinet/ip.h>
52 #define __FAVOR_BSD /* on linux use bsd version of udphdr (more portable) */
53 #include <netinet/udp.h>
54
55 #include "../../sr_module.h"
56 #include "../../dprint.h"
57 #include "../../events.h"
58 #include "../../ut.h"
59 #include "../../ip_addr.h"
60 #include "../../mem/mem.h"
61 #include "../../mem/shm_mem.h"
62 #include "../../lib/kmi/mi.h"
63 #include "../../lib/srdb1/db.h"
64 #include "../../parser/contact/parse_contact.h"
65 #include "../../parser/parse_content.h"
66 #include "../../parser/parse_from.h"
67 #include "../../parser/parse_uri.h"
68 #include "../../parser/digest/digest.h"
69 #include "../../lib/kcore/parse_pai.h"
70 #include "../../lib/kcore/parse_ppi.h"
71 #include "../../pvar.h"
72 #include "../../str.h"
73 #include "../../onsend.h"
74 #include "../../resolve.h"
75 #include "../../receive.h"
76 #include "sipcapture.h"
77 #include "hash_mode.h"
78
79 #ifdef STATISTICS
80 #include "../../lib/kcore/statistics.h"
81 #endif
82
83
84 MODULE_VERSION
85
86
87 #define ETHHDR 14 /* sizeof of ethhdr structure */
88
89 #define EMPTY_STR(val) val.s=""; val.len=0;
90
91 #define TABLE_LEN 256
92
93 #define NR_KEYS 37
94
95 #define HEP_BUF_SIZE  65535
96
97
98 /* module function prototypes */
99 static int mod_init(void);
100 static int child_init(int rank);
101 static void destroy(void);
102 static int sip_capture(struct sip_msg *msg, char *s1, char *s2);
103 int hep_msg_received(void *data);
104 int init_rawsock_children(void);
105 int extract_host_port(void);
106 int raw_capture_socket(struct ip_addr* ip, str* iface, int port_start, int port_end, int proto);
107 int raw_capture_rcv_loop(int rsock, int port1, int port2, int ipip);
108
109
110 /* HEPv2 HEPv3 */
111 int hepv2_received(char *buf, unsigned int *len, struct receive_info *ri);
112 int hepv3_received(char *buf, unsigned int *len, struct receive_info *ri);
113 int parsing_hepv3_message(char *buf, unsigned int *len);
114
115 int init_tcp_listen_children();
116 int tcp_capture_rcv_loop(int tsock);
117 int get_tcp_stream(int tcp_sock_desc);
118 int tcp_capture_socket();
119
120
121 static struct mi_root* sip_capture_mi(struct mi_root* cmd, void* param );
122
123 static str db_url               = str_init(DEFAULT_RODB_URL);
124 static str table_name           = str_init("sip_capture");
125 static str hash_source          = str_init("call_id");
126 static str mt_mode                      = str_init("rand");
127 static str id_column            = str_init("id");
128 static str date_column          = str_init("date");
129 static str micro_ts_column      = str_init("micro_ts");
130 static str method_column        = str_init("method");   
131 static str reply_reason_column  = str_init("reply_reason");        
132 static str ruri_column          = str_init("ruri");             
133 static str ruri_user_column     = str_init("ruri_user");  
134 static str from_user_column     = str_init("from_user");  
135 static str from_tag_column      = str_init("from_tag");   
136 static str to_user_column       = str_init("to_user");
137 static str to_tag_column        = str_init("to_tag");   
138 static str pid_user_column      = str_init("pid_user");
139 static str contact_user_column  = str_init("contact_user");
140 static str auth_user_column     = str_init("auth_user");  
141 static str callid_column        = str_init("callid");
142 static str callid_aleg_column   = str_init("callid_aleg");
143 static str via_1_column         = str_init("via_1");      
144 static str via_1_branch_column  = str_init("via_1_branch"); 
145 static str cseq_column          = str_init("cseq");     
146 static str diversion_column     = str_init("diversion_user"); 
147 static str reason_column        = str_init("reason");        
148 static str content_type_column  = str_init("content_type");  
149 static str authorization_column = str_init("authorization"); 
150 static str user_agent_column    = str_init("user_agent");
151 static str source_ip_column     = str_init("source_ip");  
152 static str source_port_column   = str_init("source_port");      
153 static str dest_ip_column       = str_init("destination_ip");
154 static str dest_port_column     = str_init("destination_port");         
155 static str contact_ip_column    = str_init("contact_ip"); 
156 static str contact_port_column  = str_init("contact_port");
157 static str orig_ip_column       = str_init("originator_ip");      
158 static str orig_port_column     = str_init("originator_port");    
159 static str rtp_stat_column      = str_init("rtp_stat");    
160 static str proto_column         = str_init("proto"); 
161 static str family_column        = str_init("family"); 
162 static str type_column          = str_init("type");  
163 static str node_column          = str_init("node");  
164 static str msg_column           = str_init("msg");   
165 static str capture_node         = str_init("homer01");          
166 static str star_contact         = str_init("*");
167
168 int raw_sock_desc = -1; /* raw socket used for ip packets */
169 unsigned int raw_sock_children = 1;
170 int capture_on   = 0;
171 int hep_capture_on   = 0;
172 int ipip_capture_on   = 0;
173 int moni_capture_on   = 0;
174 int moni_port_start = 0;
175 int moni_port_end   = 0;
176 int *capture_on_flag = NULL;
177 int db_insert_mode = 0;
178 int promisc_on = 0;
179 int bpf_on = 0;
180 int hep_offset = 0; //this stores the hep header added offset 
181 int tcp_hep_port = 9060;
182 int tcp_hep_capture_on   = 0;
183 int tcp_hep_socket = -1; /* tcp hep socket */
184 int fork_on_accept = 0; /* fork on new accept */
185 unsigned int hep_tcp_sock_children = 1;
186
187
188 str raw_socket_listen = { 0, 0 };
189 str raw_interface = { 0, 0 };
190
191 struct ifreq ifr;       /* interface structure */
192
193 #ifdef __OS_linux
194 /* Linux socket filter */
195 /* tcpdump -s 0 udp and portrange 5060-5090 -dd */
196 static struct sock_filter BPF_code[] = { { 0x28, 0, 0, 0x0000000c }, { 0x15, 0, 7, 0x000086dd },
197         { 0x30, 0, 0, 0x00000014 },   { 0x15, 0, 18, 0x00000011 }, { 0x28, 0, 0, 0x00000036 },
198         { 0x35, 0, 1, 0x000013c4 },   { 0x25, 0, 14, 0x000013e2 }, { 0x28, 0, 0, 0x00000038 },
199         { 0x35, 11, 13, 0x000013c4 }, { 0x15, 0, 12, 0x00000800 }, { 0x30, 0, 0, 0x00000017 },
200         { 0x15, 0, 10, 0x00000011 },  { 0x28, 0, 0, 0x00000014 },  { 0x45, 8, 0, 0x00001fff },
201         { 0xb1, 0, 0, 0x0000000e },   { 0x48, 0, 0, 0x0000000e },  { 0x35, 0, 1, 0x000013c4 },
202         { 0x25, 0, 3, 0x000013e2 },   { 0x48, 0, 0, 0x00000010 },  { 0x35, 0, 2, 0x000013c4 },
203         { 0x25, 1, 0, 0x000013e2 },   { 0x6, 0, 0, 0x0000ffff },   { 0x6, 0, 0, 0x00000000 },
204 };
205 #endif
206
207 db1_con_t *db_con = NULL;               /*!< database connection */
208 db_func_t db_funcs;                     /*!< Database functions */
209
210 str* table_names = NULL;
211 unsigned int no_tables = 0;
212
213 /*multiple table mode*/
214 enum e_mt_mode{
215         mode_random = 1,
216         mode_hash,
217         mode_round_robin,
218         mode_error
219 };
220
221 enum e_mt_mode mtmode = mode_random ;
222 enum hash_source source = hs_error;
223
224 unsigned int rr_idx = 0;
225
226 struct hep_timehdr* heptime;
227
228
229 /*! \brief
230  * Exported functions
231  */
232 static cmd_export_t cmds[] = {
233         {"sip_capture", (cmd_function)sip_capture, 0, 0, 0, ANY_ROUTE},
234         {0, 0, 0, 0, 0, 0}
235 };
236
237
238 /*! \brief
239  * Exported parameters
240  */
241 static param_export_t params[] = {
242         {"db_url",                      STR_PARAM, &db_url.s            },
243         {"table_name",                  STR_PARAM, &table_name.s        },
244         {"hash_source",                         STR_PARAM, &hash_source.s       },
245         {"mt_mode",                                     STR_PARAM, &mt_mode.s   },
246         {"id_column",                   STR_PARAM, &id_column.s         },
247         {"date_column",                 STR_PARAM, &date_column.s       },      
248         {"micro_ts_column",             STR_PARAM, &micro_ts_column.s   },
249         {"method_column",               STR_PARAM, &method_column.s     },
250         {"reply_reason_column",         STR_PARAM, &reply_reason_column.s       },
251         {"ruri_column",                 STR_PARAM, &ruri_column.s       },
252         {"ruri_user_column",            STR_PARAM, &ruri_user_column.s  },
253         {"from_user_column",            STR_PARAM, &from_user_column.s  },
254         {"from_tag_column",             STR_PARAM, &from_tag_column.s   },
255         {"to_user_column",              STR_PARAM, &to_user_column.s    },
256         {"to_tag_column",               STR_PARAM, &to_tag_column.s     },      
257         {"pid_user_column",             STR_PARAM, &pid_user_column.s   },
258         {"contact_user_column",         STR_PARAM, &contact_user_column.s       },
259         {"auth_user_column",            STR_PARAM, &auth_user_column.s  },
260         {"callid_column",               STR_PARAM, &callid_column.s},
261         {"callid_aleg_column",          STR_PARAM, &callid_aleg_column.s},
262         {"via_1_column",                STR_PARAM, &via_1_column.s      },
263         {"via_1_branch_column",         STR_PARAM, &via_1_branch_column.s },
264         {"cseq_column",                 STR_PARAM, &cseq_column.s     },
265         {"diversion_column",            STR_PARAM, &diversion_column.s },
266         {"reason_column",               STR_PARAM, &reason_column.s        },
267         {"content_type_column",         STR_PARAM, &content_type_column.s  },
268         {"authorization_column",        STR_PARAM, &authorization_column.s },
269         {"user_agent_column",           STR_PARAM, &user_agent_column.s },
270         {"source_ip_column",            STR_PARAM, &source_ip_column.s  },
271         {"source_port_column",          STR_PARAM, &source_port_column.s},      
272         {"destination_ip_column",       STR_PARAM, &dest_ip_column.s    },
273         {"destination_port_column",     STR_PARAM, &dest_port_column.s  },              
274         {"contact_ip_column",           STR_PARAM, &contact_ip_column.s },
275         {"contact_port_column",         STR_PARAM, &contact_port_column.s       },
276         {"originator_ip_column",        STR_PARAM, &orig_ip_column.s    },
277         {"originator_port_column",      STR_PARAM, &orig_port_column.s  },
278         {"proto_column",                STR_PARAM, &proto_column.s },
279         {"family_column",               STR_PARAM, &family_column.s },
280         {"rtp_stat_column",             STR_PARAM, &rtp_stat_column.s },
281         {"type_column",                 STR_PARAM, &type_column.s  },
282         {"node_column",                 STR_PARAM, &node_column.s  },
283         {"msg_column",                  STR_PARAM, &msg_column.s   },
284         {"capture_on",                  INT_PARAM, &capture_on          },
285         {"capture_node",                STR_PARAM, &capture_node.s      },
286         {"raw_sock_children",           INT_PARAM, &raw_sock_children   },      
287         {"hep_capture_on",              INT_PARAM, &hep_capture_on   }, 
288         {"raw_socket_listen",           STR_PARAM, &raw_socket_listen.s   },        
289         {"raw_ipip_capture_on",         INT_PARAM, &ipip_capture_on  }, 
290         {"raw_moni_capture_on",         INT_PARAM, &moni_capture_on  }, 
291         {"db_insert_mode",              INT_PARAM, &db_insert_mode  },  
292         {"raw_interface",               STR_PARAM, &raw_interface.s   },
293         {"promiscious_on",              INT_PARAM, &promisc_on   },             
294         {"raw_moni_bpf_on",             INT_PARAM, &bpf_on   },         
295         {"hep_tcp_sock_children",       INT_PARAM, &hep_tcp_sock_children   },
296         {"hep_tcp_capture_on",          INT_PARAM, &tcp_hep_capture_on   },
297         {"fork_on_accept",              INT_PARAM, &fork_on_accept   },
298         {"tcp_hep_port",                INT_PARAM, &tcp_hep_port   },
299         {0, 0, 0}
300 };
301
302 /*! \brief
303  * MI commands
304  */
305 static mi_export_t mi_cmds[] = {
306         { "sip_capture", sip_capture_mi,   0,  0,  0 },
307         { 0, 0, 0, 0, 0}
308 };
309
310
311 #ifdef STATISTICS
312 stat_var* sipcapture_req;
313 stat_var* sipcapture_rpl;
314
315 stat_export_t sipcapture_stats[] = {
316         {"captured_requests" ,  0,  &sipcapture_req  },
317         {"captured_replies"  ,  0,  &sipcapture_rpl  },
318         {0,0,0}
319 };
320 #endif
321
322 /*! \brief module exports */
323 struct module_exports exports = {
324         "sipcapture", 
325         DEFAULT_DLFLAGS, /*!< dlopen flags */
326         cmds,       /*!< Exported functions */
327         params,     /*!< Exported parameters */
328 #ifdef STATISTICS
329         sipcapture_stats,  /*!< exported statistics */
330 #else
331         0,          /*!< exported statistics */
332 #endif
333         mi_cmds,    /*!< exported MI functions */
334         0,          /*!< exported pseudo-variables */
335         0,          /*!< extra processes */
336         mod_init,   /*!< module initialization function */
337         0,          /*!< response function */
338         destroy,    /*!< destroy function */
339         child_init  /*!< child initialization function */
340 };
341
342
343 static int mt_init(void) {
344
345         char *p = NULL;
346         int i = 0;
347
348         /*parse and save table names*/
349         no_tables = 1;
350         p = table_name.s;
351
352         while (*p)
353         {
354                 if (*p== '|')
355                 {
356                         no_tables++;
357                 }
358                 p++;
359         }
360
361         table_names = (str*)pkg_malloc(sizeof(str) * no_tables);
362         if(table_names == NULL) {
363                 LM_ERR("no more pkg memory left\n");
364                 return -1;
365         }
366         p = strtok (table_name.s,"| \t");
367         while (p != NULL)
368         {
369                 LM_INFO ("INFO: table name:%s\n",p);
370                 table_names[i].s =  p;
371                 table_names[i].len = strlen (p);
372                 i++;
373                 p = strtok (NULL, "| \t");
374         }
375
376         if (strcmp (mt_mode.s, "rand") ==0)
377         {
378                 mtmode = mode_random;
379         }
380         else if (strcmp (mt_mode.s, "round_robin") ==0)
381         {
382                 mtmode = mode_round_robin;
383         }
384         else if (strcmp (mt_mode.s, "hash") == 0)
385         {
386                 mtmode = mode_hash;
387         }
388         else {
389                 LM_ERR("ERROR: sipcapture: mod_init: multiple tables mode unrecognized\n");
390                 return -1;
391                 
392         }
393
394
395         if ( mtmode == mode_hash && (source = get_hash_source (hash_source.s) ) == hs_error)
396         {
397                 LM_ERR("ERROR: sipcapture: mod_init: hash source unrecognized\n");
398                 return -1;
399         }
400
401         srand(time(NULL));
402
403         return 0;
404
405 }
406
407 /*! \brief Initialize sipcapture module */
408 static int mod_init(void) {
409
410         struct ip_addr *ip = NULL;
411
412 #ifdef STATISTICS
413         /* register statistics */
414         if (register_module_stats(exports.name, sipcapture_stats)!=0)
415         {
416                 LM_ERR("failed to register core statistics\n");
417                 return -1;
418         }
419 #endif
420
421         if(register_mi_mod(exports.name, mi_cmds)!=0)
422         {
423                 LM_ERR("failed to register MI commands\n");
424                 return -1;
425         }
426
427         db_url.len = strlen(db_url.s);
428         table_name.len = strlen(table_name.s);
429         hash_source.len = strlen (hash_source.s);
430         mt_mode.len = strlen(mt_mode.s);
431         date_column.len = strlen(date_column.s);
432         id_column.len = strlen(id_column.s);
433         micro_ts_column.len = strlen(micro_ts_column.s);
434         method_column.len = strlen(method_column.s);    
435         reply_reason_column.len = strlen(reply_reason_column.s);        
436         ruri_column.len = strlen(ruri_column.s);        
437         ruri_user_column.len = strlen(ruri_user_column.s);  
438         from_user_column.len = strlen(from_user_column.s);  
439         from_tag_column.len = strlen(from_tag_column.s);   
440         to_user_column.len = strlen(to_user_column.s);
441         pid_user_column.len = strlen(pid_user_column.s);
442         contact_user_column.len = strlen(contact_user_column.s);
443         auth_user_column.len = strlen(auth_user_column.s);  
444         callid_column.len = strlen(callid_column.s);
445         via_1_column.len = strlen(via_1_column.s);      
446         via_1_branch_column.len = strlen(via_1_branch_column.s); 
447         cseq_column.len = strlen(cseq_column.s);     
448         diversion_column.len = strlen(diversion_column.s); 
449         reason_column.len = strlen(reason_column.s);        
450         content_type_column.len = strlen(content_type_column.s);  
451         authorization_column.len = strlen(authorization_column.s); 
452         user_agent_column.len = strlen(user_agent_column.s);
453         source_ip_column.len = strlen(source_ip_column.s);  
454         source_port_column.len = strlen(source_port_column.s);  
455         dest_ip_column.len = strlen(dest_ip_column.s);
456         dest_port_column.len = strlen(dest_port_column.s);              
457         contact_ip_column.len = strlen(contact_ip_column.s); 
458         contact_port_column.len = strlen(contact_port_column.s);
459         orig_ip_column.len = strlen(orig_ip_column.s);      
460         orig_port_column.len = strlen(orig_port_column.s);    
461         proto_column.len = strlen(proto_column.s); 
462         family_column.len = strlen(family_column.s); 
463         type_column.len = strlen(type_column.s);  
464         rtp_stat_column.len = strlen(rtp_stat_column.s);  
465         node_column.len = strlen(node_column.s);  
466         msg_column.len = strlen(msg_column.s);   
467         capture_node.len = strlen(capture_node.s);      
468         
469         if(raw_socket_listen.s) 
470                 raw_socket_listen.len = strlen(raw_socket_listen.s);            
471         if(raw_interface.s)
472                 raw_interface.len = strlen(raw_interface.s);            
473
474         /* Find a database module */
475         if (db_bind_mod(&db_url, &db_funcs))
476         {
477                 LM_ERR("unable to bind database module\n");
478                 return -1;
479         }
480         if (!DB_CAPABILITY(db_funcs, DB_CAP_INSERT))
481         {
482                 LM_ERR("database modules does not provide all functions needed"
483                                 " by module\n");
484                 return -1;
485         }
486
487         /*Check the table name*/
488         if(!table_name.len) {   
489                 LM_ERR("ERROR: sipcapture: mod_init: table_name is not defined or empty\n");
490                 return -1;
491         }
492
493         if (mt_init () <0)
494         {
495                 return -1;
496         }
497
498
499         if(db_insert_mode) {
500                 LM_INFO("INFO: sipcapture: mod_init: you have enabled INSERT DELAYED \
501                                 Make sure your DB can support it\n");
502         }
503
504         capture_on_flag = (int*)shm_malloc(sizeof(int));
505         if(capture_on_flag==NULL) {
506                 LM_ERR("no more shm memory left\n");
507                 return -1;
508         }
509         
510         *capture_on_flag = capture_on;
511         
512         /* register DGRAM event */
513         if(sr_event_register_cb(SREV_NET_DGRAM_IN, hep_msg_received) < 0) {
514                 LM_ERR("failed to register SREV_NET_DGRAM_IN event\n");
515                 return -1;                                      
516         }
517
518         if(ipip_capture_on && moni_capture_on) {
519                 LM_ERR("only one RAW mode is supported. Please disable ipip_capture_on or moni_capture_on\n");
520                 return -1;                                              
521         }
522         
523
524
525         /* raw processes for IPIP encapsulation */
526         if (ipip_capture_on || moni_capture_on) {
527                 register_procs(raw_sock_children);
528                                                 
529                 if(extract_host_port() && (((ip=str2ip(&raw_socket_listen)) == NULL)
530 #ifdef  USE_IPV6
531                                && ((ip=str2ip6(&raw_socket_listen)) == NULL)
532 #endif
533                          )) 
534                 {               
535                         LM_ERR("sipcapture mod_init: bad RAW IP: %.*s\n", raw_socket_listen.len, raw_socket_listen.s); 
536                         return -1;
537                 }               
538                         
539                 if(moni_capture_on && !moni_port_start) {
540                         LM_ERR("ERROR:sipcapture:mod_init: Please define port/portrange in 'raw_socket_listen', before \
541                                                 activate monitoring capture\n");
542                         return -1;                                              
543                 }                       
544                         
545                 raw_sock_desc = raw_capture_socket(raw_socket_listen.len ? ip : 0, raw_interface.len ? &raw_interface : 0, 
546                                                 moni_port_start, moni_port_end , ipip_capture_on ? IPPROTO_IPIP : htons(0x0800));                                                        
547                                                 
548                 if(raw_sock_desc < 0) {
549                         LM_ERR("could not initialize raw udp socket:"
550                                          " %s (%d)\n", strerror(errno), errno);
551                         if (errno == EPERM)
552                                 LM_ERR("could not initialize raw socket on startup"
553                                         " due to inadequate permissions, please"
554                                         " restart as root or with CAP_NET_RAW\n");
555                                 
556                         return -1;              
557                 }
558
559                 if(promisc_on && raw_interface.len) {
560
561                          memset(&ifr, 0, sizeof(ifr));
562                          memcpy(ifr.ifr_name, raw_interface.s, raw_interface.len);
563
564
565 #ifdef __OS_linux                                                
566                          if(ioctl(raw_sock_desc, SIOCGIFFLAGS, &ifr) < 0) {
567                                 LM_ERR("could not get flags from interface [%.*s]:"
568                                          " %s (%d)\n", raw_interface.len, raw_interface.s, strerror(errno), errno);                                                                              
569                                 goto error;
570                          }
571                          
572                          ifr.ifr_flags |= IFF_PROMISC; 
573                          
574                          if (ioctl(raw_sock_desc, SIOCSIFFLAGS, &ifr) < 0) {
575                                 LM_ERR("could not set PROMISC flag to interface [%.*s]:"
576                                          " %s (%d)\n", raw_interface.len, raw_interface.s, strerror(errno), errno);                                                                              
577                                 goto error;                      
578                          }
579 #endif
580                          
581                 }               
582         }
583         
584         if(tcp_hep_capture_on ) {
585
586                 register_procs(hep_tcp_sock_children);
587
588                 if(!tcp_capture_socket()) {
589                                 LM_ERR("coudn't initialize tcp HEP capture socket");
590                                 goto error;
591
592                 }
593         }
594
595
596         return 0;
597 #ifdef __OS_linux                                                
598 error:
599         if(raw_sock_desc) close(raw_sock_desc);
600         if(tcp_hep_socket) close(tcp_hep_socket);
601         return -1;      
602 #endif
603 }
604
605 int extract_host_port(void)
606 {
607         if(raw_socket_listen.len) {
608                 char *p1,*p2;
609                 p1 = raw_socket_listen.s;
610                         
611                 if( (p1 = strrchr(p1, ':')) != 0 ) {
612                          *p1 = '\0';
613                          p1++;                   
614                          p2=p1;
615                          if((p2 = strrchr(p2, '-')) != 0 ) {
616                                 p2++;
617                                 moni_port_end = atoi(p2);
618                                 p1[strlen(p1)-strlen(p2)-1]='\0';
619                          }
620                          moni_port_start = atoi(p1);
621                          raw_socket_listen.len = strlen(raw_socket_listen.s);
622                 }                                                                                                                                                                                       
623                 return 1;
624         }
625         return 0;
626 }
627
628
629 static int child_init(int rank)
630 {
631         if (rank == PROC_MAIN) {
632                 if((ipip_capture_on || moni_capture_on) && (init_rawsock_children() < 0))
633                                                  return -1;
634
635                 if(tcp_hep_capture_on && (init_tcp_listen_children() < 0))
636                                                 return -1;
637         }
638
639
640         if (rank==PROC_INIT || rank==PROC_MAIN || rank==PROC_TCP_MAIN)
641                 return 0; /* do nothing for the main process */
642
643         db_con = db_funcs.init(&db_url);
644         if (!db_con)
645         {
646                 LM_ERR("unable to connect to database. Please check configuration.\n");
647                 return -1;
648         }
649         
650         heptime = (struct hep_timehdr*)pkg_malloc(sizeof(struct hep_timehdr));
651         if(heptime==NULL) {
652                 LM_ERR("no more pkg memory left\n");
653                 return -1;
654         }
655
656     if (mtmode ==mode_round_robin && rank > 0)
657     {
658                 rr_idx = rank % no_tables;
659     }
660
661         return 0;
662 }
663
664 /*
665  * RAW IPIP || Monitoring listeners
666  */
667 int init_rawsock_children(void)
668 {
669         int i;
670         pid_t pid;
671
672         for(i = 0; i < raw_sock_children; i++) {
673                 pid = fork_process(PROC_UNIXSOCK,"homer raw socket", 1);
674                 if (pid < 0) {
675                         ERR("Unable to fork: %s\n", strerror(errno));
676                         return -1;
677                 } else if (pid == 0) { /* child */
678                         raw_capture_rcv_loop(raw_sock_desc, moni_port_start, moni_port_end, moni_capture_on ? 0 : 1);
679                 }
680                 /* Parent */
681         }
682
683         DBG("Raw IPIP socket server successfully initialized\n");
684         return 1;
685 }
686
687
688 static void destroy(void)
689 {
690         if (db_con!=NULL)
691                 db_funcs.close(db_con);
692         if (capture_on_flag)
693                 shm_free(capture_on_flag);
694                 
695         if(heptime) pkg_free(heptime);
696
697         if(raw_sock_desc > 0) {
698                  if(promisc_on && raw_interface.len) {
699 #ifdef __OS_linux
700                          ifr.ifr_flags &= ~(IFF_PROMISC);
701
702                          if (ioctl(raw_sock_desc, SIOCSIFFLAGS, &ifr) < 0) {
703                                 LM_ERR("destroy: could not remove PROMISC flag from interface [%.*s]:"
704                                          " %s (%d)\n", raw_interface.len, raw_interface.s, strerror(errno), errno);
705                          }
706 #endif                        
707                 }                               
708                 close(raw_sock_desc);
709         }
710         if (table_names){
711                 pkg_free(table_names);
712         }
713 }
714
715
716 /**
717  * HEP message
718  */
719 int hep_msg_received(void *data)
720 {
721
722         void **srevp;
723         char *buf;
724         unsigned *len;
725         struct receive_info *ri;
726
727         struct hep_hdr *heph;
728
729         srevp = (void**)data;
730
731         buf = (char *)srevp[0];
732         len = (unsigned *)srevp[1];
733         ri = (struct receive_info *)srevp[2];
734
735         /* hep_hdr */
736         heph = (struct hep_hdr*) buf;
737
738         /* Check version */
739         if(heph->hp_v == 1 || heph->hp_v == 2)  {
740
741                 return hepv2_received(buf, len, ri);
742         }
743         else if(!memcmp(buf, "\x48\x45\x50\x33",4)) {
744
745                 //LOG(L_ERR, "DATA: HEPv3\r\n");
746                 //LM_ERR("ZZ: [%c%c%c%c]\n", buf[0], buf[1], buf[2], buf[3]);
747                 return hepv3_received(buf, len, ri);
748         }
749         else {
750
751                 LOG(L_ERR, "ERROR: sipcapture:hep_msg_received: not supported version or bad length: v:[%d] l:[%d]\n",
752                                                 heph->hp_v, heph->hp_l);
753                 return -1;
754         }
755 }
756
757
758 /**
759  * HEP v1 && v2 message
760  */
761 int hepv2_received(char *buf, unsigned int *len, struct receive_info *ri)
762 {
763         int hl;
764         struct hep_hdr *heph;
765         struct ip_addr dst_ip, src_ip;
766         char *hep_payload, *end, *hep_ip;
767         struct hep_iphdr *hepiph = NULL;
768
769         struct hep_timehdr* heptime_tmp = NULL;
770         memset(heptime, 0, sizeof(struct hep_timehdr));
771
772 #ifdef USE_IPV6
773         struct hep_ip6hdr *hepip6h = NULL;
774 #endif /* USE_IPV6 */
775
776         hep_offset = 0; 
777         
778         hl = hep_offset = sizeof(struct hep_hdr);
779         end = buf + *len;
780         if (unlikely(*len<hep_offset)) {
781                 LOG(L_ERR, "ERROR: sipcapture:hep_msg_received len less than offset [%i] vs [%i]\n", *len, hep_offset);
782                 return -1;
783         }
784
785         /* hep_hdr */
786         heph = (struct hep_hdr*) buf;
787
788         switch(heph->hp_f){
789                 case AF_INET:
790                         hl += sizeof(struct hep_iphdr);
791                         break;
792 #ifdef USE_IPV6
793                 case AF_INET6:
794                         hl += sizeof(struct hep_ip6hdr);
795                         break;
796 #endif /* USE_IPV6 */
797                 default:
798                         LOG(L_ERR, "ERROR: sipcapture:hep_msg_received:  unsupported family [%d]\n", heph->hp_f);
799                         return -1;
800         }
801
802         /* PROTO */
803         if(heph->hp_p == IPPROTO_UDP) ri->proto=PROTO_UDP;
804         else if(heph->hp_p == IPPROTO_TCP) ri->proto=PROTO_TCP;
805         else if(heph->hp_p == IPPROTO_IDP) ri->proto=PROTO_TLS; /* fake protocol */
806 #ifdef USE_SCTP
807         else if(heph->hp_p == IPPROTO_SCTP) ri->proto=PROTO_SCTP;
808 #endif
809         else {
810                 LOG(L_ERR, "ERROR: sipcapture:hep_msg_received: unknow protocol [%d]\n",heph->hp_p);
811                 ri->proto = PROTO_NONE;
812         }
813
814         hep_ip = buf + sizeof(struct hep_hdr);
815
816         if (unlikely(hep_ip>end)){
817                 LOG(L_ERR,"hep_ip is over buf+len\n");
818                 return -1;
819         }
820
821         switch(heph->hp_f){
822                 case AF_INET:
823                         hep_offset+=sizeof(struct hep_iphdr);
824                         hepiph = (struct hep_iphdr*) hep_ip;
825                         break;
826 #ifdef USE_IPV6
827
828                 case AF_INET6:
829                         hep_offset+=sizeof(struct hep_ip6hdr);
830                         hepip6h = (struct hep_ip6hdr*) hep_ip;
831                         break;
832 #endif /* USE_IPV6 */
833
834         }
835
836         /* VOIP payload */
837         hep_payload = buf + hep_offset;
838
839         if (unlikely(hep_payload>end)){
840                 LOG(L_ERR,"hep_payload is over buf+len\n");
841                 return -1;
842         }
843
844         /* timming */
845         if(heph->hp_v == 2) {
846                 hep_offset+=sizeof(struct hep_timehdr);
847                 heptime_tmp = (struct hep_timehdr*) hep_payload;
848
849                 heptime->tv_sec = heptime_tmp->tv_sec;
850                 heptime->tv_usec = heptime_tmp->tv_usec;
851                 heptime->captid = heptime_tmp->captid;
852         }
853
854
855         /* fill ip from the packet to dst_ip && to */
856         switch(heph->hp_f){
857
858                 case AF_INET:
859                         dst_ip.af = src_ip.af = AF_INET;
860                         dst_ip.len = src_ip.len = 4 ;
861                         memcpy(&dst_ip.u.addr, &hepiph->hp_dst, 4);
862                         memcpy(&src_ip.u.addr, &hepiph->hp_src, 4);
863                         break;
864 #ifdef USE_IPV6
865
866                 case AF_INET6:
867                         dst_ip.af = src_ip.af = AF_INET6;
868                         dst_ip.len = src_ip.len = 16 ;
869                         memcpy(&dst_ip.u.addr, &hepip6h->hp6_dst, 16);
870                         memcpy(&src_ip.u.addr, &hepip6h->hp6_src, 16);
871                         break;
872
873 #endif /* USE_IPV6 */
874         }
875
876         ri->src_ip = src_ip;
877         ri->src_port = ntohs(heph->hp_sport);
878
879         ri->dst_ip = dst_ip;
880         ri->dst_port = ntohs(heph->hp_dport);
881
882         /* cut off the offset */
883         /* 
884          *  *len -= offset;
885          *  p = buf + offset;
886          *  memmove(buf, p, BUF_SIZE+1); 
887         */
888         memset(buf, '\n', hep_offset); /* the parser will ignore the starting \n no need to do expensive memmove */
889         
890         return 0;
891 }
892
893
894 /**
895  * HEP message
896  */
897 int hepv3_received(char *buf, unsigned int *len, struct receive_info *ri)
898 {
899         if(!parsing_hepv3_message(buf, len)) {
900                 LM_ERR("couldnot parse hepv3 message\n");
901                 return -1;
902         }
903
904         return -1;
905 }
906
907
908
909 static int sip_capture_prepare(sip_msg_t *msg)
910 {
911         /* We need parse all headers */
912         if (parse_headers(msg, HDR_CALLID_F|HDR_EOH_F, 0) != 0) {
913                 LM_ERR("cannot parse headers\n");
914                 return -1;
915         }
916         
917         return 0;
918 }
919
920 static int sip_capture_store(struct _sipcapture_object *sco)
921 {
922         db_key_t db_keys[NR_KEYS];
923         db_val_t db_vals[NR_KEYS];
924
925         str tmp;
926         int ii = 0;
927
928         if(sco==NULL)
929         {
930                 LM_DBG("invalid parameter\n");
931                 return -1;
932         }
933         
934         db_keys[0] = &id_column;                        
935         db_vals[0].type = DB1_INT;
936         db_vals[0].nul = 0;
937         db_vals[0].val.int_val = 0;
938         
939         db_keys[1] = &date_column;
940         db_vals[1].type = DB1_DATETIME;
941         db_vals[1].nul = 0;
942         db_vals[1].val.time_val = time(NULL);
943         
944         db_keys[2] = &micro_ts_column;
945         db_vals[2].type = DB1_BIGINT;
946         db_vals[2].nul = 0;
947         db_vals[2].val.ll_val = sco->tmstamp;
948         
949         db_keys[3] = &method_column;
950         db_vals[3].type = DB1_STR;
951         db_vals[3].nul = 0;
952         db_vals[3].val.str_val = sco->method;
953         
954         db_keys[4] = &reply_reason_column;
955         db_vals[4].type = DB1_STR;
956         db_vals[4].nul = 0;
957         db_vals[4].val.str_val = sco->reply_reason;
958         
959         db_keys[5] = &ruri_column;
960         db_vals[5].type = DB1_STR;
961         db_vals[5].nul = 0;
962         db_vals[5].val.str_val = sco->ruri;
963         
964         db_keys[6] = &ruri_user_column;
965         db_vals[6].type = DB1_STR;
966         db_vals[6].nul = 0;
967         db_vals[6].val.str_val = sco->ruri_user;
968         
969         db_keys[7] = &from_user_column;
970         db_vals[7].type = DB1_STR;
971         db_vals[7].nul = 0;
972         db_vals[7].val.str_val = sco->from_user;
973         
974         db_keys[8] = &from_tag_column;
975         db_vals[8].type = DB1_STR;
976         db_vals[8].nul = 0;
977         db_vals[8].val.str_val = sco->from_tag;
978
979         db_keys[9] = &to_user_column;
980         db_vals[9].type = DB1_STR;
981         db_vals[9].nul = 0;
982         db_vals[9].val.str_val = sco->to_user;
983
984         db_keys[10] = &to_tag_column;
985         db_vals[10].type = DB1_STR;
986         db_vals[10].nul = 0;
987         db_vals[10].val.str_val = sco->to_tag;
988         
989         db_keys[11] = &pid_user_column;
990         db_vals[11].type = DB1_STR;
991         db_vals[11].nul = 0;
992         db_vals[11].val.str_val = sco->pid_user;
993
994         db_keys[12] = &contact_user_column;
995         db_vals[12].type = DB1_STR;
996         db_vals[12].nul = 0;
997         db_vals[12].val.str_val = sco->contact_user;    
998
999         db_keys[13] = &auth_user_column;
1000         db_vals[13].type = DB1_STR;
1001         db_vals[13].nul = 0;
1002         db_vals[13].val.str_val = sco->auth_user;
1003         
1004         db_keys[14] = &callid_column;
1005         db_vals[14].type = DB1_STR;
1006         db_vals[14].nul = 0;
1007         db_vals[14].val.str_val = sco->callid;
1008
1009         db_keys[15] = &callid_aleg_column;
1010         db_vals[15].type = DB1_STR;
1011         db_vals[15].nul = 0;
1012         db_vals[15].val.str_val = sco->callid_aleg;
1013         
1014         db_keys[16] = &via_1_column;
1015         db_vals[16].type = DB1_STR;
1016         db_vals[16].nul = 0;
1017         db_vals[16].val.str_val = sco->via_1;
1018         
1019         db_keys[17] = &via_1_branch_column;
1020         db_vals[17].type = DB1_STR;
1021         db_vals[17].nul = 0;
1022         db_vals[17].val.str_val = sco->via_1_branch;
1023
1024         db_keys[18] = &cseq_column;
1025         db_vals[18].type = DB1_STR;
1026         db_vals[18].nul = 0;
1027         db_vals[18].val.str_val = sco->cseq;    
1028         
1029         db_keys[19] = &reason_column;
1030         db_vals[19].type = DB1_STR;
1031         db_vals[19].nul = 0;
1032         db_vals[19].val.str_val = sco->reason;
1033         
1034         db_keys[20] = &content_type_column;
1035         db_vals[20].type = DB1_STR;
1036         db_vals[20].nul = 0;
1037         db_vals[20].val.str_val = sco->content_type;
1038
1039         db_keys[21] = &authorization_column;
1040         db_vals[21].type = DB1_STR;
1041         db_vals[21].nul = 0;
1042         db_vals[21].val.str_val = sco->authorization;
1043
1044         db_keys[22] = &user_agent_column;
1045         db_vals[22].type = DB1_STR;
1046         db_vals[22].nul = 0;
1047         db_vals[22].val.str_val = sco->user_agent;
1048         
1049         db_keys[23] = &source_ip_column;
1050         db_vals[23].type = DB1_STR;
1051         db_vals[23].nul = 0;
1052         db_vals[23].val.str_val = sco->source_ip;
1053         
1054         db_keys[24] = &source_port_column;
1055         db_vals[24].type = DB1_INT;
1056         db_vals[24].nul = 0;
1057         db_vals[24].val.int_val = sco->source_port;
1058         
1059         db_keys[25] = &dest_ip_column;
1060         db_vals[25].type = DB1_STR;
1061         db_vals[25].nul = 0;
1062         db_vals[25].val.str_val = sco->destination_ip;
1063         
1064         db_keys[26] = &dest_port_column;
1065         db_vals[26].type = DB1_INT;
1066         db_vals[26].nul = 0;
1067         db_vals[26].val.int_val = sco->destination_port;        
1068         
1069         db_keys[27] = &contact_ip_column;
1070         db_vals[27].type = DB1_STR;
1071         db_vals[27].nul = 0;
1072         db_vals[27].val.str_val = sco->contact_ip;
1073         
1074         db_keys[28] = &contact_port_column;
1075         db_vals[28].type = DB1_INT;
1076         db_vals[28].nul = 0;
1077         db_vals[28].val.int_val = sco->contact_port;
1078         
1079         db_keys[29] = &orig_ip_column;
1080         db_vals[29].type = DB1_STR;
1081         db_vals[29].nul = 0;
1082         db_vals[29].val.str_val = sco->originator_ip;
1083         
1084         db_keys[30] = &orig_port_column;                        
1085         db_vals[30].type = DB1_INT;
1086         db_vals[30].nul = 0;
1087         db_vals[30].val.int_val = sco->originator_port;        
1088         
1089         db_keys[31] = &proto_column;                    
1090         db_vals[31].type = DB1_INT;
1091         db_vals[31].nul = 0;
1092         db_vals[31].val.int_val = sco->proto;        
1093
1094         db_keys[32] = &family_column;                   
1095         db_vals[32].type = DB1_INT;
1096         db_vals[32].nul = 0;
1097         db_vals[32].val.int_val = sco->family;        
1098         
1099         db_keys[33] = &rtp_stat_column;                 
1100         db_vals[33].type = DB1_STR;
1101         db_vals[33].nul = 0;
1102         db_vals[33].val.str_val = sco->rtp_stat;                
1103         
1104         db_keys[34] = &type_column;                     
1105         db_vals[34].type = DB1_INT;
1106         db_vals[34].nul = 0;
1107         db_vals[34].val.int_val = sco->type;                
1108
1109         db_keys[35] = &node_column;
1110         db_vals[35].type = DB1_STR;
1111         db_vals[35].nul = 0;
1112         db_vals[35].val.str_val = sco->node;
1113         
1114         db_keys[36] = &msg_column;
1115         db_vals[36].type = DB1_BLOB;
1116         db_vals[36].nul = 0;
1117         
1118         if(hep_offset>0){
1119                 /* if message was captured via hep skip trailing empty spaces(newlines) from the start of the buffer */
1120                 tmp.s = sco->msg.s + hep_offset;
1121                 tmp.len = sco->msg.len - hep_offset;
1122                 hep_offset = 0;
1123         } else {
1124                 tmp.s = sco->msg.s;
1125                 tmp.len = sco->msg.len;
1126         }
1127
1128         db_vals[36].val.blob_val = tmp;
1129
1130         if (no_tables > 0 ){
1131                 if ( mtmode == mode_hash ){
1132                         ii = hash_func ( sco, source , no_tables);
1133                         LM_DBG ("hash idx is:%d\n", ii);
1134                 }
1135                 else if (mtmode == mode_random )
1136                 {
1137                         ii = rand() % no_tables;
1138                         LM_DBG("rand idx is:%d\n", ii);
1139                 }
1140                 else if (mtmode == mode_round_robin)
1141                 {
1142                         ii = rr_idx;
1143                         rr_idx = (rr_idx +1) % no_tables;
1144                         LM_DBG("round robin idx is:%d\n", ii);
1145                 }
1146         }
1147         LM_DBG("insert into homer table: [%.*s]\n", table_names[ii].len, table_names[ii].s);
1148         db_funcs.use_table(db_con, &table_names[ii]);
1149
1150         LM_DBG("storing info...\n");
1151         
1152         if(db_insert_mode==1 && db_funcs.insert_delayed!=NULL) {
1153                 if (db_funcs.insert_delayed(db_con, db_keys, db_vals, NR_KEYS) < 0) {
1154                         LM_ERR("failed to insert delayed into database\n");
1155                         goto error;
1156                 }
1157         } else if (db_funcs.insert(db_con, db_keys, db_vals, NR_KEYS) < 0) {
1158                 LM_ERR("failed to insert into database\n");
1159                 goto error;               
1160         }
1161         
1162         
1163 #ifdef STATISTICS
1164         update_stat(sco->stat, 1);
1165 #endif  
1166
1167         return 1;
1168 error:
1169         return -1;
1170 }
1171
1172 static int sip_capture(struct sip_msg *msg, char *s1, char *s2)
1173 {
1174         struct _sipcapture_object sco;
1175         struct sip_uri from, to, pai, contact;
1176         struct hdr_field *hook1 = NULL;  
1177         hdr_field_t *tmphdr[4];       
1178         contact_body_t*  cb=0;                          
1179         char buf_ip[IP_ADDR_MAX_STR_SIZE+12];
1180         char *port_str = NULL, *tmp = NULL;
1181         struct timeval tvb;
1182         struct timezone tz;
1183         char tmp_node[100];
1184         char rtpinfo[256];
1185         unsigned int len = 0;
1186                                                   
1187         LM_DBG("CAPTURE DEBUG...\n");
1188
1189         gettimeofday( &tvb, &tz );
1190                 
1191
1192         if(msg==NULL) {
1193                 LM_DBG("nothing to capture\n");
1194                 return -1;
1195         }
1196         memset(&sco, 0, sizeof(struct _sipcapture_object));
1197
1198
1199         if(capture_on_flag==NULL || *capture_on_flag==0) {
1200                 LM_DBG("capture off...\n");
1201                 return -1;
1202         }
1203         
1204         if(sip_capture_prepare(msg)<0) return -1;
1205
1206         if(msg->first_line.type == SIP_REQUEST) {
1207
1208                 if (parse_sip_msg_uri(msg)<0) return -1;
1209         
1210                 sco.method = msg->first_line.u.request.method;
1211                 EMPTY_STR(sco.reply_reason);
1212                 
1213                 sco.ruri = msg->first_line.u.request.uri;
1214                 sco.ruri_user = msg->parsed_uri.user;           
1215         }
1216         else if(msg->first_line.type == SIP_REPLY) {
1217                 sco.method = msg->first_line.u.reply.status;
1218                 sco.reply_reason = msg->first_line.u.reply.reason;
1219
1220                 EMPTY_STR(sco.ruri);
1221                 EMPTY_STR(sco.ruri_user);               
1222         }
1223         else {          
1224                 LM_ERR("unknow type [%i]\n", msg->first_line.type);     
1225                 EMPTY_STR(sco.method);
1226                 EMPTY_STR(sco.reply_reason);
1227                 EMPTY_STR(sco.ruri);
1228                 EMPTY_STR(sco.ruri_user);
1229         }
1230
1231         if(heptime && heptime->tv_sec != 0) {
1232                sco.tmstamp = (unsigned long long)heptime->tv_sec*1000000+heptime->tv_usec; /* micro ts */
1233                snprintf(tmp_node, 100, "%.*s:%i", capture_node.len, capture_node.s, heptime->captid);
1234                sco.node.s = tmp_node;
1235                sco.node.len = strlen(tmp_node);
1236         }
1237         else {
1238                sco.tmstamp = (unsigned long long)tvb.tv_sec*1000000+tvb.tv_usec; /* micro ts */
1239                sco.node = capture_node;
1240         }
1241         
1242         /* Parse FROM */
1243         if(msg->from) {
1244
1245               if (parse_from_header(msg)!=0){
1246                    LOG(L_ERR, "ERROR: eval_elem: bad or missing" " From: header\n");
1247                    return -1;
1248               }
1249
1250               if (parse_uri(get_from(msg)->uri.s, get_from(msg)->uri.len, &from)<0){
1251                    LOG(L_ERR, "ERROR: do_action: bad from dropping"" packet\n");
1252                    return -1;
1253               }
1254               
1255               sco.from_user = from.user;
1256               sco.from_tag = get_from(msg)->tag_value;              
1257         }
1258         else {
1259                 EMPTY_STR(sco.from_user);
1260                 EMPTY_STR(sco.from_tag);
1261         }
1262
1263         /* Parse TO */
1264         if(msg->to) {
1265
1266               if (parse_uri(get_to(msg)->uri.s, get_to(msg)->uri.len, &to)<0){
1267                     LOG(L_ERR, "ERROR: do_action: bad to dropping"" packet\n");
1268                     return -1;
1269               }
1270         
1271               sco.to_user = to.user;
1272               if(get_to(msg)->tag_value.len) 
1273                         sco.to_tag = get_to(msg)->tag_value;              
1274               else { EMPTY_STR(sco.to_tag); }
1275         }
1276         else {        
1277                 EMPTY_STR(sco.to_user);
1278                 EMPTY_STR(sco.to_tag);
1279         }
1280         
1281         /* Call-id */
1282         if(msg->callid) sco.callid = msg->callid->body;
1283         else { EMPTY_STR(sco.callid); }
1284         
1285         /* P-Asserted-Id */
1286         if(msg->pai && (parse_pai_header(msg) == 0)) {
1287
1288              if (parse_uri(get_pai(msg)->uri.s, get_pai(msg)->uri.len, &pai)<0){
1289                 LM_DBG("DEBUG: do_action: bad pai: method:[%.*s] CID: [%.*s]\n", sco.method.len, sco.method.s, sco.callid.len, sco.callid.s);
1290              }
1291              else {
1292                 LM_DBG("PARSE PAI: (%.*s)\n",get_pai(msg)->uri.len, get_pai(msg)->uri.s);
1293                 sco.pid_user = pai.user;                          
1294              }
1295         }       
1296         else if(msg->ppi && (parse_ppi_header(msg) == 0)) {
1297                 
1298              if (parse_uri(get_ppi(msg)->uri.s, get_ppi(msg)->uri.len, &pai)<0){
1299                 LM_DBG("DEBUG: do_action: bad ppi: method:[%.*s] CID: [%.*s]\n", sco.method.len, sco.method.s, sco.callid.len, sco.callid.s);
1300              }
1301              else {
1302                 sco.pid_user = pai.user;
1303              }
1304         }
1305         else { EMPTY_STR(sco.pid_user); }
1306         
1307         /* Auth headers */
1308         if(msg->proxy_auth != NULL) hook1 = msg->proxy_auth;
1309         else if(msg->authorization != NULL) hook1 = msg->authorization;
1310
1311         if(hook1) {
1312                if(parse_credentials(hook1) == 0)  sco.auth_user = ((auth_body_t*)(hook1->parsed))->digest.username.user;               
1313                else { EMPTY_STR(sco.auth_user); }
1314         }
1315         else { EMPTY_STR(sco.auth_user);}
1316
1317         if(msg->contact) {
1318
1319               if (msg->contact->parsed == 0 && parse_contact(msg->contact) == -1) {
1320                      LOG(L_ERR,"assemble_msg: error while parsing <Contact:> header\n");
1321                      return -1;
1322               }
1323
1324               cb = (contact_body_t*)msg->contact->parsed;
1325
1326               if(cb) {
1327                     if (cb->contacts) {
1328                         if(parse_uri( cb->contacts->uri.s, cb->contacts->uri.len, &contact)<0){
1329                                 LOG(L_ERR, "ERROR: do_action: bad contact dropping"" packet\n");
1330                                 return -1;
1331                         }
1332                     } else {
1333                         if(cb->star){ /* in the case Contact is "*" */
1334                             memset(&contact, 0, sizeof(contact));
1335                             contact.user.s =  star_contact.s;
1336                             contact.user.len = star_contact.len;
1337                         } else {
1338                             LOG(L_NOTICE,"Invalid contact\n");
1339                             memset(&contact, 0, sizeof(contact));
1340                         }
1341                     }
1342             }
1343         }
1344
1345         /* get header x-cid: */
1346         /* callid_aleg X-CID */
1347         if((tmphdr[0] = get_hdr_by_name(msg,"X-CID", 5)) != NULL) {
1348                 sco.callid_aleg = tmphdr[0]->body;
1349         }
1350         else { EMPTY_STR(sco.callid_aleg);}
1351                 
1352         /* VIA 1 */
1353         sco.via_1 = msg->h_via1->body;
1354
1355         /* Via branch */
1356         if(msg->via1->branch) sco.via_1_branch = msg->via1->branch->value;
1357         else { EMPTY_STR(sco.via_1_branch); }
1358         
1359         /* CSEQ */      
1360         if(msg->cseq) sco.cseq = msg->cseq->body;
1361         else { EMPTY_STR(sco.cseq); }
1362         
1363         /* Reason */    
1364         if((tmphdr[1] = get_hdr_by_name(msg,"Reason", 6)) != NULL) {
1365                 sco.reason =  tmphdr[1]->body;
1366         }                                       
1367         else { EMPTY_STR(sco.reason); }
1368
1369         /* Diversion */ 
1370         if(msg->diversion) sco.diversion = msg->diversion->body;
1371         else { EMPTY_STR(sco.diversion);}
1372         
1373         /* Content-type */      
1374         if(msg->content_type) sco.content_type = msg->content_type->body;
1375         else { EMPTY_STR(sco.content_type);}
1376         
1377         /* User-Agent */        
1378         if(msg->user_agent) sco.user_agent = msg->user_agent->body;
1379         else { EMPTY_STR(sco.user_agent);}
1380
1381         /* Contact */   
1382         if(msg->contact && cb) {
1383                 sco.contact_ip = contact.host;
1384                 str2int(&contact.port, (unsigned int*)&sco.contact_port);
1385                 sco.contact_user = contact.user;
1386         }
1387         else {
1388                 EMPTY_STR(sco.contact_ip);      
1389                 sco.contact_port = 0;
1390                 EMPTY_STR(sco.contact_user);
1391         }
1392         
1393         /* X-OIP */     
1394         if((tmphdr[2] = get_hdr_by_name(msg,"X-OIP", 5)) != NULL) {
1395                 sco.originator_ip = tmphdr[2]->body;
1396                 /* Originator port. Should be parsed from XOIP header as ":" param */
1397                 tmp = strchr(tmphdr[2]->body.s, ':');
1398                 if (tmp) {
1399                         *tmp = '\0';
1400                         port_str = tmp + 1;
1401                         sco.originator_port = strtol(port_str, NULL, 10);
1402                 }
1403                 else sco.originator_port = 0;           
1404         }
1405         else {
1406                 EMPTY_STR(sco.originator_ip);
1407                 sco.originator_port = 0;
1408         }       
1409         
1410         /* X-RTP-Stat */        
1411         if((tmphdr[3] = get_hdr_by_name(msg,"X-RTP-Stat", 10)) != NULL) {
1412                 sco.rtp_stat =  tmphdr[3]->body;
1413         }                                
1414         /* P-RTP-Stat */        
1415         else if((tmphdr[3] = get_hdr_by_name(msg,"P-RTP-Stat", 10)) != NULL) {
1416                 sco.rtp_stat =  tmphdr[3]->body;
1417         }                                       
1418         /* RTP-RxStat */
1419         else if((tmphdr[3] = get_hdr_by_name(msg,"RTP-RxStat", 10)) != NULL) {
1420                 if(tmphdr[3]->body.len > 250) tmphdr[3]->body.len = 250;
1421
1422                 memcpy(&rtpinfo, tmphdr[3]->body.s, tmphdr[3]->body.len);
1423                 len = tmphdr[3]->body.len;
1424                 if((tmphdr[3] = get_hdr_by_name(msg,"RTP-TxStat", 10)) != NULL) {
1425                         memcpy(&rtpinfo[len], ", ", 2);
1426                         if((len + 2 + tmphdr[3]->body.len) > 256) tmphdr[3]->body.len = 256 - (len+2);
1427                         memcpy(&rtpinfo[len+2], tmphdr[3]->body.s, tmphdr[3]->body.len);
1428                 }
1429                 sco.rtp_stat.s =  rtpinfo;
1430                 sco.rtp_stat.len =  strlen(rtpinfo);
1431         }
1432
1433
1434         else { EMPTY_STR(sco.rtp_stat); }       
1435         
1436                 
1437         /* PROTO TYPE */
1438         sco.proto = msg->rcv.proto;
1439         
1440         /* FAMILY TYPE */
1441         sco.family = msg->rcv.src_ip.af;
1442         
1443         /* MESSAGE TYPE */
1444         sco.type = msg->first_line.type;
1445         
1446         /* MSG */       
1447         sco.msg.s = msg->buf;
1448         sco.msg.len = msg->len;         
1449         //EMPTY_STR(sco.msg);
1450                  
1451         /* IP source and destination */
1452         
1453         strcpy(buf_ip, ip_addr2a(&msg->rcv.src_ip));
1454         sco.source_ip.s = buf_ip;
1455         sco.source_ip.len = strlen(buf_ip);
1456         sco.source_port = msg->rcv.src_port;    
1457
1458         /*source ip*/
1459         sco.destination_ip.s = ip_addr2a(&msg->rcv.dst_ip);
1460         sco.destination_ip.len = strlen(sco.destination_ip.s);
1461         sco.destination_port = msg->rcv.dst_port;
1462         
1463         
1464         LM_DBG("src_ip: [%.*s]\n", sco.source_ip.len, sco.source_ip.s);
1465         LM_DBG("dst_ip: [%.*s]\n", sco.destination_ip.len, sco.destination_ip.s);
1466                  
1467         LM_DBG("dst_port: [%d]\n", sco.destination_port);
1468         LM_DBG("src_port: [%d]\n", sco.source_port);
1469         
1470 #ifdef STATISTICS
1471         if(msg->first_line.type==SIP_REPLY) {
1472                 sco.stat = sipcapture_rpl;
1473         } else {
1474                 sco.stat = sipcapture_req;
1475         }
1476 #endif
1477         //LM_DBG("DONE");
1478         return sip_capture_store(&sco);
1479 }
1480
1481 #define capture_is_off(_msg) \
1482         (capture_on_flag==NULL || *capture_on_flag==0)
1483
1484
1485 /*! \brief
1486  * MI Sip_capture command
1487  *
1488  * MI command format:
1489  * name: sip_capture
1490  * attribute: name=none, value=[on|off]
1491  */
1492 static struct mi_root* sip_capture_mi(struct mi_root* cmd_tree, void* param )
1493 {
1494         struct mi_node* node;
1495         
1496         struct mi_node *rpl; 
1497         struct mi_root *rpl_tree ; 
1498
1499         node = cmd_tree->node.kids;
1500         if(node == NULL) {
1501                 rpl_tree = init_mi_tree( 200, MI_SSTR(MI_OK));
1502                 if (rpl_tree == 0)
1503                         return 0;
1504                 rpl = &rpl_tree->node;
1505
1506                 if (*capture_on_flag == 0 ) {
1507                         node = add_mi_node_child(rpl,0,0,0,MI_SSTR("off"));
1508                 } else if (*capture_on_flag == 1) {
1509                         node = add_mi_node_child(rpl,0,0,0,MI_SSTR("on"));
1510                 }
1511                 return rpl_tree ;
1512         }
1513         if(capture_on_flag==NULL)
1514                 return init_mi_tree( 500, MI_SSTR(MI_INTERNAL_ERR));
1515
1516         if ( node->value.len==2 && (node->value.s[0]=='o'
1517                                 || node->value.s[0]=='O') &&
1518                         (node->value.s[1]=='n'|| node->value.s[1]=='N')) {
1519                 *capture_on_flag = 1;
1520                 return init_mi_tree( 200, MI_SSTR(MI_OK));
1521         } else if ( node->value.len==3 && (node->value.s[0]=='o'
1522                                 || node->value.s[0]=='O')
1523                         && (node->value.s[1]=='f'|| node->value.s[1]=='F')
1524                         && (node->value.s[2]=='f'|| node->value.s[2]=='F')) {
1525                 *capture_on_flag = 0;
1526                 return init_mi_tree( 200, MI_SSTR(MI_OK));
1527         } else {
1528                 return init_mi_tree( 400, MI_SSTR(MI_BAD_PARM));
1529         }
1530 }
1531
1532 /* Local raw socket */
1533 int raw_capture_socket(struct ip_addr* ip, str* iface, int port_start, int port_end, int proto)
1534 {
1535
1536         int sock = -1;  
1537         union sockaddr_union su;
1538
1539 #ifdef __OS_linux
1540         struct sock_fprog pf;
1541         char short_ifname[sizeof(int)];
1542         int ifname_len;
1543         char* ifname;
1544 #endif 
1545         //0x0003 - all packets
1546         if(proto == IPPROTO_IPIP) {
1547                 sock = socket(PF_INET, SOCK_RAW, proto);
1548         }
1549 #ifdef __OS_linux
1550         else if(proto == htons(0x800)) {
1551                 sock = socket(PF_PACKET, SOCK_RAW, proto);
1552         }
1553 #endif
1554         else {
1555                 ERR("raw_capture_socket: LSF currently supported only on linux\n");
1556                 goto error;                        
1557         }
1558                 
1559         if (sock==-1)
1560                 goto error;
1561
1562 #ifdef __OS_linux
1563
1564         /* set socket options */
1565         if (iface && iface->s){
1566
1567                 /* workaround for linux bug: arg to setsockopt must have at least
1568                  * sizeof(int) size or EINVAL would be returned */
1569                 if (iface->len<sizeof(int)){
1570                         memcpy(short_ifname, iface->s, iface->len);
1571                         short_ifname[iface->len]=0; /* make sure it's zero term */
1572                         ifname_len=sizeof(short_ifname);
1573                         ifname=short_ifname;
1574                 }else{
1575                         ifname_len=iface->len;
1576                         ifname=iface->s;
1577                 }
1578                 if (setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE, ifname, ifname_len) <0){
1579                                 ERR("raw_socket: could not bind to %.*s: %s [%d]\n",
1580                                                         iface->len, ZSW(iface->s), strerror(errno), errno);
1581                                 goto error;
1582                 }
1583         }
1584
1585         if(bpf_on) {
1586
1587                 memset(&pf, 0, sizeof(pf));
1588                 pf.len = sizeof(BPF_code) / sizeof(BPF_code[0]);
1589                 pf.filter = (struct sock_filter *) BPF_code;
1590
1591                 if(!port_end) port_end = port_start;
1592                 
1593                 /* Start PORT */
1594                 BPF_code[5]  = (struct sock_filter)BPF_JUMP(0x35, port_start, 0, 1);
1595                 BPF_code[8] = (struct  sock_filter)BPF_JUMP(0x35, port_start, 11, 13);
1596                 BPF_code[16] = (struct sock_filter)BPF_JUMP(0x35, port_start, 0, 1);
1597                 BPF_code[19] = (struct sock_filter)BPF_JUMP(0x35, port_start, 0, 2);
1598                 /* Stop PORT */
1599                 BPF_code[6]  = (struct sock_filter)BPF_JUMP(0x25, port_end, 0, 14);
1600                 BPF_code[17] = (struct sock_filter)BPF_JUMP(0x25, port_end, 0, 3);      
1601                 BPF_code[20] = (struct sock_filter)BPF_JUMP(0x25, port_end, 1, 0);                                                                      
1602         
1603                 /* Attach the filter to the socket */
1604                 if(setsockopt(sock, SOL_SOCKET, SO_ATTACH_FILTER, &pf, sizeof(pf)) < 0 ) {
1605                         ERR(" setsockopt filter: [%s] [%d]\n", strerror(errno), errno);
1606                 }               
1607         }
1608 #endif
1609
1610         if (ip && proto == IPPROTO_IPIP){
1611                 init_su(&su, ip, 0);
1612                 if (bind(sock, &su.s, sockaddru_len(su))==-1){
1613                         ERR("raw_capture_socket: bind(%s) failed: %s [%d]\n",
1614                                 ip_addr2a(ip), strerror(errno), errno);
1615                         goto error;
1616                 }
1617         }
1618
1619         return sock;
1620         
1621 error:
1622         if (sock!=-1) close(sock);
1623         return -1;              
1624                         
1625 }
1626
1627 /* Local raw receive loop */
1628 int raw_capture_rcv_loop(int rsock, int port1, int port2, int ipip) {
1629
1630
1631         static char buf [BUF_SIZE+1];
1632         union sockaddr_union from;
1633         union sockaddr_union to;
1634         struct receive_info ri;
1635         int len;
1636         struct ip *iph;
1637         struct udphdr *udph;
1638         char* udph_start;
1639         unsigned short udp_len;
1640         int offset = 0; 
1641         char* end;
1642         unsigned short dst_port;
1643         unsigned short src_port;
1644         struct ip_addr dst_ip, src_ip;
1645         struct socket_info* si = 0;
1646         int tmp_len;
1647         
1648
1649         for(;;){
1650
1651                 len = recvfrom(rsock, buf, BUF_SIZE, 0x20, 0, 0);
1652
1653                 if (len<0){
1654                         if (len==-1){
1655                                 LOG(L_ERR, "ERROR: raw_moni_rcv_loop:recvfrom: %s [%d]\n",
1656                                                 strerror(errno), errno);
1657                                 if ((errno==EINTR)||(errno==EWOULDBLOCK))
1658                                         continue;
1659                         }else{
1660                                 DBG("raw_moni_rcv_loop: recvfrom error: %d\n", len);
1661                                 continue;
1662                         }
1663                 }
1664
1665                 end=buf+len;
1666                 
1667                 offset =  ipip ? sizeof(struct ip) : ETHHDR;
1668                 
1669                 if (unlikely(len<(sizeof(struct ip)+sizeof(struct udphdr) + offset))) {
1670                         DBG("received small packet: %d. Ignore it\n",len);
1671                         continue;
1672                 }
1673                 
1674                 iph = (struct ip*) (buf + offset);                              
1675
1676                 offset+=iph->ip_hl*4;
1677
1678                 udph_start = buf+offset;
1679                 
1680                 udph = (struct udphdr*) udph_start;
1681                 offset +=sizeof(struct udphdr);
1682
1683                 if (unlikely((buf+offset)>end)){
1684                         continue;                       
1685                 }
1686
1687                 udp_len=ntohs(udph->uh_ulen);
1688                 if (unlikely((udph_start+udp_len)!=end)){
1689                         if ((udph_start+udp_len)>end){
1690                                 continue;
1691                         }else{
1692                                 DBG("udp length too small: %d/%d\n", (int)udp_len, (int)(end-udph_start));
1693                                 continue;
1694                         }
1695                 }
1696                                                                                 
1697                 /* cut off the offset */
1698                 len -= offset;
1699
1700                 if (len<MIN_UDP_PACKET){
1701                         DBG("raw_udp4_rcv_loop: probing packet received from\n");
1702                         continue;
1703                 }
1704
1705                 /* fill dst_port && src_port */
1706                 dst_port=ntohs(udph->uh_dport);
1707                 src_port=ntohs(udph->uh_sport);
1708                                               
1709                 /* if the message has not alpha */
1710                 if(!isalnum((buf+offset)[0])) {
1711                         DBG("not alpha and not digit... skiping...\n");
1712                         continue;
1713                 }
1714                                                         
1715
1716                 DBG("PORT: [%d] and [%d]\n", port1, port2);
1717                 
1718                 if((!port1 && !port2) || (src_port >= port1 && src_port <= port2) 
1719                         || (dst_port >= port1 && dst_port <= port2) 
1720                         || (!port2 && (src_port == port1 || dst_port == port1))) {
1721                         
1722                         /*FIL IPs*/
1723                         dst_ip.af=AF_INET;
1724                         dst_ip.len=4;
1725                         dst_ip.u.addr32[0]=iph->ip_dst.s_addr;
1726
1727                         /* fill dst_port */
1728                         ip_addr2su(&to, &dst_ip, dst_port);
1729
1730                         /* fill src_port */
1731                         src_ip.af=AF_INET;
1732                         src_ip.len=4;
1733                         src_ip.u.addr32[0]=iph->ip_src.s_addr;
1734                         ip_addr2su(&from, &src_ip, src_port);
1735                         su_setport(&from, src_port);
1736         
1737                         ri.src_su=from;
1738                         su2ip_addr(&ri.src_ip, &from);
1739                         ri.src_port=src_port;
1740                         su2ip_addr(&ri.dst_ip, &to);
1741                         ri.dst_port=dst_port;
1742                         ri.proto=PROTO_UDP;                                
1743
1744                         /* a little bit memory */                
1745                         si=(struct socket_info*) pkg_malloc(sizeof(struct socket_info));
1746                         if (si==0) {                                
1747                                 LOG(L_ERR, "ERROR: new_sock_info: memory allocation error\n");
1748                                 return 0;
1749                         }
1750                         
1751                         memset(si, 0, sizeof(struct socket_info));                
1752                         si->address = ri.dst_ip; 
1753                         si->socket=-1;
1754
1755                         /* set port & proto */
1756                         si->port_no = dst_port;
1757                         si->proto=PROTO_UDP;
1758                         si->flags=0;
1759                         si->addr_info_lst=0;
1760                         
1761                         si->port_no_str.s = int2str(si->port_no, &tmp_len);
1762                         si->port_no_str.len = tmp_len;
1763                 
1764                         si->address_str.s = ip_addr2a(&si->address);;
1765                         si->address_str.len = strlen(si->address_str.s);                                
1766                 
1767                         si->name.len = si->address_str.len;
1768                         si->name.s = si->address_str.s;
1769
1770                         ri.bind_address=si;                                             
1771                         
1772
1773                         /* and now recieve message */
1774                         receive_msg(buf+offset, len, &ri);                                        
1775                         if(si) pkg_free(si);                         
1776                 }                                
1777         }
1778
1779         return 0;
1780 }
1781
1782
1783 /* Local raw socket */
1784 int tcp_capture_socket()
1785 {
1786         struct sockaddr_in local;
1787
1788         // open TCP socket
1789         LM_DBG("Starting TCP server on port %d - ", tcp_hep_port);
1790
1791         if ((tcp_hep_socket=socket(AF_INET, SOCK_STREAM, 0)) < 0) {
1792                 LM_ERR("tcp socket error");
1793                 exit(errno);
1794         }
1795
1796         local.sin_family=AF_INET;
1797         // listen on port <server_port>
1798         local.sin_port=htons(tcp_hep_port);
1799         // listen on any ip interface
1800         local.sin_addr.s_addr=htonl(INADDR_ANY);
1801         memset(&local.sin_zero, 0, sizeof(local.sin_zero));
1802
1803         // bind and listen on port and ip interface
1804         if (bind(tcp_hep_socket, (struct sockaddr*)&local, sizeof(local)) < 0) {
1805                 LM_ERR("tcp bind error");
1806                 return -1;
1807         }
1808         if (listen(tcp_hep_socket, 15) < 0) {
1809                 LM_ERR("tcp listen error");
1810                 return -1;
1811         }
1812
1813         LM_DBG("TCP HEPV3 success\n");
1814
1815         return 1;
1816 }
1817
1818 /* Local raw socket */
1819 int init_tcp_listen_children()
1820 {
1821         int fdd;
1822         struct sockaddr_in remote;
1823         int rlen, i;
1824         pid_t pid;
1825
1826         for(i = 0; i < hep_tcp_sock_children; i++) {
1827                 pid = fork_process(PROC_UNIXSOCK,"homer tcp socket", 1);
1828                 if (pid < 0) {
1829                         ERR("Unable to fork: %s\n", strerror(errno));
1830                         return -1;
1831                 } else if (pid == 0) { /* child */
1832                         while(1) {
1833                                 rlen=sizeof(remote);
1834                                 // accept connection
1835                                 if ((fdd=accept(tcp_hep_socket, (struct sockaddr*)&remote, (socklen_t *)&rlen)) < 0) {
1836                                         LM_ERR("accept error");
1837                                         return -1;
1838                                 }               
1839
1840                                 get_tcp_stream(fdd);            
1841                         }
1842                 }
1843                 /* Parent */
1844         }
1845         
1846         return 1;
1847 }
1848
1849 /*
1850  *  TCP listeners
1851  */
1852 int get_tcp_stream(int tcp_sock_desc)
1853 {
1854
1855         if(fork_on_accept) {
1856         
1857                 // create child to be able to get multiple connections
1858                 switch(fork()) {
1859                         case -1: 
1860                                 LM_ERR("Unable to fork: %s\n", strerror(errno));
1861                                 return -1;                      
1862                         case 0:
1863                                 tcp_capture_rcv_loop(tcp_sock_desc);
1864                                 exit(0);
1865                         default:
1866                                 // parent process: prepare for new connections
1867                                 close(tcp_sock_desc);
1868                                 break;          
1869                 }
1870         }
1871         else {
1872                 
1873               tcp_capture_rcv_loop(tcp_sock_desc);
1874               
1875         }
1876         
1877         LM_DBG("Raw TCP socket server successfully initialized\n");
1878         return 1;
1879 }
1880
1881
1882 /* Local raw receive loop */
1883 int tcp_capture_rcv_loop(int tsock) {
1884
1885         char *msgtmp = NULL;
1886         static char recvtmp[3000];
1887         int blen;
1888         struct hep_ctrl *hep_header;
1889         int left_length = 0;        
1890         unsigned int total_length = 0;
1891
1892         while ((blen=read(tsock, recvtmp, 6))>0) {
1893         
1894                 hep_header = NULL;
1895
1896                 memset(&hep_header, 0, sizeof(struct hep_ctrl));
1897                 
1898                 if(!memcmp(recvtmp, "\x48\x45\x50\x33", 4)) {
1899                                 
1900                         hep_header = (struct hep_ctrl*) recvtmp;
1901                         total_length = ntohs(hep_header->length);
1902                         left_length = total_length - blen;
1903                               
1904                         //LM_ERR("RD: TL:[%d] LL:[%d] NT: [%d]\n", total_length, left_length, hep_header->length);
1905
1906                         msgtmp =  pkg_malloc(total_length+1);
1907                         if(msgtmp==NULL) {
1908                                 LM_ERR("msgtmp: no more pkg memory left\n");
1909                                 return -1;
1910                         }
1911
1912                         memset(msgtmp, 0, (total_length+1));
1913                                 
1914                         /* Copy to our buffer*/
1915                         memcpy(msgtmp, recvtmp, blen);                          
1916
1917                         while ((blen=read(tsock, recvtmp, left_length))>0) {                              
1918                                                                         
1919                                 memcpy(msgtmp+(total_length-left_length), recvtmp, blen);       
1920                                 left_length-=blen;                                                              
1921                                 if(left_length <= 0) break;                                                           
1922                         }
1923
1924                         
1925                         if(!parsing_hepv3_message(msgtmp, &total_length)) {
1926                                 goto error;
1927                                                         
1928                         }                                                
1929
1930                         if(msgtmp) pkg_free(msgtmp);                              
1931                 }
1932         }
1933
1934         return 0;
1935 error:
1936         if(msgtmp) pkg_free(msgtmp);
1937         if(tsock) close(tsock);
1938         return -1;                      
1939 }
1940
1941
1942 int parsing_hepv3_message(char *buf, unsigned int *blen) {
1943
1944         union sockaddr_union from;
1945         union sockaddr_union to;
1946         struct receive_info ri;
1947         char *tmp;
1948         struct ip_addr dst_ip, src_ip;
1949         struct socket_info* si = 0;
1950         int tmp_len, i;
1951         char *payload = NULL;
1952         struct hep_chunk *chunk;        
1953         struct hep_generic_recv *hg;
1954         int totelem = 0;
1955         int chunk_vendor=0, chunk_type=0, chunk_length=0;
1956         int total_length = 0;
1957
1958
1959         hg = (struct hep_generic_recv*)pkg_malloc(sizeof(struct hep_generic_recv));
1960         if(hg==NULL) {
1961                 LM_ERR("no more pkg memory left for hg\n");
1962                 return -1;
1963         }
1964                                                                         
1965         memset(hg, 0, sizeof(struct hep_generic_recv));
1966         
1967                 
1968         /* HEADER */
1969         hg->header  = (hep_ctrl_t *) (buf);
1970
1971         /*Packet size */
1972         total_length = ntohs(hg->header->length);
1973
1974         ri.src_port = 0;
1975         ri.dst_port = 0;
1976         dst_ip.af = 0;
1977         src_ip.af = 0;
1978                                 
1979         payload = NULL;
1980
1981         i = sizeof(hep_ctrl_t);         
1982                 
1983         while(i < total_length) {
1984                 
1985                 /*OUR TMP DATA */                                  
1986                 tmp = buf+i;
1987
1988                 chunk = (struct hep_chunk*) tmp;
1989                              
1990                 chunk_vendor = ntohs(chunk->vendor_id);                             
1991                 chunk_type = ntohs(chunk->type_id);
1992                 chunk_length = ntohs(chunk->length);
1993                        
1994
1995
1996                 /* if chunk_length */
1997                 if(chunk_length == 0) {
1998                         /* BAD LEN we drop this packet */
1999                         goto error;
2000                 }
2001
2002                 /* SKIP not general Chunks */
2003                 if(chunk_vendor != 0) {
2004                         i+=chunk_length;
2005                 }
2006                 else {                                                                                                                               
2007                         switch(chunk_type) {
2008                                      
2009                                 case 0:
2010                                         goto error;
2011                                         break;
2012                                      
2013                                 case 1:                                                                          
2014                                         hg->ip_family  = (hep_chunk_uint8_t *) (tmp);
2015                                         i+=chunk_length;
2016                                         totelem++;
2017                                         break;
2018                                 case 2:
2019                                         hg->ip_proto  = (hep_chunk_uint8_t *) (tmp);
2020                                         i+=chunk_length;
2021                                         totelem++;
2022                                         break;                                                     
2023                                 case 3:
2024                                         hg->hep_src_ip4  = (hep_chunk_ip4_t *) (tmp);
2025                                         i+=chunk_length;
2026                                         src_ip.af=AF_INET;
2027                                         src_ip.len=4;
2028                                         src_ip.u.addr32[0] = hg->hep_src_ip4->data.s_addr;
2029                                         totelem++;
2030                                         break;
2031                                 case 4:
2032                                         hg->hep_dst_ip4  = (hep_chunk_ip4_t *) (tmp);
2033                                         i+=chunk_length;                                                     
2034                                         dst_ip.af=AF_INET;
2035                                         dst_ip.len=4;
2036                                         dst_ip.u.addr32[0] = hg->hep_dst_ip4->data.s_addr;
2037                                         totelem++;
2038
2039                                         break;
2040 #ifdef USE_IPV6                                                     
2041                                 case 5:
2042                                         hg->hep_src_ip6  = (hep_chunk_ip6_t *) (tmp);
2043                                         i+=chunk_length;
2044                                         src_ip.af=AF_INET6;
2045                                         src_ip.len=16;
2046                                         memcpy(src_ip.u.addr, &hg->hep_src_ip6->data, 16);
2047                                         totelem++;
2048                                         break;
2049                                 case 6:
2050                                         hg->hep_dst_ip6  = (hep_chunk_ip6_t *) (tmp);
2051                                         i+=chunk_length;                                                     
2052                                         dst_ip.af=AF_INET6;
2053                                         dst_ip.len=16;
2054                                         memcpy(dst_ip.u.addr, &hg->hep_dst_ip6->data, 16);
2055                                         totelem++;
2056                                         break;
2057 #endif                                             
2058         
2059                                 case 7:
2060                                         hg->src_port  = (hep_chunk_uint16_t *) (tmp);
2061                                         ri.src_port = ntohs(hg->src_port->data);
2062                                         i+=chunk_length;                      
2063                                         totelem++;
2064                                         break;
2065
2066                                 case 8:
2067                                         hg->dst_port  = (hep_chunk_uint16_t *) (tmp);
2068                                         ri.dst_port = ntohs(hg->dst_port->data);
2069                                         i+=chunk_length;
2070                                         totelem++;
2071                                         break;
2072                                 case 9:
2073                                         hg->time_sec  = (hep_chunk_uint32_t *) (tmp);
2074                                         hg->time_sec->data = ntohl(hg->time_sec->data);
2075                                         i+=chunk_length;
2076                                         totelem++;
2077                                         break;                                                     
2078                                                      
2079                                 case 10:
2080                                         hg->time_usec  = (hep_chunk_uint32_t *) (tmp);
2081                                         hg->time_usec->data = ntohl(hg->time_usec->data);
2082                                         i+=chunk_length;
2083                                         totelem++;
2084                                         break;      
2085
2086                                 case 11:
2087                                         hg->proto_t  = (hep_chunk_uint8_t *) (tmp);
2088                                         i+=chunk_length;
2089                                         totelem++;
2090                                         break;                                                                                                                                                         
2091
2092                                 case 12:
2093                                         hg->capt_id  = (hep_chunk_uint32_t *) (tmp);
2094                                         i+=chunk_length;
2095                                         totelem++;
2096                                         break;
2097
2098                                 case 13:
2099                                         hg->keep_tm  = (hep_chunk_uint16_t *) (tmp);
2100                                         i+=chunk_length;
2101                                         break;                                                     
2102
2103                                 case 14:
2104                                         hg->auth_key  = (hep_chunk_str_t *) (tmp);
2105                                         i+=chunk_length;                                                                             
2106                                         break;
2107                                                      
2108                                 case 15:
2109                                         hg->payload_chunk  = (hep_chunk_t *) (tmp);
2110                                         payload = (char *) tmp+sizeof(hep_chunk_t);
2111                                         i+=chunk_length;
2112                                         totelem++;
2113                                         break;
2114                                                      
2115                                 default:
2116                                         i+=chunk_length;
2117                                         break;
2118                         }                                        
2119                 }
2120         }                                                                                                                 
2121                         
2122         /* CHECK how much elements */
2123         if(totelem < 9) {                        
2124                 LM_ERR("Not all elements [%d]\n", totelem);                        
2125                 goto done;
2126         }                 
2127
2128         if ( dst_ip.af == 0 || src_ip.af == 0)  {
2129                 LM_ERR("NO IP's set\n");
2130                 goto done;
2131         }
2132
2133                         
2134         ip_addr2su(&to, &dst_ip, ri.dst_port);
2135         ip_addr2su(&from, &src_ip, ri.src_port);
2136                         
2137         ri.src_su=from;
2138         su2ip_addr(&ri.src_ip, &from);
2139         su2ip_addr(&ri.dst_ip, &to);
2140
2141         if(hg->ip_proto->data == IPPROTO_TCP) ri.proto=PROTO_TCP;
2142         else if(hg->ip_proto->data == IPPROTO_UDP) ri.proto=PROTO_UDP;
2143
2144         /* a little bit memory */
2145         si=(struct socket_info*) pkg_malloc(sizeof(struct socket_info));
2146         if (si==0) {
2147                 LOG(L_ERR, "ERROR: new_sock_info: memory allocation error\n");
2148                 goto error;
2149         }
2150
2151         memset(si, 0, sizeof(struct socket_info));
2152         si->address = ri.dst_ip;
2153         si->socket=-1;
2154
2155         /* set port & proto */
2156         si->port_no = ri.dst_port;
2157
2158         if(hg->ip_proto->data == IPPROTO_TCP) si->proto=PROTO_TCP;
2159         else if(hg->ip_proto->data == IPPROTO_UDP) si->proto=PROTO_UDP;
2160
2161         si->flags=0;
2162         si->addr_info_lst=0;
2163
2164         si->address_str.s = ip_addr2a(&si->address);;
2165         si->address_str.len = strlen(si->address_str.s);                                                
2166
2167         si->port_no_str.s = int2str(si->port_no, &tmp_len);
2168         si->port_no_str.len = tmp_len;
2169         si->address_str.len = strlen(si->address_str.s);
2170
2171         si->name.len = si->address_str.len;
2172         si->name.s = si->address_str.s;
2173         ri.bind_address=si;
2174
2175
2176         /*TIME*/ 
2177         heptime->tv_sec = hg->time_sec->data;
2178         heptime->tv_usec = hg->time_usec->data;
2179         heptime->captid = ntohs(hg->capt_id->data);
2180           
2181  
2182         if(payload != NULL ) {
2183                 /* and now recieve message */
2184                 receive_msg(payload, ntohs(hg->payload_chunk->length), &ri);
2185         }
2186         
2187 done:
2188         if(si) pkg_free(si);
2189         if(hg) pkg_free(hg);                     
2190
2191         return 1;
2192         
2193 error:
2194
2195         if(si) pkg_free(si);
2196         if(hg) pkg_free(hg);
2197                 
2198         return -1;           
2199         
2200 }
2201