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 "dprint.h"
83 #include "globals.h"
84 #include "cfg_core.h"
85 #include "data_lump.h"
86 #include "ut.h"
87 #include "mem/mem.h"
88 #include "msg_translator.h"
89 #include "sr_module.h"
90 #include "ip_addr.h"
91 #include "resolve.h"
92 #include "name_alias.h"
93 #include "socket_info.h"
94 #include "onsend.h"
95 #include "resolve.h"
96 #ifdef USE_DNS_FAILOVER
97 #include "dns_cache.h"
98 #endif
99 #ifdef USE_DST_BLACKLIST
100 #include "dst_blacklist.h"
101 #endif
102 #include "compiler_opt.h"
103
104 #ifdef DEBUG_DMALLOC
105 #include <dmalloc.h>
106 #endif
107
108
109
110 /* return a socket_info_pointer to the sending socket; as opposed to
111  * get_send_socket, which returns process's default socket, get_out_socket
112  * attempts to determine the outbound interface which will be used;
113  * it uses a temporary connected socket to determine it; it will
114  * be very likely noticeably slower, but it can deal better with
115  * multihomed hosts
116  */
117
118 static int sock_inet = 0;
119 static int sock_inet6 = 0;
120
121 struct socket_info* get_out_socket(union sockaddr_union* to, int proto)
122 {
123         int temp_sock;
124         socklen_t len;
125         union sockaddr_union from; 
126         struct socket_info* si;
127         struct ip_addr ip;
128
129         if (proto!=PROTO_UDP) {
130                 LOG(L_CRIT, "BUG: get_out_socket can only be called for UDP\n");
131                 return 0;
132         }
133
134         switch(to->s.sa_family){
135         case AF_INET : {
136                 if(sock_inet <= 0){
137                         sock_inet = socket(AF_INET, SOCK_DGRAM, 0);
138                         if (sock_inet==-1) {
139                                 LM_ERR("socket() failed: %s\n", strerror(errno));
140                                 return 0;
141                         }
142                 }
143                 temp_sock = sock_inet;
144                 break;
145         }
146         case AF_INET6 : {
147                 if(sock_inet6 <= 0){
148                         sock_inet6 = socket(AF_INET6, SOCK_DGRAM, 0);
149                         if (sock_inet6==-1) {
150                                 LM_ERR("socket() failed: %s\n", strerror(errno));
151                                 return 0;
152                         }
153                 }
154                 temp_sock = sock_inet6;
155                 break;
156         }
157         default: {
158                 LM_ERR("Unknow protocol family \n");
159                 return 0;
160         }
161         }
162         if (connect(temp_sock, &to->s, sockaddru_len(*to))==-1) {
163                 LOG(L_ERR, "ERROR: get_out_socket: connect failed: %s\n",
164                                 strerror(errno));
165                 sock_inet = 0;
166                 sock_inet6 = 0;
167                 goto error;
168         }
169         len=sizeof(from);
170         if (getsockname(temp_sock, &from.s, &len)==-1) {
171                 LOG(L_ERR, "ERROR: get_out_socket: getsockname failed: %s\n",
172                                 strerror(errno));
173                 sock_inet = 0;
174                 sock_inet6 = 0;
175                 goto error;
176         }
177         su2ip_addr(&ip, &from);
178         si=find_si(&ip, 0, proto);
179         if (si==0) goto error;
180         DBG("DEBUG: get_out_socket: socket determined: %p\n", si );
181         return si;
182 error:
183         LOG(L_ERR, "ERROR: get_out_socket: no socket found\n");
184         return 0;
185 }
186
187
188
189 /** get the sending socket for a corresponding destination.
190  * @param force_send_socket - if !=0 and the protocol and af correspond
191  *                            with the destination, it will be returned.
192  *                            If the protocol or af check fail, a look-alike
193  *                            socket will be searched for and mismatch will be
194  *                            set. If no look-alike socket is found it will
195  *                            fallback to normal resolution.
196  * @param to - destination
197  * @param proto - protocol
198  * @param mismatch - result parameter, set if a force_send_socket was used, but
199  *                   there was an error matching it exactly to the destination.
200  *                   Possible values: 0 ok, SS_MISMATCH_PROTO,
201  *                   SS_MISMATCH_ADDR, SS_MISMATCH_AF, SS_MISMATCH_MCAST.
202  * @return a socket_info pointer to the sending socket on success (and possibly
203  *         sets mismatch) or 0 on error.
204  */
205 struct socket_info* get_send_socket2(struct socket_info* force_send_socket,
206                                                                                 union sockaddr_union* to, int proto,
207                                                                                 enum ss_mismatch* mismatch)
208 {
209         struct socket_info* send_sock;
210         
211         if (likely(mismatch)) *mismatch=0;
212         /* check if send interface is not forced */
213         if (unlikely(force_send_socket)){
214                 if (unlikely(force_send_socket->proto!=proto)){
215                         force_send_socket=find_si(&(force_send_socket->address),
216                                                                                         force_send_socket->port_no,
217                                                                                         proto);
218                         if (unlikely(force_send_socket == 0)){
219                                 if (likely(mismatch)) *mismatch=SS_MISMATCH_ADDR;
220                                 LOG(L_WARN, "WARNING: get_send_socket: "
221                                                 "protocol/port mismatch\n");
222                                 goto not_forced;
223                         }
224                         if (likely(mismatch)) *mismatch=SS_MISMATCH_PROTO;
225                 }
226                 if (unlikely(force_send_socket->address.af!=to->s.sa_family)){
227                         DBG("get_send_socket: force_send_socket of different af (dst %d,"
228                                         " forced %d)\n",
229                                         to->s.sa_family, force_send_socket->address.af);
230                         if (likely(mismatch)) *mismatch=SS_MISMATCH_AF;
231                         goto not_forced;
232                 }
233                 /* check if listening on the socket (the check does not work
234                    for TCP and TLS, for them socket==-1 on all the processes
235                    except tcp_main(), see close_extra_socks() */
236                 if (likely((force_send_socket->socket!=-1 ||
237                                                 force_send_socket->proto==PROTO_TCP ||
238                                                 force_send_socket->proto==PROTO_TLS) &&
239                                         !(force_send_socket->flags & SI_IS_MCAST)))
240                                 return force_send_socket;
241                 else{
242                         if (!(force_send_socket->flags & SI_IS_MCAST))
243                                 LOG(L_WARN, "WARNING: get_send_socket: not listening"
244                                                          " on the requested socket, no fork mode?\n");
245                         else if (likely(mismatch)) *mismatch=SS_MISMATCH_MCAST;
246                 }
247         };
248 not_forced:
249         if (mhomed && proto==PROTO_UDP){
250                 send_sock=get_out_socket(to, proto);
251                 if ((send_sock==0) || (send_sock->socket!=-1))
252                         return send_sock; /* found or error*/
253                 else if (send_sock->socket==-1){
254                         LOG(L_WARN, "WARNING: get_send_socket: not listening on the"
255                                         " requested socket, no fork mode?\n");
256                         /* continue: try to use some socket */
257                 }
258         }
259
260         send_sock=0;
261         /* check if we need to change the socket (different address families -
262          * eg: ipv4 -> ipv6 or ipv6 -> ipv4) */
263         switch(proto){
264 #ifdef USE_TCP
265                 case PROTO_TCP:
266                 /* on tcp just use the "main address", we don't really now the
267                  * sending address (we can find it out, but we'll need also to see
268                  * if we listen on it, and if yes on which port -> too complicated*/
269                         switch(to->s.sa_family){
270                                 /* FIXME */
271                                 case AF_INET:   send_sock=sendipv4_tcp;
272                                                                 break;
273 #ifdef USE_IPV6
274                                 case AF_INET6:  send_sock=sendipv6_tcp;
275                                                                 break;
276 #endif
277                                 default:        LOG(L_ERR, "get_send_socket: BUG: don't know how"
278                                                                         " to forward to af %d\n", to->s.sa_family);
279                         }
280                         break;
281 #endif
282 #ifdef USE_TLS
283                 case PROTO_TLS:
284                         switch(to->s.sa_family){
285                                 /* FIXME */
286                                 case AF_INET:   send_sock=sendipv4_tls;
287                                                                 break;
288 #ifdef USE_IPV6
289                                 case AF_INET6:  send_sock=sendipv6_tls;
290                                                                 break;
291 #endif
292                                 default:        LOG(L_ERR, "get_send_socket: BUG: don't know how"
293                                                                         " to forward to af %d\n", to->s.sa_family);
294                         }
295                         break;
296 #endif /* USE_TLS */
297 #ifdef USE_SCTP
298                 case PROTO_SCTP:
299                         if ((bind_address==0) ||
300                                         (to->s.sa_family!=bind_address->address.af) ||
301                                         (bind_address->proto!=PROTO_SCTP)){
302                                 switch(to->s.sa_family){
303                                         case AF_INET:   send_sock=sendipv4_sctp;
304                                                                         break;
305 #ifdef USE_IPV6
306                                         case AF_INET6:  send_sock=sendipv6_sctp;
307                                                                         break;
308 #endif
309                                         default:        LOG(L_ERR, "get_send_socket: BUG: don't know"
310                                                                                 " how to forward to af %d\n",
311                                                                                 to->s.sa_family);
312                                 }
313                         }else send_sock=bind_address;
314                         break;
315 #endif /* USE_SCTP */
316                 case PROTO_UDP:
317                         if ((bind_address==0) ||
318                                         (to->s.sa_family!=bind_address->address.af) ||
319                                         (bind_address->proto!=PROTO_UDP)){
320                                 switch(to->s.sa_family){
321                                         case AF_INET:   send_sock=sendipv4;
322                                                                         break;
323 #ifdef USE_IPV6
324                                         case AF_INET6:  send_sock=sendipv6;
325                                                                         break;
326 #endif
327                                         default:        LOG(L_ERR, "get_send_socket: BUG: don't know"
328                                                                                 " how to forward to af %d\n",
329                                                                                 to->s.sa_family);
330                                 }
331                         }else send_sock=bind_address;
332                         break;
333                 default:
334                         LOG(L_CRIT, "BUG: get_send_socket: unknown proto %d\n", proto);
335         }
336         return send_sock;
337 }
338
339 static struct _check_self_func {
340         check_self_f fself;
341         struct _check_self_func *next;
342 } *_check_self_func_list = NULL;
343
344 /* register a function to be called when matching for myself
345  * - return 0 on success, -1 on error
346  * - f must have same prototype as check_self() and return same kind of values
347  */
348 int register_check_self_func(check_self_f f)
349 {
350         struct _check_self_func *nf = 0;
351         nf=(struct _check_self_func*)pkg_malloc(sizeof(struct _check_self_func));
352         if(nf==0)
353         {
354                 LM_ERR("no more pkg\n");
355                 return -1;
356         }
357         nf->fself = f;
358         nf->next = _check_self_func_list;
359         _check_self_func_list = nf;
360         return 0;
361 }
362
363 /* run registered check self functions
364  * returns 1 if true, 0 if false
365  */
366 int run_check_self_func(str* host, unsigned short port, unsigned short proto)
367 {
368         struct _check_self_func *sf = 0;
369
370         if(_check_self_func_list==NULL)
371                 return 0;
372         for(sf=_check_self_func_list; sf; sf=sf->next)
373                 if(sf->fself(host, port, proto)==1)
374                         return 1;
375         return 0;
376 }
377
378 /* checks if the proto: host:port is one of the address we listen on;
379  * if port==0, the  port number is ignored
380  * if proto==0 (PROTO_NONE) the protocol is ignored
381  * returns 1 if true, 0 if false, -1 on error
382  * WARNING: uses str2ip6 so it will overwrite any previous
383  *  unsaved result of this function (static buffer)
384  */
385 int check_self(str* host, unsigned short port, unsigned short proto)
386 {
387         if (grep_sock_info(host, port, proto)) goto found;
388         /* try to look into the aliases*/
389         if (grep_aliases(host->s, host->len, port, proto)==0){
390                 DBG("check_self: host != me\n");
391                 return (_check_self_func_list==NULL)?0:run_check_self_func(host,
392                                                                                                                 port, proto);
393         }
394 found:
395         return 1;
396 }
397
398 /* checks if the proto:port is one of the ports we listen on;
399  * if proto==0 (PROTO_NONE) the protocol is ignored
400  * returns 1 if true, 0 if false, -1 on error
401  */
402 int check_self_port(unsigned short port, unsigned short proto)
403 {
404         if (grep_sock_info_by_port(port, proto))
405                 /* as aliases do not contain different ports we can skip them */
406                 return 1;
407         else
408                 return 0;
409 }
410
411
412
413 /* forwards a request to dst
414  * parameters:
415  *   msg       - sip msg
416  *   dst       - destination name, if non-null it will be resolved and
417  *               send_info updated with the ip/port. Even if dst is non
418  *               null send_info must contain the protocol and if a non
419  *               default port or non srv. lookup is desired, the port must
420  *               be !=0 
421  *   port      - used only if dst!=0 (else the port in send_info->to is used)
422  *   send_info - value/result partially filled dest_info structure:
423  *                 - send_info->proto and comp are used
424  *                 - send_info->to will be filled (dns)
425  *                 - send_info->send_flags is filled from the message
426  *                 - if the send_socket member is null, a send_socket will be 
427  *                   chosen automatically
428  * WARNING: don't forget to zero-fill all the  unused members (a non-zero 
429  * random id along with proto==PROTO_TCP can have bad consequences, same for
430  *   a bogus send_socket value)
431  */
432 int forward_request(struct sip_msg* msg, str* dst, unsigned short port,
433                                                         struct dest_info* send_info)
434 {
435         unsigned int len;
436         char* buf;
437         char md5[MD5_LEN];
438         struct socket_info* orig_send_sock; /* initial send_sock */
439         int ret;
440         struct ip_addr ip; /* debugging only */
441         char proto;
442 #ifdef USE_DNS_FAILOVER
443         struct socket_info* prev_send_sock;
444         int err;
445         struct dns_srv_handle dns_srv_h;
446         
447         prev_send_sock=0;
448         err=0;
449 #endif
450         
451         
452         buf=0;
453         orig_send_sock=send_info->send_sock;
454         proto=send_info->proto;
455         ret=0;
456
457         if(dst){
458 #ifdef USE_DNS_FAILOVER
459                 if (cfg_get(core, core_cfg, use_dns_failover)){
460                         dns_srv_handle_init(&dns_srv_h);
461                         err=dns_sip_resolve2su(&dns_srv_h, &send_info->to, dst, port,
462                                                                         &proto, dns_flags);
463                         if (err!=0){
464                                 LOG(L_ERR, "ERROR: forward_request: resolving \"%.*s\""
465                                                 " failed: %s [%d]\n", dst->len, ZSW(dst->s),
466                                                 dns_strerror(err), err);
467                                 ret=E_BAD_ADDRESS;
468                                 goto error;
469                         }
470                 }else
471 #endif
472                 if (sip_hostport2su(&send_info->to, dst, port, &proto)<0){
473                         LOG(L_ERR, "ERROR: forward_request: bad host name %.*s,"
474                                                 " dropping packet\n", dst->len, ZSW(dst->s));
475                         ret=E_BAD_ADDRESS;
476                         goto error;
477                 }
478         }/* dst */
479         send_info->send_flags=msg->fwd_send_flags;
480         /* calculate branch for outbound request;  if syn_branch is turned off,
481            calculate is from transaction key, i.e., as an md5 of From/To/CallID/
482            CSeq exactly the same way as TM does; good for reboot -- than messages
483            belonging to transaction lost due to reboot will still be forwarded
484            with the same branch parameter and will be match-able downstream
485         
486            if it is turned on, we don't care about reboot; we simply put a simple
487            value in there; better for performance
488         */
489         if (syn_branch ) {
490                 *msg->add_to_branch_s='0';
491                 msg->add_to_branch_len=1;
492         } else {
493                 if (!char_msg_val( msg, md5 ))  { /* parses transaction key */
494                         LOG(L_ERR, "ERROR: forward_request: char_msg_val failed\n");
495                         ret=E_UNSPEC;
496                         goto error;
497                 }
498                 msg->hash_index=hash( msg->callid->body, get_cseq(msg)->number);
499                 if (!branch_builder( msg->hash_index, 0, md5, 0 /* 0-th branch */,
500                                         msg->add_to_branch_s, &msg->add_to_branch_len )) {
501                         LOG(L_ERR, "ERROR: forward_request: branch_builder failed\n");
502                         ret=E_UNSPEC;
503                         goto error;
504                 }
505         }
506         /* try to send the message until success or all the ips are exhausted
507          *  (if dns lookup is performed && the dns cache used ) */
508 #ifdef USE_DNS_FAILOVER
509         do{
510 #endif
511                 if (orig_send_sock==0) /* no forced send_sock => find it **/
512                         send_info->send_sock=get_send_socket(msg, &send_info->to, proto);
513                 if (send_info->send_sock==0){
514                         LOG(L_ERR, "forward_req: ERROR: cannot forward to af %d, proto %d "
515                                                 "no corresponding listening socket\n",
516                                                 send_info->to.s.sa_family, proto);
517                         ret=ser_error=E_NO_SOCKET;
518 #ifdef USE_DNS_FAILOVER
519                         /* continue, maybe we find a socket for some other ip */
520                         continue;
521 #else
522                         goto error;
523 #endif
524                 }
525         
526 #ifdef USE_DNS_FAILOVER
527                 if (prev_send_sock!=send_info->send_sock){
528                         /* rebuild the message only if the send_sock changed */
529                         prev_send_sock=send_info->send_sock;
530 #endif
531                         if (buf) pkg_free(buf);
532                         send_info->proto=proto;
533                         buf = build_req_buf_from_sip_req(msg, &len, send_info, 0);
534                         if (!buf){
535                                 LOG(L_ERR, "ERROR: forward_request: building failed\n");
536                                 ret=E_OUT_OF_MEM; /* most probable */
537                                 goto error;
538                         }
539 #ifdef USE_DNS_FAILOVER
540                 }
541 #endif
542                  /* send it! */
543                 DBG("Sending:\n%.*s.\n", (int)len, buf);
544                 DBG("orig. len=%d, new_len=%d, proto=%d\n",
545                                 msg->len, len, send_info->proto );
546         
547                 if (run_onsend(msg, send_info, buf, len)==0){
548                         su2ip_addr(&ip, &send_info->to);
549                         LOG(L_INFO, "forward_request: request to %s:%d(%d) dropped"
550                                         " (onsend_route)\n", ip_addr2a(&ip),
551                                                 su_getport(&send_info->to), send_info->proto);
552                         ser_error=E_OK; /* no error */
553                         ret=E_ADM_PROHIBITED;
554 #ifdef USE_DNS_FAILOVER
555                         continue; /* try another ip */
556 #else
557                         goto error; /* error ? */
558 #endif
559                 }
560 #ifdef USE_DST_BLACKLIST
561                 if (cfg_get(core, core_cfg, use_dst_blacklist)){
562                         if (dst_is_blacklisted(send_info, msg)){
563                                 su2ip_addr(&ip, &send_info->to);
564                                 LOG(L_DBG, "DEBUG: blacklisted destination:%s:%d (%d)\n",
565                                                         ip_addr2a(&ip), su_getport(&send_info->to),
566                                                         send_info->proto);
567                                 ret=ser_error=E_SEND;
568 #ifdef USE_DNS_FAILOVER
569                                 continue; /* try another ip */
570 #else
571                                 goto error;
572 #endif
573                         }
574                 }
575 #endif
576                 if (msg_send(send_info, buf, len)<0){
577                         ret=ser_error=E_SEND;
578 #ifdef USE_DST_BLACKLIST
579                         if (cfg_get(core, core_cfg, use_dst_blacklist))
580                                 dst_blacklist_add(BLST_ERR_SEND, send_info, msg);
581 #endif
582 #ifdef USE_DNS_FAILOVER
583                         continue; /* try another ip */
584 #else
585                         goto error;
586 #endif
587                 }else{
588                         ret=ser_error=E_OK;
589                         /* sent requests stats */
590                         STATS_TX_REQUEST(  msg->first_line.u.request.method_value );
591                         /* exit succcesfully */
592                         goto end;
593                 }
594 #ifdef USE_DNS_FAILOVER
595         }while(dst && cfg_get(core, core_cfg, use_dns_failover) &&
596                         dns_srv_handle_next(&dns_srv_h, err) && 
597                         ((err=dns_sip_resolve2su(&dns_srv_h, &send_info->to, dst, port,
598                                                                                 &proto, dns_flags))==0));
599         if ((err!=0) && (err!=-E_DNS_EOR)){
600                 LOG(L_ERR, "ERROR:  resolving %.*s host name in uri"
601                                                         " failed: %s [%d] (dropping packet)\n",
602                                                                         dst->len, ZSW(dst->s),
603                                                                         dns_strerror(err), err);
604                 ret=ser_error=E_BAD_ADDRESS;
605                 goto error;
606         }
607 #endif
608         
609 error:
610         STATS_TX_DROPS;
611 end:
612 #ifdef USE_DNS_FAILOVER
613         if (dst && cfg_get(core, core_cfg, use_dns_failover)){
614                                 dns_srv_handle_put(&dns_srv_h);
615         }
616 #endif
617         if (buf) pkg_free(buf);
618         /* received_buf & line_buf will be freed in receive_msg by free_lump_list*/
619         return ret;
620 }
621
622
623
624 int update_sock_struct_from_via( union sockaddr_union* to,
625                                                                  struct sip_msg* msg,
626                                                                  struct via_body* via )
627 {
628         struct hostent* he;
629         str* name;
630         int err;
631         unsigned short port;
632         char proto;
633
634         port=0;
635         if(via==msg->via1){ 
636                 /* _local_ reply, we ignore any rport or received value
637                  * (but we will send back to the original port if rport is
638                  *  present) */
639                 if ((msg->msg_flags&FL_FORCE_RPORT)||(via->rport))
640                         port=msg->rcv.src_port;
641                 else port=via->port;
642                 name=&(via->host); /* received=ip in 1st via is ignored (it's
643                                                           not added by us so it's bad) */
644         }else{
645                 /* "normal" reply, we use rport's & received value if present */
646                 if (via->rport && via->rport->value.s){
647                         DBG("update_sock_struct_from_via: using 'rport'\n");
648                         port=str2s(via->rport->value.s, via->rport->value.len, &err);
649                         if (err){
650                                 LOG(L_NOTICE, "ERROR: update_sock_struct_from_via: bad rport value(%.*s)\n",
651                                                 via->rport->value.len, via->rport->value.s);
652                                 port=0;
653                         }
654                 }
655                 if (via->received){
656                         DBG("update_sock_struct_from_via: using 'received'\n");
657                         name=&(via->received->value);
658                         /* making sure that we won't do SRV lookup on "received"
659                          * (possible if no DNS_IP_HACK is used)*/
660                         if (port==0) port=via->port?via->port:SIP_PORT; 
661                 }else{
662                         DBG("update_sock_struct_from_via: using via host\n");
663                         name=&(via->host);
664                         if (port==0) port=via->port;
665                 }
666         }
667         /* we do now a malloc/memcpy because gethostbyname loves \0-terminated 
668            strings; -jiri 
669            but only if host is not null terminated
670            (host.s[len] will always be ok for a via)
671             BTW: when is via->host.s non null terminated? tm copy? - andrei 
672             Yes -- it happened on generating a 408 by TM; -jiri
673             sip_resolvehost now accepts str -janakj
674         */
675         DBG("update_sock_struct_from_via: trying SRV lookup\n");
676         proto=via->proto;
677         he=sip_resolvehost(name, &port, &proto);
678         
679         if (he==0){
680                 LOG(L_NOTICE, "ERROR:forward_reply:resolve_host(%.*s) failure\n",
681                                 name->len, name->s);
682                 return -1;
683         }
684                 
685         hostent2su(to, he, 0, port);
686         return 1;
687 }
688
689
690
691 /* removes first via & sends msg to the second */
692 int forward_reply(struct sip_msg* msg)
693 {
694         char* new_buf;
695         struct dest_info dst;
696         unsigned int new_len;
697         int r;
698 #ifdef USE_TCP
699         char* s;
700         int len;
701 #endif
702         init_dest_info(&dst);
703         new_buf=0;
704         /*check if first via host = us */
705         if (check_via){
706                 if (check_self(&msg->via1->host,
707                                         msg->via1->port?msg->via1->port:SIP_PORT,
708                                         msg->via1->proto)!=1){
709                         LOG(L_NOTICE, "ERROR: forward_reply: host in first via!=me :"
710                                         " %.*s:%d\n", msg->via1->host.len, msg->via1->host.s,
711                                                                         msg->via1->port);
712                         /* send error msg back? */
713                         goto error;
714                 }
715         }
716         
717         /* check modules response_f functions */
718         for (r=0; r<mod_response_cbk_no; r++)
719                 if (mod_response_cbks[r](msg)==0) goto skip;
720         /* we have to forward the reply stateless, so we need second via -bogdan*/
721         if (parse_headers( msg, HDR_VIA2_F, 0 )==-1 
722                 || (msg->via2==0) || (msg->via2->error!=PARSE_OK))
723         {
724                 /* no second via => error */
725                 LOG(L_ERR, "ERROR: forward_reply: no 2nd via found in reply\n");
726                 goto error;
727         }
728
729         new_buf = build_res_buf_from_sip_res( msg, &new_len);
730         if (!new_buf){
731                 LOG(L_ERR, "ERROR: forward_reply: building failed\n");
732                 goto error;
733         }
734
735         dst.proto=msg->via2->proto;
736         dst.send_flags=msg->fwd_send_flags | msg->rpl_send_flags;
737         if (update_sock_struct_from_via( &dst.to, msg, msg->via2 )==-1) goto error;
738 #ifdef USE_COMP
739         dst.comp=msg->via2->comp_no;
740 #endif
741
742 #if defined USE_TCP || defined USE_SCTP
743         if (
744 #ifdef USE_TCP
745                         dst.proto==PROTO_TCP
746 #ifdef USE_TLS
747                         || dst.proto==PROTO_TLS
748 #endif
749 #ifdef USE_SCTP
750                         ||
751 #endif /* USE_SCTP */
752 #endif /* USE_TCP */
753 #ifdef USE_SCTP
754                         dst.proto==PROTO_SCTP
755 #endif /* USE_SCTP */
756                         ){
757                 /* find id in i param if it exists */
758                 if (msg->via1->i && msg->via1->i->value.s){
759                         s=msg->via1->i->value.s;
760                         len=msg->via1->i->value.len;
761                         DBG("forward_reply: i=%.*s\n",len, ZSW(s));
762                         if (reverse_hex2int(s, len, (unsigned int*)&dst.id)<0){
763                                 LOG(L_ERR, "ERROR: forward_reply: bad via i param \"%.*s\"\n",
764                                                 len, ZSW(s));
765                                         dst.id=0;
766                         }
767                 }               
768                                 
769         } 
770 #endif
771         if (msg_send(&dst, new_buf, new_len)<0) goto error;
772 #ifdef STATS
773         STATS_TX_RESPONSE(  (msg->first_line.u.reply.statuscode/100) );
774 #endif
775
776         DBG(" reply forwarded to %.*s:%d\n", 
777                         msg->via2->host.len, msg->via2->host.s,
778                         (unsigned short) msg->via2->port);
779
780         pkg_free(new_buf);
781 skip:
782         return 0;
783 error:
784         if (new_buf) pkg_free(new_buf);
785         return -1;
786 }