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