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