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