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