4 * Copyright (C) 2001-2003 FhG Fokus
6 * This file is part of ser, a free SIP server.
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
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:
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.
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
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)
64 #include <sys/types.h>
65 #include <sys/socket.h>
67 #include <netinet/in.h>
68 #include <arpa/inet.h>
71 #include "hash_func.h"
73 #include "parser/msg_parser.h"
78 #include "data_lump.h"
81 #include "msg_translator.h"
82 #include "sr_module.h"
85 #include "name_alias.h"
86 #include "socket_info.h"
89 #ifdef USE_DNS_FAILOVER
90 #include "dns_cache.h"
92 #ifdef USE_DST_BLACKLIST
93 #include "dst_blacklist.h"
95 #include "compiler_opt.h"
103 /* return a socket_info_pointer to the sending socket; as opposed to
104 * get_send_socket, which returns process's default socket, get_out_socket
105 * attempts to determine the outbound interface which will be used;
106 * it creates a temporary connected socket to determine it; it will
107 * be very likely noticeably slower, but it can deal better with
110 struct socket_info* get_out_socket(union sockaddr_union* to, int proto)
114 union sockaddr_union from;
115 struct socket_info* si;
118 if (proto!=PROTO_UDP) {
119 LOG(L_CRIT, "BUG: get_out_socket can only be called for UDP\n");
123 temp_sock=socket(to->s.sa_family, SOCK_DGRAM, 0 );
125 LOG(L_ERR, "ERROR: get_out_socket: socket() failed: %s\n",
129 if (connect(temp_sock, &to->s, sockaddru_len(*to))==-1) {
130 LOG(L_ERR, "ERROR: get_out_socket: connect failed: %s\n",
135 if (getsockname(temp_sock, &from.s, &len)==-1) {
136 LOG(L_ERR, "ERROR: get_out_socket: getsockname failed: %s\n",
140 su2ip_addr(&ip, &from);
141 si=find_si(&ip, 0, proto);
142 if (si==0) goto error;
144 DBG("DEBUG: get_out_socket: socket determined: %p\n", si );
147 LOG(L_ERR, "ERROR: get_out_socket: no socket found\n");
154 /* returns a socket_info pointer to the sending socket or 0 on error
155 * params: sip msg (can be null), destination socket_union pointer, protocol
156 * if msg!=null and msg->force_send_socket, the force_send_socket will be
159 struct socket_info* get_send_socket(struct sip_msg *msg,
160 union sockaddr_union* to, int proto)
162 struct socket_info* send_sock;
164 /* check if send interface is not forced */
165 if (unlikely(msg && msg->force_send_socket)){
166 if (unlikely(msg->force_send_socket->proto!=proto)){
167 DBG("get_send_socket: force_send_socket of different proto"
169 msg->force_send_socket=find_si(&(msg->force_send_socket->address),
170 msg->force_send_socket->port_no,
172 if (unlikely(msg->force_send_socket == 0)){
173 LOG(L_WARN, "WARNING: get_send_socket: "
174 "protocol/port mismatch\n");
178 if (likely((msg->force_send_socket->socket!=-1) &&
179 !(msg->force_send_socket->flags & SI_IS_MCAST)))
180 return msg->force_send_socket;
182 if (!(msg->force_send_socket->flags & SI_IS_MCAST))
183 LOG(L_WARN, "WARNING: get_send_socket: not listening"
184 " on the requested socket, no fork mode?\n");
188 if (mhomed && proto==PROTO_UDP){
189 send_sock=get_out_socket(to, proto);
190 if ((send_sock==0) || (send_sock->socket!=-1))
191 return send_sock; /* found or error*/
192 else if (send_sock->socket==-1){
193 LOG(L_WARN, "WARNING: get_send_socket: not listening on the"
194 " requested socket, no fork mode?\n");
195 /* continue: try to use some socket */
200 /* check if we need to change the socket (different address families -
201 * eg: ipv4 -> ipv6 or ipv6 -> ipv4) */
205 /* on tcp just use the "main address", we don't really now the
206 * sending address (we can find it out, but we'll need also to see
207 * if we listen on it, and if yes on which port -> too complicated*/
208 switch(to->s.sa_family){
210 case AF_INET: send_sock=sendipv4_tcp;
213 case AF_INET6: send_sock=sendipv6_tcp;
216 default: LOG(L_ERR, "get_send_socket: BUG: don't know how"
217 " to forward to af %d\n", to->s.sa_family);
223 switch(to->s.sa_family){
225 case AF_INET: send_sock=sendipv4_tls;
228 case AF_INET6: send_sock=sendipv6_tls;
231 default: LOG(L_ERR, "get_send_socket: BUG: don't know how"
232 " to forward to af %d\n", to->s.sa_family);
237 if ((bind_address==0)||(to->s.sa_family!=bind_address->address.af)||
238 (bind_address->proto!=PROTO_UDP)){
239 switch(to->s.sa_family){
240 case AF_INET: send_sock=sendipv4;
243 case AF_INET6: send_sock=sendipv6;
246 default: LOG(L_ERR, "get_send_socket: BUG: don't know"
247 " how to forward to af %d\n",
250 }else send_sock=bind_address;
253 LOG(L_CRIT, "BUG: get_send_socket: unknown proto %d\n", proto);
260 /* checks if the proto: host:port is one of the address we listen on;
261 * if port==0, the port number is ignored
262 * if proto==0 (PROTO_NONE) the protocol is ignored
263 * returns 1 if true, 0 if false, -1 on error
264 * WARNING: uses str2ip6 so it will overwrite any previous
265 * unsaved result of this function (static buffer)
267 int check_self(str* host, unsigned short port, unsigned short proto)
269 if (grep_sock_info(host, port, proto)) goto found;
270 /* try to look into the aliases*/
271 if (grep_aliases(host->s, host->len, port, proto)==0){
272 DBG("check_self: host != me\n");
279 /* checks if the proto:port is one of the ports we listen on;
280 * if proto==0 (PROTO_NONE) the protocol is ignored
281 * returns 1 if true, 0 if false, -1 on error
283 int check_self_port(unsigned short port, unsigned short proto)
285 if (grep_sock_info_by_port(port, proto))
286 /* as aliases do not contain different ports we can skip them */
294 /* forwards a request to dst
297 * dst - destination name, if non-null it will be resolved and
298 * send_info updated with the ip/port. Even if dst is non
299 * null send_info must contain the protocol and if a non
300 * default port or non srv. lookup is desired, the port must
302 * port - used only if dst!=0 (else the port in send_info->to is used)
303 * send_info - filled dest_info structure:
304 * if the send_socket member is null, a send_socket will be
305 * chosen automatically
306 * WARNING: don't forget to zero-fill all the unused members (a non-zero
307 * random id along with proto==PROTO_TCP can have bad consequences, same for
308 * a bogus send_socket value)
310 int forward_request(struct sip_msg* msg, str* dst, unsigned short port,
311 struct dest_info* send_info)
316 struct socket_info* orig_send_sock; /* initial send_sock */
318 struct ip_addr ip; /* debugging only */
319 #ifdef USE_DNS_FAILOVER
320 struct socket_info* prev_send_sock;
322 struct dns_srv_handle dns_srv_h;
330 orig_send_sock=send_info->send_sock;
334 #ifdef USE_DNS_FAILOVER
335 if (cfg_get(core, core_cfg, use_dns_failover)){
336 dns_srv_handle_init(&dns_srv_h);
337 err=dns_sip_resolve2su(&dns_srv_h, &send_info->to, dst, port,
338 &send_info->proto, dns_flags);
340 LOG(L_ERR, "ERROR: forward_request: resolving \"%.*s\""
341 " failed: %s [%d]\n", dst->len, ZSW(dst->s),
342 dns_strerror(err), err);
348 if (sip_hostport2su(&send_info->to, dst, port, &send_info->proto)<0){
349 LOG(L_ERR, "ERROR: forward_request: bad host name %.*s,"
350 " dropping packet\n", dst->len, ZSW(dst->s));
355 /* calculate branch for outbound request; if syn_branch is turned off,
356 calculate is from transaction key, i.e., as an md5 of From/To/CallID/
357 CSeq exactly the same way as TM does; good for reboot -- than messages
358 belonging to transaction lost due to reboot will still be forwarded
359 with the same branch parameter and will be match-able downstream
361 if it is turned on, we don't care about reboot; we simply put a simple
362 value in there; better for performance
365 *msg->add_to_branch_s='0';
366 msg->add_to_branch_len=1;
368 if (!char_msg_val( msg, md5 )) { /* parses transaction key */
369 LOG(L_ERR, "ERROR: forward_request: char_msg_val failed\n");
373 msg->hash_index=hash( msg->callid->body, get_cseq(msg)->number);
374 if (!branch_builder( msg->hash_index, 0, md5, 0 /* 0-th branch */,
375 msg->add_to_branch_s, &msg->add_to_branch_len )) {
376 LOG(L_ERR, "ERROR: forward_request: branch_builder failed\n");
381 /* try to send the message until success or all the ips are exhausted
382 * (if dns lookup is peformed && the dns cache used ) */
383 #ifdef USE_DNS_FAILOVER
386 if (orig_send_sock==0) /* no forced send_sock => find it **/
387 send_info->send_sock=get_send_socket(msg, &send_info->to,
389 if (send_info->send_sock==0){
390 LOG(L_ERR, "forward_req: ERROR: cannot forward to af %d, proto %d "
391 "no corresponding listening socket\n",
392 send_info->to.s.sa_family, send_info->proto);
393 ret=ser_error=E_NO_SOCKET;
394 #ifdef USE_DNS_FAILOVER
395 /* continue, maybe we find a socket for some other ip */
402 #ifdef USE_DNS_FAILOVER
403 if (prev_send_sock!=send_info->send_sock){
404 /* rebuild the message only if the send_sock changed */
405 prev_send_sock=send_info->send_sock;
407 if (buf) pkg_free(buf);
408 buf = build_req_buf_from_sip_req(msg, &len, send_info);
410 LOG(L_ERR, "ERROR: forward_request: building failed\n");
411 ret=E_OUT_OF_MEM; /* most probable */
414 #ifdef USE_DNS_FAILOVER
418 DBG("Sending:\n%.*s.\n", (int)len, buf);
419 DBG("orig. len=%d, new_len=%d, proto=%d\n",
420 msg->len, len, send_info->proto );
422 if (run_onsend(msg, send_info, buf, len)==0){
423 su2ip_addr(&ip, &send_info->to);
424 LOG(L_INFO, "forward_request: request to %s:%d(%d) dropped"
425 " (onsend_route)\n", ip_addr2a(&ip),
426 su_getport(&send_info->to), send_info->proto);
427 ser_error=E_OK; /* no error */
428 ret=E_ADM_PROHIBITED;
429 #ifdef USE_DNS_FAILOVER
430 continue; /* try another ip */
432 goto error; /* error ? */
435 #ifdef USE_DST_BLACKLIST
436 if (cfg_get(core, core_cfg, use_dst_blacklist)){
437 if (dst_is_blacklisted(send_info, msg)){
438 su2ip_addr(&ip, &send_info->to);
439 LOG(L_DBG, "DEBUG: blacklisted destination:%s:%d (%d)\n",
440 ip_addr2a(&ip), su_getport(&send_info->to),
442 ret=ser_error=E_SEND;
443 #ifdef USE_DNS_FAILOVER
444 continue; /* try another ip */
451 if (msg_send(send_info, buf, len)<0){
452 ret=ser_error=E_SEND;
453 #ifdef USE_DST_BLACKLIST
454 if (cfg_get(core, core_cfg, use_dst_blacklist))
455 dst_blacklist_add(BLST_ERR_SEND, send_info, msg);
457 #ifdef USE_DNS_FAILOVER
458 continue; /* try another ip */
464 /* sent requests stats */
465 STATS_TX_REQUEST( msg->first_line.u.request.method_value );
466 /* exit succcesfully */
469 #ifdef USE_DNS_FAILOVER
470 }while(dst && cfg_get(core, core_cfg, use_dns_failover) &&
471 dns_srv_handle_next(&dns_srv_h, err) &&
472 ((err=dns_sip_resolve2su(&dns_srv_h, &send_info->to, dst, port,
473 &send_info->proto, dns_flags))==0));
474 if ((err!=0) && (err!=-E_DNS_EOR)){
475 LOG(L_ERR, "ERROR: resolving %.*s host name in uri"
476 " failed: %s [%d] (dropping packet)\n",
477 dst->len, ZSW(dst->s),
478 dns_strerror(err), err);
479 ret=ser_error=E_BAD_ADDRESS;
487 #ifdef USE_DNS_FAILOVER
488 if (dst && cfg_get(core, core_cfg, use_dns_failover)){
489 dns_srv_handle_put(&dns_srv_h);
492 if (buf) pkg_free(buf);
493 /* received_buf & line_buf will be freed in receive_msg by free_lump_list*/
499 int update_sock_struct_from_via( union sockaddr_union* to,
501 struct via_body* via )
511 /* _local_ reply, we ignore any rport or received value
512 * (but we will send back to the original port if rport is
514 if ((msg->msg_flags&FL_FORCE_RPORT)||(via->rport))
515 port=msg->rcv.src_port;
517 name=&(via->host); /* received=ip in 1st via is ignored (it's
518 not added by us so it's bad) */
520 /* "normal" reply, we use rport's & received value if present */
521 if (via->rport && via->rport->value.s){
522 DBG("update_sock_struct_from_via: using 'rport'\n");
523 port=str2s(via->rport->value.s, via->rport->value.len, &err);
525 LOG(L_NOTICE, "ERROR: forward_reply: bad rport value(%.*s)\n",
526 via->rport->value.len, via->rport->value.s);
531 DBG("update_sock_struct_from_via: using 'received'\n");
532 name=&(via->received->value);
533 /* making sure that we won't do SRV lookup on "received"
534 * (possible if no DNS_IP_HACK is used)*/
535 if (port==0) port=via->port?via->port:SIP_PORT;
537 DBG("update_sock_struct_from_via: using via host\n");
539 if (port==0) port=via->port;
542 /* we do now a malloc/memcpy because gethostbyname loves \0-terminated
544 but only if host is not null terminated
545 (host.s[len] will always be ok for a via)
546 BTW: when is via->host.s non null terminated? tm copy? - andrei
547 Yes -- it happened on generating a 408 by TM; -jiri
548 sip_resolvehost now accepts str -janakj
550 DBG("update_sock_struct_from_via: trying SRV lookup\n");
552 he=sip_resolvehost(name, &port, &proto);
555 LOG(L_NOTICE, "ERROR:forward_reply:resolve_host(%.*s) failure\n",
560 hostent2su(to, he, 0, port);
566 /* removes first via & sends msg to the second */
567 int forward_reply(struct sip_msg* msg)
570 struct dest_info dst;
571 unsigned int new_len;
577 init_dest_info(&dst);
579 /*check if first via host = us */
581 if (check_self(&msg->via1->host,
582 msg->via1->port?msg->via1->port:SIP_PORT,
583 msg->via1->proto)!=1){
584 LOG(L_NOTICE, "ERROR: forward_reply: host in first via!=me :"
585 " %.*s:%d\n", msg->via1->host.len, msg->via1->host.s,
587 /* send error msg back? */
592 /* check modules response_f functions */
593 for (r=0; r<mod_response_cbk_no; r++)
594 if (mod_response_cbks[r](msg)==0) goto skip;
595 /* we have to forward the reply stateless, so we need second via -bogdan*/
596 if (parse_headers( msg, HDR_VIA2_F, 0 )==-1
597 || (msg->via2==0) || (msg->via2->error!=PARSE_OK))
599 /* no second via => error */
600 LOG(L_ERR, "ERROR: forward_reply: no 2nd via found in reply\n");
604 new_buf = build_res_buf_from_sip_res( msg, &new_len);
606 LOG(L_ERR, "ERROR: forward_reply: building failed\n");
610 dst.proto=msg->via2->proto;
611 if (update_sock_struct_from_via( &dst.to, msg, msg->via2 )==-1) goto error;
613 dst.comp=msg->via2->comp_no;
617 if (dst.proto==PROTO_TCP
619 || dst.proto==PROTO_TLS
622 /* find id in i param if it exists */
623 if (msg->via1->i && msg->via1->i->value.s){
624 s=msg->via1->i->value.s;
625 len=msg->via1->i->value.len;
626 DBG("forward_reply: i=%.*s\n",len, ZSW(s));
627 if (reverse_hex2int(s, len, (unsigned int*)&dst.id)<0){
628 LOG(L_ERR, "ERROR: forward_reply: bad via i param \"%.*s\"\n",
636 if (msg_send(&dst, new_buf, new_len)<0) goto error;
638 STATS_TX_RESPONSE( (msg->first_line.u.reply.statuscode/100) );
641 DBG(" reply forwarded to %.*s:%d\n",
642 msg->via2->host.len, msg->via2->host.s,
643 (unsigned short) msg->via2->port);
649 if (new_buf) pkg_free(new_buf);