Merge remote branch 'origin/sr_3.0'
[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 "route.h"
82 #include "events.h"
83 #include "dprint.h"
84 #include "globals.h"
85 #include "cfg_core.h"
86 #include "data_lump.h"
87 #include "ut.h"
88 #include "mem/mem.h"
89 #include "msg_translator.h"
90 #include "sr_module.h"
91 #include "ip_addr.h"
92 #include "resolve.h"
93 #include "name_alias.h"
94 #include "socket_info.h"
95 #include "onsend.h"
96 #include "resolve.h"
97 #ifdef USE_DNS_FAILOVER
98 #include "dns_cache.h"
99 #endif
100 #ifdef USE_DST_BLACKLIST
101 #include "dst_blacklist.h"
102 #endif
103 #include "compiler_opt.h"
104 #include "core_stats.h"
105
106 #ifdef DEBUG_DMALLOC
107 #include <dmalloc.h>
108 #endif
109
110
111
112 /* return a socket_info_pointer to the sending socket; as opposed to
113  * get_send_socket, which returns process's default socket, get_out_socket
114  * attempts to determine the outbound interface which will be used;
115  * it uses a temporary connected socket to determine it; it will
116  * be very likely noticeably slower, but it can deal better with
117  * multihomed hosts
118  */
119
120 static int mhomed_sock_cache_disabled = 0;
121 static int sock_inet = -1;
122 #ifdef USE_IPV6
123 static int sock_inet6 = -1;
124 #endif /* USE_IPV6 */
125
126 struct socket_info* get_out_socket(union sockaddr_union* to, int proto)
127 {
128         int* temp_sock;
129         socklen_t len;
130         union sockaddr_union from; 
131         struct socket_info* si;
132         struct ip_addr ip;
133
134         if (unlikely(proto!=PROTO_UDP)) {
135                 LOG(L_CRIT, "BUG: get_out_socket can only be called for UDP\n");
136                 return 0;
137         }
138 retry:
139         switch(to->s.sa_family){
140         case AF_INET : {
141                 if(unlikely(sock_inet < 0)){
142                         sock_inet = socket(AF_INET, SOCK_DGRAM, 0);
143                         if (sock_inet==-1) {
144                                 LM_ERR("socket() failed: %s\n", strerror(errno));
145                                 return 0;
146                         }
147                 }
148                 temp_sock = &sock_inet;
149                 break;
150         }
151 #ifdef USE_IPV6
152         case AF_INET6 : {
153                 if(unlikely(sock_inet6 < 0)){
154                         sock_inet6 = socket(AF_INET6, SOCK_DGRAM, 0);
155                         if (sock_inet6==-1) {
156                                 LM_ERR("socket() failed: %s\n", strerror(errno));
157                                 return 0;
158                         }
159                 }
160                 temp_sock = &sock_inet6;
161                 break;
162         }
163 #endif /* USE_IPV6 */
164         default: {
165                 LM_ERR("Unknown protocol family \n");
166                 return 0;
167         }
168         }
169         if (unlikely(connect(*temp_sock, &to->s, sockaddru_len(*to))==-1)) {
170                 if (unlikely(errno==EISCONN && !mhomed_sock_cache_disabled)){
171                         /*  no multiple connects support on the same socket */
172                         mhomed_sock_cache_disabled=1;
173                         if (sock_inet>=0){
174                                 close(sock_inet);
175                                 sock_inet=-1;
176                         }
177 #ifdef USE_IPV6
178                         if (sock_inet6>=0){
179                                 close(sock_inet6);
180                                 sock_inet6=-1;
181                         }
182 #endif /* USE_IPV6 */
183                         goto retry;
184                 }
185                 LOG(L_ERR, "ERROR: get_out_socket: connect failed: %s\n",
186                                 strerror(errno));
187                 goto error;
188         }
189         len=sizeof(from);
190         if (unlikely(getsockname(*temp_sock, &from.s, &len)==-1)) {
191                 LOG(L_ERR, "ERROR: get_out_socket: getsockname failed: %s\n",
192                                 strerror(errno));
193                 goto error;
194         }
195         su2ip_addr(&ip, &from);
196         si=find_si(&ip, 0, proto);
197         if (si==0) goto error;
198         DBG("DEBUG: get_out_socket: socket determined: %p\n", si );
199         if (unlikely(mhomed_sock_cache_disabled)){
200                 close(*temp_sock);
201                 *temp_sock=-1;
202         }
203         return si;
204 error:
205         LOG(L_ERR, "ERROR: get_out_socket: no socket found\n");
206         if (unlikely(mhomed_sock_cache_disabled && *temp_sock >=0)){
207                 close(*temp_sock);
208                 *temp_sock=-1;
209         }
210         return 0;
211 }
212
213
214
215 /** get the sending socket for a corresponding destination.
216  * @param force_send_socket - if !=0 and the protocol and af correspond
217  *                            with the destination, it will be returned.
218  *                            If the protocol or af check fail, a look-alike
219  *                            socket will be searched for and mismatch will be
220  *                            set. If no look-alike socket is found it will
221  *                            fallback to normal resolution.
222  * @param to - destination
223  * @param proto - protocol
224  * @param mismatch - result parameter, set if a force_send_socket was used, but
225  *                   there was an error matching it exactly to the destination.
226  *                   Possible values: 0 ok, SS_MISMATCH_PROTO,
227  *                   SS_MISMATCH_ADDR, SS_MISMATCH_AF, SS_MISMATCH_MCAST.
228  * @return a socket_info pointer to the sending socket on success (and possibly
229  *         sets mismatch) or 0 on error.
230  */
231 struct socket_info* get_send_socket2(struct socket_info* force_send_socket,
232                                                                                 union sockaddr_union* to, int proto,
233                                                                                 enum ss_mismatch* mismatch)
234 {
235         struct socket_info* send_sock;
236         
237         if (likely(mismatch)) *mismatch=0;
238         /* check if send interface is not forced */
239         if (unlikely(force_send_socket)){
240                 if (unlikely(force_send_socket->proto!=proto)){
241                         force_send_socket=find_si(&(force_send_socket->address),
242                                                                                         force_send_socket->port_no,
243                                                                                         proto);
244                         if (unlikely(force_send_socket == 0)){
245                                 if (likely(mismatch)) *mismatch=SS_MISMATCH_ADDR;
246                                 LOG(L_WARN, "WARNING: get_send_socket: "
247                                                 "protocol/port mismatch\n");
248                                 goto not_forced;
249                         }
250                         if (likely(mismatch)) *mismatch=SS_MISMATCH_PROTO;
251                 }
252                 if (unlikely(force_send_socket->address.af!=to->s.sa_family)){
253                         DBG("get_send_socket: force_send_socket of different af (dst %d,"
254                                         " forced %d)\n",
255                                         to->s.sa_family, force_send_socket->address.af);
256                         if (likely(mismatch)) *mismatch=SS_MISMATCH_AF;
257                         goto not_forced;
258                 }
259                 /* check if listening on the socket (the check does not work
260                    for TCP and TLS, for them socket==-1 on all the processes
261                    except tcp_main(), see close_extra_socks() */
262                 if (likely((force_send_socket->socket!=-1 ||
263                                                 force_send_socket->proto==PROTO_TCP ||
264                                                 force_send_socket->proto==PROTO_TLS) &&
265                                         !(force_send_socket->flags & SI_IS_MCAST)))
266                                 return force_send_socket;
267                 else{
268                         if (!(force_send_socket->flags & SI_IS_MCAST))
269                                 LOG(L_WARN, "WARNING: get_send_socket: not listening"
270                                                          " on the requested socket, no fork mode?\n");
271                         else if (likely(mismatch)) *mismatch=SS_MISMATCH_MCAST;
272                 }
273         };
274 not_forced:
275         if (mhomed && proto==PROTO_UDP){
276                 send_sock=get_out_socket(to, proto);
277                 if ((send_sock==0) || (send_sock->socket!=-1))
278                         return send_sock; /* found or error*/
279                 else if (send_sock->socket==-1){
280                         LOG(L_WARN, "WARNING: get_send_socket: not listening on the"
281                                         " requested socket, no fork mode?\n");
282                         /* continue: try to use some socket */
283                 }
284         }
285
286         send_sock=0;
287         /* check if we need to change the socket (different address families -
288          * eg: ipv4 -> ipv6 or ipv6 -> ipv4) */
289         switch(proto){
290 #ifdef USE_TCP
291                 case PROTO_TCP:
292                 /* on tcp just use the "main address", we don't really now the
293                  * sending address (we can find it out, but we'll need also to see
294                  * if we listen on it, and if yes on which port -> too complicated*/
295                         switch(to->s.sa_family){
296                                 /* FIXME */
297                                 case AF_INET:   send_sock=sendipv4_tcp;
298                                                                 break;
299 #ifdef USE_IPV6
300                                 case AF_INET6:  send_sock=sendipv6_tcp;
301                                                                 break;
302 #endif
303                                 default:        LOG(L_ERR, "get_send_socket: BUG: don't know how"
304                                                                         " to forward to af %d\n", to->s.sa_family);
305                         }
306                         break;
307 #endif
308 #ifdef USE_TLS
309                 case PROTO_TLS:
310                         switch(to->s.sa_family){
311                                 /* FIXME */
312                                 case AF_INET:   send_sock=sendipv4_tls;
313                                                                 break;
314 #ifdef USE_IPV6
315                                 case AF_INET6:  send_sock=sendipv6_tls;
316                                                                 break;
317 #endif
318                                 default:        LOG(L_ERR, "get_send_socket: BUG: don't know how"
319                                                                         " to forward to af %d\n", to->s.sa_family);
320                         }
321                         break;
322 #endif /* USE_TLS */
323 #ifdef USE_SCTP
324                 case PROTO_SCTP:
325                         if ((bind_address==0) ||
326                                         (to->s.sa_family!=bind_address->address.af) ||
327                                         (bind_address->proto!=PROTO_SCTP)){
328                                 switch(to->s.sa_family){
329                                         case AF_INET:   send_sock=sendipv4_sctp;
330                                                                         break;
331 #ifdef USE_IPV6
332                                         case AF_INET6:  send_sock=sendipv6_sctp;
333                                                                         break;
334 #endif
335                                         default:        LOG(L_ERR, "get_send_socket: BUG: don't know"
336                                                                                 " how to forward to af %d\n",
337                                                                                 to->s.sa_family);
338                                 }
339                         }else send_sock=bind_address;
340                         break;
341 #endif /* USE_SCTP */
342                 case PROTO_UDP:
343                         if ((bind_address==0) ||
344                                         (to->s.sa_family!=bind_address->address.af) ||
345                                         (bind_address->proto!=PROTO_UDP)){
346                                 switch(to->s.sa_family){
347                                         case AF_INET:   send_sock=sendipv4;
348                                                                         break;
349 #ifdef USE_IPV6
350                                         case AF_INET6:  send_sock=sendipv6;
351                                                                         break;
352 #endif
353                                         default:        LOG(L_ERR, "get_send_socket: BUG: don't know"
354                                                                                 " how to forward to af %d\n",
355                                                                                 to->s.sa_family);
356                                 }
357                         }else send_sock=bind_address;
358                         break;
359                 default:
360                         LOG(L_CRIT, "BUG: get_send_socket: unknown proto %d\n", proto);
361         }
362         return send_sock;
363 }
364
365 static struct _check_self_func {
366         check_self_f fself;
367         struct _check_self_func *next;
368 } *_check_self_func_list = NULL;
369
370 /* register a function to be called when matching for myself
371  * - return 0 on success, -1 on error
372  * - f must have same prototype as check_self() and return same kind of values
373  */
374 int register_check_self_func(check_self_f f)
375 {
376         struct _check_self_func *nf = 0;
377         nf=(struct _check_self_func*)pkg_malloc(sizeof(struct _check_self_func));
378         if(nf==0)
379         {
380                 LM_ERR("no more pkg\n");
381                 return -1;
382         }
383         nf->fself = f;
384         nf->next = _check_self_func_list;
385         _check_self_func_list = nf;
386         return 0;
387 }
388
389 /* run registered check self functions
390  * returns 1 if true, 0 if false
391  */
392 int run_check_self_func(str* host, unsigned short port, unsigned short proto)
393 {
394         struct _check_self_func *sf = 0;
395
396         if(_check_self_func_list==NULL)
397                 return 0;
398         for(sf=_check_self_func_list; sf; sf=sf->next)
399                 if(sf->fself(host, port, proto)==1)
400                         return 1;
401         return 0;
402 }
403
404 /* checks if the proto: host:port is one of the address we listen on;
405  * if port==0, the  port number is ignored
406  * if proto==0 (PROTO_NONE) the protocol is ignored
407  * returns 1 if true, 0 if false, -1 on error
408  * WARNING: uses str2ip6 so it will overwrite any previous
409  *  unsaved result of this function (static buffer)
410  */
411 int check_self(str* host, unsigned short port, unsigned short proto)
412 {
413         if (grep_sock_info(host, port, proto)) goto found;
414         /* try to look into the aliases*/
415         if (grep_aliases(host->s, host->len, port, proto)==0){
416                 DBG("check_self: host != me\n");
417                 return (_check_self_func_list==NULL)?0:run_check_self_func(host,
418                                                                                                                 port, proto);
419         }
420 found:
421         return 1;
422 }
423
424 /* checks if the proto:port is one of the ports we listen on;
425  * if proto==0 (PROTO_NONE) the protocol is ignored
426  * returns 1 if true, 0 if false, -1 on error
427  */
428 int check_self_port(unsigned short port, unsigned short proto)
429 {
430         if (grep_sock_info_by_port(port, proto))
431                 /* as aliases do not contain different ports we can skip them */
432                 return 1;
433         else
434                 return 0;
435 }
436
437
438
439 /* forwards a request to dst
440  * parameters:
441  *   msg       - sip msg
442  *   dst       - destination name, if non-null it will be resolved and
443  *               send_info updated with the ip/port. Even if dst is non
444  *               null send_info must contain the protocol and if a non
445  *               default port or non srv. lookup is desired, the port must
446  *               be !=0 
447  *   port      - used only if dst!=0 (else the port in send_info->to is used)
448  *   send_info - value/result partially filled dest_info structure:
449  *                 - send_info->proto and comp are used
450  *                 - send_info->to will be filled (dns)
451  *                 - send_info->send_flags is filled from the message
452  *                 - if the send_socket member is null, a send_socket will be 
453  *                   chosen automatically
454  * WARNING: don't forget to zero-fill all the  unused members (a non-zero 
455  * random id along with proto==PROTO_TCP can have bad consequences, same for
456  *   a bogus send_socket value)
457  */
458 int forward_request(struct sip_msg* msg, str* dst, unsigned short port,
459                                                         struct dest_info* send_info)
460 {
461         unsigned int len;
462         char* buf;
463         char md5[MD5_LEN];
464         struct socket_info* orig_send_sock; /* initial send_sock */
465         int ret;
466         struct ip_addr ip; /* debugging only */
467         char proto;
468 #ifdef USE_DNS_FAILOVER
469         struct socket_info* prev_send_sock;
470         int err;
471         struct dns_srv_handle dns_srv_h;
472         
473         prev_send_sock=0;
474         err=0;
475 #endif
476         
477         
478         buf=0;
479         orig_send_sock=send_info->send_sock;
480         proto=send_info->proto;
481         ret=0;
482
483         if(dst){
484 #ifdef USE_DNS_FAILOVER
485                 if (cfg_get(core, core_cfg, use_dns_failover)){
486                         dns_srv_handle_init(&dns_srv_h);
487                         err=dns_sip_resolve2su(&dns_srv_h, &send_info->to, dst, port,
488                                                                         &proto, dns_flags);
489                         if (err!=0){
490                                 LOG(L_ERR, "ERROR: forward_request: resolving \"%.*s\""
491                                                 " failed: %s [%d]\n", dst->len, ZSW(dst->s),
492                                                 dns_strerror(err), err);
493                                 ret=E_BAD_ADDRESS;
494                                 goto error;
495                         }
496                 }else
497 #endif
498                 if (sip_hostport2su(&send_info->to, dst, port, &proto)<0){
499                         LOG(L_ERR, "ERROR: forward_request: bad host name %.*s,"
500                                                 " dropping packet\n", dst->len, ZSW(dst->s));
501                         ret=E_BAD_ADDRESS;
502                         goto error;
503                 }
504         }/* dst */
505         send_info->send_flags=msg->fwd_send_flags;
506         /* calculate branch for outbound request;  if syn_branch is turned off,
507            calculate is from transaction key, i.e., as an md5 of From/To/CallID/
508            CSeq exactly the same way as TM does; good for reboot -- than messages
509            belonging to transaction lost due to reboot will still be forwarded
510            with the same branch parameter and will be match-able downstream
511         
512            if it is turned on, we don't care about reboot; we simply put a simple
513            value in there; better for performance
514         */
515         if (syn_branch ) {
516                 *msg->add_to_branch_s='0';
517                 msg->add_to_branch_len=1;
518         } else {
519                 if (!char_msg_val( msg, md5 ))  { /* parses transaction key */
520                         LOG(L_ERR, "ERROR: forward_request: char_msg_val failed\n");
521                         ret=E_UNSPEC;
522                         goto error;
523                 }
524                 msg->hash_index=hash( msg->callid->body, get_cseq(msg)->number);
525                 if (!branch_builder( msg->hash_index, 0, md5, 0 /* 0-th branch */,
526                                         msg->add_to_branch_s, &msg->add_to_branch_len )) {
527                         LOG(L_ERR, "ERROR: forward_request: branch_builder failed\n");
528                         ret=E_UNSPEC;
529                         goto error;
530                 }
531         }
532         /* try to send the message until success or all the ips are exhausted
533          *  (if dns lookup is performed && the dns cache used ) */
534 #ifdef USE_DNS_FAILOVER
535         do{
536 #endif
537                 if (orig_send_sock==0) /* no forced send_sock => find it **/
538                         send_info->send_sock=get_send_socket(msg, &send_info->to, proto);
539                 if (send_info->send_sock==0){
540                         LOG(L_ERR, "forward_req: ERROR: cannot forward to af %d, proto %d "
541                                                 "no corresponding listening socket\n",
542                                                 send_info->to.s.sa_family, proto);
543                         ret=ser_error=E_NO_SOCKET;
544 #ifdef USE_DNS_FAILOVER
545                         /* continue, maybe we find a socket for some other ip */
546                         continue;
547 #else
548                         goto error;
549 #endif
550                 }
551         
552 #ifdef USE_DNS_FAILOVER
553                 if (prev_send_sock!=send_info->send_sock){
554                         /* rebuild the message only if the send_sock changed */
555                         prev_send_sock=send_info->send_sock;
556 #endif
557                         if (buf) pkg_free(buf);
558                         send_info->proto=proto;
559                         buf = build_req_buf_from_sip_req(msg, &len, send_info, 0);
560                         if (!buf){
561                                 LOG(L_ERR, "ERROR: forward_request: building failed\n");
562                                 ret=E_OUT_OF_MEM; /* most probable */
563                                 goto error;
564                         }
565 #ifdef USE_DNS_FAILOVER
566                 }
567 #endif
568                  /* send it! */
569                 DBG("Sending:\n%.*s.\n", (int)len, buf);
570                 DBG("orig. len=%d, new_len=%d, proto=%d\n",
571                                 msg->len, len, send_info->proto );
572         
573                 if (run_onsend(msg, send_info, buf, len)==0){
574                         su2ip_addr(&ip, &send_info->to);
575                         LOG(L_INFO, "forward_request: request to %s:%d(%d) dropped"
576                                         " (onsend_route)\n", ip_addr2a(&ip),
577                                                 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                                 LOG(L_DBG, "DEBUG: blacklisted destination:%s:%d (%d)\n",
591                                                         ip_addr2a(&ip), su_getport(&send_info->to),
592                                                         send_info->proto);
593                                 ret=ser_error=E_SEND;
594 #ifdef USE_DNS_FAILOVER
595                                 continue; /* try another ip */
596 #else
597                                 goto error;
598 #endif
599                         }
600                 }
601 #endif
602                 if (msg_send(send_info, buf, len)<0){
603                         ret=ser_error=E_SEND;
604 #ifdef USE_DST_BLACKLIST
605                         if (cfg_get(core, core_cfg, 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         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 }