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