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