core: more debug messages when matching myself
[sip-router] / src / core / forward.c
1 /*
2  * Copyright (C) 2001-2003 FhG Fokus
3  *
4  * This file is part of Kamailio, a free SIP server.
5  *
6  * Kamailio is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version
10  *
11  * Kamailio is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  */
21
22 /*!
23  * \file
24  * \brief Kamailio core :: Message forwarding
25  * \ingroup core
26  * Module: \ref core
27  */
28
29
30
31 #include <string.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <sys/types.h>
35 #include <sys/socket.h>
36 #include <netdb.h>
37 #include <netinet/in.h>
38 #include <arpa/inet.h>
39
40 #include "forward.h"
41 #include "hash_func.h"
42 #include "config.h"
43 #include "parser/msg_parser.h"
44 #include "char_msg_val.h"
45 #include "route.h"
46 #include "events.h"
47 #include "dprint.h"
48 #include "globals.h"
49 #include "cfg_core.h"
50 #include "data_lump.h"
51 #include "ut.h"
52 #include "mem/mem.h"
53 #include "crypto/md5utils.h"
54 #include "msg_translator.h"
55 #include "sr_module.h"
56 #include "ip_addr.h"
57 #include "resolve.h"
58 #include "name_alias.h"
59 #include "socket_info.h"
60 #include "onsend.h"
61 #include "resolve.h"
62 #ifdef USE_DNS_FAILOVER
63 #include "dns_cache.h"
64 #endif
65 #ifdef USE_DST_BLACKLIST
66 #include "dst_blacklist.h"
67 #endif
68 #include "compiler_opt.h"
69 #include "core_stats.h"
70
71 #ifdef DEBUG_DMALLOC
72 #include <dmalloc.h>
73 #endif
74
75
76
77 /* return a socket_info_pointer to the sending socket; as opposed to
78  * get_send_socket, which returns process's default socket, get_out_socket
79  * attempts to determine the outbound interface which will be used;
80  * it uses a temporary connected socket to determine it; it will
81  * be very likely noticeably slower, but it can deal better with
82  * multihomed hosts
83  */
84
85 static int mhomed_sock_cache_disabled = 0;
86 static int sock_inet = -1;
87 static int sock_inet6 = -1;
88 static int _forward_set_send_info = 0;
89
90 void forward_set_send_info(int v)
91 {
92         _forward_set_send_info = v;
93 }
94
95 static void apply_force_send_socket(struct dest_info* dst, struct sip_msg* msg);
96
97 struct socket_info* get_out_socket(union sockaddr_union* to, int proto)
98 {
99         int* temp_sock;
100         socklen_t len;
101         union sockaddr_union from;
102         struct socket_info* si;
103         struct ip_addr ip;
104         union sockaddr_union uncon;
105
106         memset(&uncon, 0, sizeof(union sockaddr_union));
107         uncon.sin.sin_family = AF_UNSPEC;
108
109         if (unlikely(proto!=PROTO_UDP)) {
110                 LM_CRIT("can only be called for UDP\n");
111                 return 0;
112         }
113 retry:
114         switch(to->s.sa_family){
115         case AF_INET : {
116                 if(unlikely(sock_inet < 0)){
117                         sock_inet = socket(AF_INET, SOCK_DGRAM, 0);
118                         if (sock_inet==-1) {
119                                 LM_ERR("socket() failed: %s\n", strerror(errno));
120                                 return 0;
121                         }
122                 }
123                 temp_sock = &sock_inet;
124                 break;
125         }
126         case AF_INET6 : {
127                 if(unlikely(sock_inet6 < 0)){
128                         sock_inet6 = socket(AF_INET6, SOCK_DGRAM, 0);
129                         if (sock_inet6==-1) {
130                                 LM_ERR("socket() failed: %s\n", strerror(errno));
131                                 return 0;
132                         }
133                 }
134                 temp_sock = &sock_inet6;
135                 break;
136         }
137         default: {
138                 LM_ERR("Unknown protocol family \n");
139                 return 0;
140         }
141         }
142
143         if( !mhomed_sock_cache_disabled ){
144                 /* some Linux kernel versions (all?) along with other UNIXes don't re-bound the sock if already bound */
145                 /* to un-bound a socket set sin_family to AF_UNSPEC and zero out the rest*/
146                 if (unlikely(connect(*temp_sock, &uncon.s, sockaddru_len(uncon)) < 0))
147                                 mhomed_sock_cache_disabled = 1;
148         }
149
150         if (unlikely(connect(*temp_sock, &to->s, sockaddru_len(*to))==-1)) {
151                 if (unlikely(errno==EISCONN && !mhomed_sock_cache_disabled)){
152                         /*  no multiple connects support on the same socket */
153                         mhomed_sock_cache_disabled=1;
154                         if (sock_inet>=0){
155                                 close(sock_inet);
156                                 sock_inet=-1;
157                         }
158                         if (sock_inet6>=0){
159                                 close(sock_inet6);
160                                 sock_inet6=-1;
161                         }
162                         goto retry;
163                 }
164                 LM_ERR("connect failed: %s\n", strerror(errno));
165                 goto error;
166         }
167         len=sizeof(from);
168         if (unlikely(getsockname(*temp_sock, &from.s, &len)==-1)) {
169                 LM_ERR("getsockname failed: %s\n", strerror(errno));
170                 goto error;
171         }
172         su2ip_addr(&ip, &from);
173         si=find_si(&ip, 0, proto);
174         if (si==0) goto error;
175         LM_DBG("socket determined: %p\n", si );
176         if (unlikely(mhomed_sock_cache_disabled)){
177                 close(*temp_sock);
178                 *temp_sock=-1;
179         }
180         return si;
181 error:
182         LM_ERR("no socket found\n");
183         ERR("no corresponding socket found for(%s:%s)\n",
184                         proto2a(proto), su2a(to, sizeof(*to)));
185         if (unlikely(mhomed_sock_cache_disabled && *temp_sock >=0)){
186                 close(*temp_sock);
187                 *temp_sock=-1;
188         }
189         return 0;
190 }
191
192
193
194 /** get the sending socket for a corresponding destination.
195  * @param force_send_socket - if !=0 and the protocol and af correspond
196  *                            with the destination, it will be returned.
197  *                            If the protocol or af check fail, a look-alike
198  *                            socket will be searched for and mismatch will be
199  *                            set. If no look-alike socket is found it will
200  *                            fallback to normal resolution.
201  * @param to - destination
202  * @param proto - protocol
203  * @param mismatch - result parameter, set if a force_send_socket was used, but
204  *                   there was an error matching it exactly to the destination.
205  *                   Possible values: 0 ok, SS_MISMATCH_PROTO,
206  *                   SS_MISMATCH_ADDR, SS_MISMATCH_AF, SS_MISMATCH_MCAST.
207  * @return a socket_info pointer to the sending socket on success (and possibly
208  *         sets mismatch) or 0 on error.
209  */
210 struct socket_info* get_send_socket2(struct socket_info* force_send_socket,
211                                                                                 union sockaddr_union* to, int proto,
212                                                                                 enum ss_mismatch* mismatch)
213 {
214         struct socket_info* send_sock;
215         struct socket_info* orig;
216
217         if (likely(mismatch)) *mismatch=0;
218         /* check if send interface is not forced */
219         if (unlikely(force_send_socket)){
220                 orig=force_send_socket;
221                 /* Special case here as there is no ;transport=wss - so wss connections
222                  * will appear as ws ones and be sorted out in the WebSocket module */
223                 if (unlikely(orig->proto!=proto && !(orig->proto==PROTO_TLS && proto==PROTO_WS))){
224                         force_send_socket=find_si(&(force_send_socket->address),
225                                                                                         force_send_socket->port_no,
226                                                                                         proto);
227                         if (unlikely(force_send_socket == 0)){
228                                 if (likely(mismatch)) *mismatch=SS_MISMATCH_ADDR;
229                                 LM_WARN("protocol/port mismatch (forced %s:%s:%d, to %s:%s)\n",
230                                                 proto2a(orig->proto), ip_addr2a(&orig->address),
231                                                 orig->port_no,
232                                                 proto2a(proto), su2a(to, sizeof(*to)));
233                                 goto not_forced;
234                         }
235                         if (likely(mismatch)) *mismatch=SS_MISMATCH_PROTO;
236                 }
237                 if (unlikely(force_send_socket->address.af!=to->s.sa_family)){
238                         LM_DBG("force_send_socket of different af"
239                                         " (dst %d - %s:%s forced %d -%s:%s:%d)\n",
240                                         to->s.sa_family, proto2a(proto), su2a(to, sizeof(*to)),
241                                         force_send_socket->address.af,
242                                         proto2a(force_send_socket->proto),
243                                         ip_addr2a(&force_send_socket->address),
244                                         force_send_socket->port_no);
245                         if (likely(mismatch)) *mismatch=SS_MISMATCH_AF;
246                         goto not_forced;
247                 }
248                 /* check if listening on the socket (the check does not work
249                  * for TCP and TLS, for them socket==-1 on all the processes
250                  * except tcp_main(), see close_extra_socks() */
251                 if (likely((force_send_socket->socket!=-1 ||
252                                                 force_send_socket->proto==PROTO_TCP ||
253                                                 force_send_socket->proto==PROTO_TLS ||
254                                                 force_send_socket->proto==PROTO_WS  ||
255                                                 force_send_socket->proto==PROTO_WSS) &&
256                                         !(force_send_socket->flags & SI_IS_MCAST)))
257                                 return force_send_socket;
258                 else{
259                         if (!(force_send_socket->flags & SI_IS_MCAST))
260                                 LM_WARN("not listening on the requested socket (%s:%s:%d),"
261                                                         " no fork mode?\n",
262                                                         proto2a(force_send_socket->proto),
263                                                         ip_addr2a(&force_send_socket->address),
264                                                         force_send_socket->port_no);
265                         else if (likely(mismatch)) *mismatch=SS_MISMATCH_MCAST;
266                 }
267         };
268 not_forced:
269         if (mhomed && proto==PROTO_UDP){
270                 send_sock=get_out_socket(to, proto);
271                 if ((send_sock==0) || (send_sock->socket!=-1))
272                         return send_sock; /* found or error*/
273                 else if (send_sock->socket==-1){
274                         LM_WARN("not listening on the"
275                                         " requested socket (%s:%s:%d), no fork mode?\n",
276                                         proto2a(send_sock->proto), ip_addr2a(&send_sock->address),
277                                         send_sock->port_no);
278                         /* continue: try to use some socket */
279                 }
280         }
281
282         send_sock=0;
283         /* check if we need to change the socket (different address families -
284          * eg: ipv4 -> ipv6 or ipv6 -> ipv4) */
285         switch(proto){
286 #ifdef USE_TCP
287                 case PROTO_WS:
288                 case PROTO_TCP:
289                 /* on tcp just use the "main address", we don't really now the
290                  * sending address (we can find it out, but we'll need also to see
291                  * if we listen on it, and if yes on which port -> too complicated*/
292                         switch(to->s.sa_family){
293                                 /* FIXME */
294                                 case AF_INET:   send_sock=sendipv4_tcp;
295                                                                 break;
296                                 case AF_INET6:  send_sock=sendipv6_tcp;
297                                                                 break;
298                                 default:        LM_ERR("don't know how to forward to af %d\n",
299                                                                         to->s.sa_family);
300                         }
301                         break;
302 #endif
303 #ifdef USE_TLS
304                 case PROTO_WSS:
305                 case PROTO_TLS:
306                         switch(to->s.sa_family){
307                                 /* FIXME */
308                                 case AF_INET:   send_sock=sendipv4_tls;
309                                                                 break;
310                                 case AF_INET6:  send_sock=sendipv6_tls;
311                                                                 break;
312                                 default:        LM_ERR("don't know how to forward to af %d\n",
313                                                                         to->s.sa_family);
314                         }
315                         break;
316 #endif /* USE_TLS */
317 #ifdef USE_SCTP
318                 case PROTO_SCTP:
319                         if ((bind_address==0) ||
320                                         (to->s.sa_family!=bind_address->address.af) ||
321                                         (bind_address->proto!=PROTO_SCTP)){
322                                 switch(to->s.sa_family){
323                                         case AF_INET:   send_sock=sendipv4_sctp;
324                                                                         break;
325                                         case AF_INET6:  send_sock=sendipv6_sctp;
326                                                                         break;
327                                         default:        LM_ERR("don't know how to forward to af %d\n",
328                                                                                 to->s.sa_family);
329                                 }
330                         }else send_sock=bind_address;
331                         break;
332 #endif /* USE_SCTP */
333                 case PROTO_UDP:
334                         if ((bind_address==0) ||
335                                         (to->s.sa_family!=bind_address->address.af) ||
336                                         (bind_address->proto!=PROTO_UDP)){
337                                 switch(to->s.sa_family){
338                                         case AF_INET:   send_sock=sendipv4;
339                                                                         break;
340                                         case AF_INET6:  send_sock=sendipv6;
341                                                                         break;
342                                         default:        LM_ERR("don't know how to forward to af %d\n",
343                                                                                 to->s.sa_family);
344                                 }
345                         }else send_sock=bind_address;
346                         break;
347                 default:
348                         LM_CRIT("unsupported proto %d (%s)\n", proto, proto2a(proto));
349         }
350         return send_sock;
351 }
352
353 static struct _check_self_func {
354         check_self_f fself;
355         struct _check_self_func *next;
356 } *_check_self_func_list = NULL;
357
358 /** check if _check_self_func_list is set
359  * - return 1 if yes, 0 if no
360  */
361 int is_check_self_func_list_set(void)
362 {
363         return (_check_self_func_list)?1:0;
364 }
365
366 /** register a function to be called when matching for myself
367  * - return 0 on success, -1 on error
368  * - f must have same prototype as check_self() and return same kind of values
369  */
370 int register_check_self_func(check_self_f f)
371 {
372         struct _check_self_func *nf = 0;
373         nf=(struct _check_self_func*)pkg_malloc(sizeof(struct _check_self_func));
374         if(nf==0)
375         {
376                 PKG_MEM_ERROR;
377                 return -1;
378         }
379         nf->fself = f;
380         nf->next = _check_self_func_list;
381         _check_self_func_list = nf;
382         return 0;
383 }
384
385 /** run registered check self functions
386  * returns 1 if true, 0 if false
387  */
388 int run_check_self_func(str* host, unsigned short port, unsigned short proto)
389 {
390         struct _check_self_func *sf = 0;
391
392         if(_check_self_func_list==NULL)
393                 return 0;
394         for(sf=_check_self_func_list; sf; sf=sf->next)
395                 if(sf->fself(host, port, proto)==1)
396                         return 1;
397         return 0;
398 }
399
400 /** checks if the proto: host:port is one of the address we listen on;
401  *
402  * if port==0, the  port number is ignored
403  * if proto==0 (PROTO_NONE) the protocol is ignored
404  * returns 1 if true, 0 if false, -1 on error
405  * WARNING: uses str2ip6 so it will overwrite any previous
406  *  unsaved result of this function (static buffer)
407  */
408 int check_self(str* host, unsigned short port, unsigned short proto)
409 {
410         int ret = 1;
411         if (grep_sock_info(host, port, proto)) {
412                 goto done;
413         }
414         /* try to look into the aliases*/
415         if (grep_aliases(host->s, host->len, port, proto)==0) {
416                 ret = (_check_self_func_list==NULL)?0:run_check_self_func(host,
417                                         port, proto);
418         }
419
420 done:
421         if(ret==1) {
422                 LM_DBG("host (%d:%.*s:%d) == me\n", proto, host->len, host->s, port);
423         } else {
424                 LM_DBG("host (%d:%.*s:%d) != me\n", proto, host->len, host->s, port);
425         }
426         return ret;
427 }
428
429 /** checks if the proto:port is one of the ports we listen on;
430  * if proto==0 (PROTO_NONE) the protocol is ignored
431  * returns 1 if true, 0 if false, -1 on error
432  */
433 int check_self_port(unsigned short port, unsigned short proto)
434 {
435         /* aliases do not contain different ports we can skip them */
436         if (grep_sock_info_by_port(port, proto)) {
437                 LM_DBG("proto:port (%d:%d) == me\n", proto, port);
438                 return 1;
439         } else {
440                 LM_DBG("proto:port (%d:%d) != me\n", proto, port);
441                 return 0;
442         }
443 }
444
445
446
447 /** forwards a request to dst
448  * parameters:
449  *   msg       - sip msg
450  *   dst       - destination name, if non-null it will be resolved and
451  *               send_info updated with the ip/port. Even if dst is non
452  *               null send_info must contain the protocol and if a non
453  *               default port or non srv. lookup is desired, the port must
454  *               be !=0
455  *   port      - used only if dst!=0 (else the port in send_info->to is used)
456  *   send_info - value/result partially filled dest_info structure:
457  *                 - send_info->proto and comp are used
458  *                 - send_info->to will be filled (dns)
459  *                 - send_info->send_flags is filled from the message
460  *                 - if the send_socket member is null, a send_socket will be
461  *                   chosen automatically
462  * WARNING: don't forget to zero-fill all the  unused members (a non-zero
463  * random id along with proto==PROTO_TCP can have bad consequences, same for
464  *   a bogus send_socket value)
465  *
466  * return: 0 (E_OK) on success; negative (E_*) on failure
467  */
468 int forward_request(struct sip_msg* msg, str* dst, unsigned short port,
469                                                         struct dest_info* send_info)
470 {
471         unsigned int len;
472         char* buf;
473         char md5[MD5_LEN];
474         struct socket_info* orig_send_sock; /* initial send_sock */
475         int ret;
476         struct ip_addr ip; /* debugging only */
477         char proto;
478         struct onsend_info onsnd_info = {0};
479 #ifdef USE_DNS_FAILOVER
480         struct socket_info* prev_send_sock;
481         int err;
482         struct dns_srv_handle dns_srv_h;
483
484         prev_send_sock=0;
485         err=0;
486         memset(&dns_srv_h, 0, sizeof(struct dns_srv_handle));
487 #endif
488
489         buf=0;
490         orig_send_sock=send_info->send_sock;
491         proto=send_info->proto;
492         ret=0;
493
494         if(dst){
495 #ifdef USE_DNS_FAILOVER
496                 if (cfg_get(core, core_cfg, use_dns_failover)){
497                         dns_srv_handle_init(&dns_srv_h);
498                         err=dns_sip_resolve2su(&dns_srv_h, &send_info->to, dst, port,
499                                                                         &proto, dns_flags);
500                         if (err!=0){
501                                 LM_ERR("resolving \"%.*s\" failed: %s [%d]\n",
502                                                 dst->len, ZSW(dst->s), dns_strerror(err), err);
503                                 ret=E_BAD_ADDRESS;
504                                 goto error;
505                         }
506                 }else
507 #endif
508                 if (sip_hostport2su(&send_info->to, dst, port, &proto)<0){
509                         LM_ERR("bad host name %.*s, dropping packet\n", dst->len, ZSW(dst->s));
510                         ret=E_BAD_ADDRESS;
511                         goto error;
512                 }
513         }/* dst */
514         send_info->send_flags=msg->fwd_send_flags;
515         /* calculate branch for outbound request;
516          * calculate is from transaction key, i.e., as an md5 of From/To/CallID/
517          * CSeq exactly the same way as TM does; good for reboot -- than messages
518          * belonging to transaction lost due to reboot will still be forwarded
519          * with the same branch parameter and will be match-able downstream
520          */
521         if (!char_msg_val( msg, md5 ))  { /* parses transaction key */
522                 LM_ERR("char_msg_val failed\n");
523                 ret=E_UNSPEC;
524                 goto error;
525         }
526         msg->hash_index=hash( msg->callid->body, get_cseq(msg)->number);
527         if (!branch_builder( msg->hash_index, 0, md5, 0 /* 0-th branch */,
528                                 msg->add_to_branch_s, &msg->add_to_branch_len )) {
529                 LM_ERR("branch_builder failed\n");
530                 ret=E_UNSPEC;
531                 goto error;
532         }
533         /* try to send the message until success or all the ips are exhausted
534          *  (if dns lookup is performed && the dns cache used ) */
535 #ifdef USE_DNS_FAILOVER
536         do{
537 #endif
538                 if (orig_send_sock==0) /* no forced send_sock => find it **/
539                         send_info->send_sock=get_send_socket(msg, &send_info->to, proto);
540                 if (send_info->send_sock==0){
541                         LM_ERR("cannot forward to af %d, proto %d "
542                                                 "no corresponding listening socket\n",
543                                                 send_info->to.s.sa_family, proto);
544                         ret=ser_error=E_NO_SOCKET;
545 #ifdef USE_DNS_FAILOVER
546                         /* continue, maybe we find a socket for some other ip */
547                         continue;
548 #else
549                         goto error;
550 #endif
551                 }
552
553 #ifdef USE_DNS_FAILOVER
554                 if (prev_send_sock!=send_info->send_sock){
555                         /* rebuild the message only if the send_sock changed */
556                         prev_send_sock=send_info->send_sock;
557 #endif
558                         if (buf) pkg_free(buf);
559                         send_info->proto=proto;
560                         buf = build_req_buf_from_sip_req(msg, &len, send_info, 0);
561                         if (!buf){
562                                 LM_ERR("building failed\n");
563                                 ret=E_OUT_OF_MEM; /* most probable */
564                                 goto error;
565                         }
566 #ifdef USE_DNS_FAILOVER
567                 }
568 #endif
569                 /* send it! */
570                 LM_DBG("Sending:\n%.*s.\n", (int)len, buf);
571                 LM_DBG("orig. len=%d, new_len=%d, proto=%d\n",
572                                 msg->len, len, send_info->proto );
573
574                 if (run_onsend(msg, send_info, buf, len)==0){
575                         su2ip_addr(&ip, &send_info->to);
576                         LM_INFO("request to %s:%d(%d) dropped (onsend_route)\n",
577                                 ip_addr2a(&ip), su_getport(&send_info->to), send_info->proto);
578                         ser_error=E_OK; /* no error */
579                         ret=E_ADM_PROHIBITED;
580 #ifdef USE_DNS_FAILOVER
581                         continue; /* try another ip */
582 #else
583                         goto error; /* error ? */
584 #endif
585                 }
586 #ifdef USE_DST_BLACKLIST
587                 if (cfg_get(core, core_cfg, use_dst_blacklist)){
588                         if (dst_is_blacklisted(send_info, msg)){
589                                 su2ip_addr(&ip, &send_info->to);
590                                 LM_DBG("blacklisted destination:%s:%d (%d)\n",
591                                         ip_addr2a(&ip), su_getport(&send_info->to), send_info->proto);
592                                 ret=ser_error=E_SEND;
593 #ifdef USE_DNS_FAILOVER
594                                 continue; /* try another ip */
595 #else
596                                 goto error;
597 #endif
598                         }
599                 }
600 #endif
601
602                 if(unlikely(_forward_set_send_info==1)) {
603                         onsnd_info.to=&send_info->to;
604                         onsnd_info.send_sock=send_info->send_sock;
605                         onsnd_info.buf=buf;
606                         onsnd_info.len=len;
607                         onsnd_info.msg=msg;
608                         p_onsend=&onsnd_info;
609                 }
610
611                 if (msg_send(send_info, buf, len)<0){
612                         p_onsend=0;
613                         ret=ser_error=E_SEND;
614 #ifdef USE_DST_BLACKLIST
615                         (void)dst_blacklist_add(BLST_ERR_SEND, send_info, msg);
616 #endif
617 #ifdef USE_DNS_FAILOVER
618                         continue; /* try another ip */
619 #else
620                         goto error;
621 #endif
622                 }else{
623                         p_onsend=0;
624                         ret=ser_error=E_OK;
625                         /* exit succcesfully */
626                         goto end;
627                 }
628 #ifdef USE_DNS_FAILOVER
629         }while(dst && cfg_get(core, core_cfg, use_dns_failover) &&
630                         dns_srv_handle_next(&dns_srv_h, err) &&
631                         ((err=dns_sip_resolve2su(&dns_srv_h, &send_info->to, dst, port,
632                                                                                 &proto, dns_flags))==0));
633         if ((err!=0) && (err!=-E_DNS_EOR)){
634                 LM_ERR("resolving %.*s host name in uri failed: %s [%d] (dropping packet)\n",
635                                                                         dst->len, ZSW(dst->s),
636                                                                         dns_strerror(err), err);
637                 ret=ser_error=E_BAD_ADDRESS;
638                 goto error;
639         }
640 #endif
641
642 error:
643 end:
644 #ifdef USE_DNS_FAILOVER
645         if (dst && cfg_get(core, core_cfg, use_dns_failover)){
646                                 dns_srv_handle_put(&dns_srv_h);
647         }
648 #endif
649         if (buf) pkg_free(buf);
650         /* received_buf & line_buf will be freed in receive_msg by free_lump_list*/
651 #if defined STATS_REQ_FWD_OK || defined STATS_REQ_FWD_DROP
652         if(ret==0)
653                 STATS_REQ_FWD_OK();
654         else
655                 STATS_REQ_FWD_DROP();
656 #endif /* STATS_REQ_FWD_* */
657         return ret;
658 }
659
660
661
662 int update_sock_struct_from_via( union sockaddr_union* to,
663                                                                         struct sip_msg* msg,
664                                                                         struct via_body* via )
665 {
666         struct hostent* he;
667         str* name;
668         int err;
669         unsigned short port;
670         char proto;
671
672         port=0;
673         if(via==msg->via1){
674                 /* _local_ reply, we ignore any rport or received value
675                  * (but we will send back to the original port if rport is
676                  *  present) */
677                 if ((msg->msg_flags&FL_FORCE_RPORT)||(via->rport))
678                         port=msg->rcv.src_port;
679                 else port=via->port;
680                 name=&(via->host); /* received=ip in 1st via is ignored (it's
681                                                         * not added by us so it's bad) */
682         }else{
683                 /* "normal" reply, we use rport's & received value if present */
684                 if (via->rport && via->rport->value.s){
685                         LM_DBG("using 'rport'\n");
686                         port=str2s(via->rport->value.s, via->rport->value.len, &err);
687                         if (err){
688                                 LM_ERR("bad rport value(%.*s)\n",
689                                                 via->rport->value.len, via->rport->value.s);
690                                 port=0;
691                         }
692                 }
693                 if (via->received){
694                         LM_DBG("using 'received'\n");
695                         name=&(via->received->value);
696                         /* making sure that we won't do SRV lookup on "received"
697                          * (possible if no DNS_IP_HACK is used)*/
698                         if (port==0) port=via->port?via->port:SIP_PORT;
699                 }else{
700                         LM_DBG("using via host\n");
701                         name=&(via->host);
702                         if (port==0) port=via->port;
703                 }
704         }
705         /* we do now a malloc/memcpy because gethostbyname loves \0-terminated
706          * strings; but only if host is not null terminated (host.s[len] will
707          * always be ok for a via)
708          */
709         LM_DBG("check if dns lookup is needed for [%.*s]\n", name->len, name->s);
710         proto=via->proto;
711         he=sip_resolvehost(name, &port, &proto);
712
713         if (he==0){
714                 LM_NOTICE("resolve_host(%.*s) failure\n", name->len, name->s);
715                 return -1;
716         }
717
718         LM_DBG("address is [%.*s] port %d proto %d\n", name->len, name->s,
719                         (int)port, (int)proto);
720
721         hostent2su(to, he, 0, port);
722         return 1;
723 }
724
725
726
727 /** removes first via & sends msg to the second
728  * - mode param controls if modules sip response callbacks are executed */
729 static int do_forward_reply(struct sip_msg* msg, int mode)
730 {
731         char* new_buf;
732         struct dest_info dst;
733         unsigned int new_len;
734         int r;
735         struct ip_addr ip;
736 #ifdef USE_TCP
737         char* s;
738         int len;
739 #endif
740         init_dest_info(&dst);
741         new_buf=0;
742         /*check if first via host = us */
743         if (check_via){
744                 if (check_self(&msg->via1->host,
745                                         msg->via1->port?msg->via1->port:SIP_PORT,
746                                         msg->via1->proto)!=1){
747                         LM_ERR("host in first via!=me : %.*s:%d\n",
748                                 msg->via1->host.len, msg->via1->host.s, msg->via1->port);
749                         /* send error msg back? */
750                         goto error;
751                 }
752         }
753
754         /* check modules response_f functions */
755         if(likely(mode==0)) {
756                 for (r=0; r<mod_response_cbk_no; r++)
757                         if (mod_response_cbks[r](msg)==0) goto skip;
758         }
759         /* we have to forward the reply stateless, so we need second via -bogdan*/
760         if (parse_headers( msg, HDR_VIA2_F, 0 )==-1
761                 || (msg->via2==0) || (msg->via2->error!=PARSE_OK))
762         {
763                 /* no second via => error */
764                 LM_DBG("reply cannot be forwarded - no 2nd via\n");
765                 goto error;
766         }
767
768         new_buf = build_res_buf_from_sip_res( msg, &new_len);
769         if (!new_buf){
770                 LM_ERR("building failed\n");
771                 goto error;
772         }
773
774         dst.proto=msg->via2->proto;
775         SND_FLAGS_OR(&dst.send_flags, &msg->fwd_send_flags, &msg->rpl_send_flags);
776         if (update_sock_struct_from_via( &dst.to, msg, msg->via2 )==-1) goto error;
777 #ifdef USE_COMP
778         dst.comp=msg->via2->comp_no;
779 #endif
780
781 #if defined USE_TCP || defined USE_SCTP
782         if (
783 #ifdef USE_TCP
784                         dst.proto==PROTO_TCP
785                         || dst.proto==PROTO_WS
786 #ifdef USE_TLS
787                         || dst.proto==PROTO_TLS
788                         || dst.proto==PROTO_WSS
789 #endif
790 #ifdef USE_SCTP
791                         ||
792 #endif /* USE_SCTP */
793 #endif /* USE_TCP */
794 #ifdef USE_SCTP
795                         dst.proto==PROTO_SCTP
796 #endif /* USE_SCTP */
797                         ){
798                 /* find id in i param if it exists */
799                 if (msg->via1->i && msg->via1->i->value.s){
800                         s=msg->via1->i->value.s;
801                         len=msg->via1->i->value.len;
802                         LM_DBG("i=%.*s\n",len, ZSW(s));
803                         if (reverse_hex2int(s, len, (unsigned int*)&dst.id)<0){
804                                 LM_ERR("bad via i param \"%.*s\"\n", len, ZSW(s));
805                                 dst.id=0;
806                         }
807                 }
808
809         }
810 #endif
811
812         apply_force_send_socket(&dst, msg);
813
814         /* call onsend_route */
815         if(dst.send_sock == NULL) {
816                 dst.send_sock=get_send_socket(msg, &dst.to, dst.proto);
817                 if (dst.send_sock==0){
818                         LM_ERR("cannot forward reply\n");
819                         goto done;
820                 }
821         }
822         if (onsend_route_enabled(SIP_REPLY)){
823                 if (run_onsend(msg, &dst, new_buf, new_len)==0){
824                         su2ip_addr(&ip, &(dst.to));
825                         LM_ERR("reply to %s:%d(%d) dropped (onsend_route)\n",
826                                         ip_addr2a(&ip), su_getport(&(dst.to)), dst.proto);
827                         goto error; /* error ? */
828                 }
829         }
830
831         if (msg_send(&dst, new_buf, new_len)<0)
832         {
833                 STATS_RPL_FWD_DROP();
834                 goto error;
835         }
836
837         LM_DBG("reply forwarded (2nd via address: %.*s port %d)\n",
838                         msg->via2->host.len, msg->via2->host.s,
839                         (int) msg->via2->port);
840
841         done:
842         LM_DBG("reply forwarding finished (2nd via address: %.*s port %d)\n",
843                         msg->via2->host.len, msg->via2->host.s,
844                         (int) msg->via2->port);
845
846         STATS_RPL_FWD_OK();
847         pkg_free(new_buf);
848 skip:
849         return 0;
850 error:
851         if (new_buf) pkg_free(new_buf);
852         return -1;
853 }
854
855 /** removes first via & sends msg to the second */
856 int forward_reply(struct sip_msg* msg)
857 {
858         return do_forward_reply(msg, 0);
859 }
860
861 /** removes first via & sends msg to the second - no module callbacks */
862 int forward_reply_nocb(struct sip_msg* msg)
863 {
864         return do_forward_reply(msg, 1);
865 }
866
867 static void apply_force_send_socket(struct dest_info* dst, struct sip_msg* msg)
868 {
869         if (msg->force_send_socket != 0) {
870                 dst->send_sock = get_send_socket(msg, &dst->to, dst->proto);
871         }
872 }