58f704ef0cbad82bfb3da3e61a1e6482c9403628
[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  */
53
54
55
56 #include <string.h>
57 #include <stdio.h>
58 #include <stdlib.h>
59 #include <sys/types.h>
60 #include <sys/socket.h>
61 #include <netdb.h>
62 #include <netinet/in.h>
63 #include <arpa/inet.h>
64
65 #include "forward.h"
66 #include "hash_func.h"
67 #include "config.h"
68 #include "parser/msg_parser.h"
69 #include "route.h"
70 #include "dprint.h"
71 #include "globals.h"
72 #include "data_lump.h"
73 #include "ut.h"
74 #include "mem/mem.h"
75 #include "msg_translator.h"
76 #include "sr_module.h"
77 #include "ip_addr.h"
78 #include "resolve.h"
79 #include "name_alias.h"
80 #include "socket_info.h"
81 #include "onsend.h"
82
83 #ifdef DEBUG_DMALLOC
84 #include <dmalloc.h>
85 #endif
86
87
88
89 /* return a socket_info_pointer to the sending socket; as opposed to
90  * get_send_socket, which returns process's default socket, get_out_socket
91  * attempts to determine the outbound interface which will be used;
92  * it creates a temporary connected socket to determine it; it will
93  * be very likely noticeably slower, but it can deal better with
94  * multihomed hosts
95  */
96 struct socket_info* get_out_socket(union sockaddr_union* to, int proto)
97 {
98         int temp_sock;
99         socklen_t len;
100         union sockaddr_union from; 
101         struct socket_info* si;
102         struct ip_addr ip;
103
104         if (proto!=PROTO_UDP) {
105                 LOG(L_CRIT, "BUG: get_out_socket can only be called for UDP\n");
106                 return 0;
107         }
108         
109         temp_sock=socket(to->s.sa_family, SOCK_DGRAM, 0 );
110         if (temp_sock==-1) {
111                 LOG(L_ERR, "ERROR: get_out_socket: socket() failed: %s\n",
112                                 strerror(errno));
113                 return 0;
114         }
115         if (connect(temp_sock, &to->s, sockaddru_len(*to))==-1) {
116                 LOG(L_ERR, "ERROR: get_out_socket: connect failed: %s\n",
117                                 strerror(errno));
118                 goto error;
119         }
120         len=sizeof(from);
121         if (getsockname(temp_sock, &from.s, &len)==-1) {
122                 LOG(L_ERR, "ERROR: get_out_socket: getsockname failed: %s\n",
123                                 strerror(errno));
124                 goto error;
125         }
126         su2ip_addr(&ip, &from);
127         si=find_si(&ip, 0, proto);
128         if (si==0) goto error;
129         close(temp_sock);
130         DBG("DEBUG: get_out_socket: socket determined: %p\n", si );
131         return si;
132 error:
133         LOG(L_ERR, "ERROR: get_out_socket: no socket found\n");
134         close(temp_sock);
135         return 0;
136 }
137
138
139
140 /* returns a socket_info pointer to the sending socket or 0 on error
141  * params: sip msg (can be null), destination socket_union pointer, protocol
142  * if msg!=null and msg->force_send_socket, the force_send_socket will be
143  * used
144  */
145 struct socket_info* get_send_socket(struct sip_msg *msg, 
146                                                                                 union sockaddr_union* to, int proto)
147 {
148         struct socket_info* send_sock;
149         
150         /* check if send interface is not forced */
151         if (msg && msg->force_send_socket){
152                 if (msg->force_send_socket->proto!=proto){
153                         DBG("get_send_socket: force_send_socket of different proto"
154                                         " (%d)!\n", proto);
155                         msg->force_send_socket=find_si(&(msg->force_send_socket->address),
156                                                                                         msg->force_send_socket->port_no,
157                                                                                         proto);
158                 }
159                 if (msg->force_send_socket && (msg->force_send_socket->socket!=-1)) 
160                         return msg->force_send_socket;
161                 else{
162                         if (msg->force_send_socket->socket==-1)
163                                 LOG(L_WARN, "WARNING: get_send_socket: not listening"
164                                                  " on the requested socket, no fork mode?\n");
165                         else
166                                 LOG(L_WARN, "WARNING: get_send_socket: "
167                                                 "protocol/port mismatch\n");
168                 }
169         };
170
171         if (mhomed && proto==PROTO_UDP){
172                 send_sock=get_out_socket(to, proto);
173                 if ((send_sock==0) || (send_sock->socket!=-1))
174                         return send_sock; /* found or error*/
175                 else if (send_sock->socket==-1){
176                         LOG(L_WARN, "WARNING: get_send_socket: not listening on the"
177                                         " requested socket, no fork mode?\n");
178                         /* continue: try to use some socket */
179                 }
180         }
181
182         send_sock=0;
183         /* check if we need to change the socket (different address families -
184          * eg: ipv4 -> ipv6 or ipv6 -> ipv4) */
185         switch(proto){
186 #ifdef USE_TCP
187                 case PROTO_TCP:
188                 /* on tcp just use the "main address", we don't really now the
189                  * sending address (we can find it out, but we'll need also to see
190                  * if we listen on it, and if yes on which port -> too complicated*/
191                         switch(to->s.sa_family){
192                                 /* FIXME */
193                                 case AF_INET:   send_sock=sendipv4_tcp;
194                                                                 break;
195 #ifdef USE_IPV6
196                                 case AF_INET6:  send_sock=sendipv6_tcp;
197                                                                 break;
198 #endif
199                                 default:        LOG(L_ERR, "get_send_socket: BUG: don't know how"
200                                                                         " to forward to af %d\n", to->s.sa_family);
201                         }
202                         break;
203 #endif
204 #ifdef USE_TLS
205                 case PROTO_TLS:
206                         switch(to->s.sa_family){
207                                 /* FIXME */
208                                 case AF_INET:   send_sock=sendipv4_tls;
209                                                                 break;
210 #ifdef USE_IPV6
211                                 case AF_INET6:  send_sock=sendipv6_tls;
212                                                                 break;
213 #endif
214                                 default:        LOG(L_ERR, "get_send_socket: BUG: don't know how"
215                                                                         " to forward to af %d\n", to->s.sa_family);
216                         }
217                         break;
218 #endif /* USE_TLS */
219                 case PROTO_UDP:
220                         if ((bind_address==0)||(to->s.sa_family!=bind_address->address.af)||
221                                   (bind_address->proto!=PROTO_UDP)){
222                                 switch(to->s.sa_family){
223                                         case AF_INET:   send_sock=sendipv4;
224                                                                         break;
225 #ifdef USE_IPV6
226                                         case AF_INET6:  send_sock=sendipv6;
227                                                                         break;
228 #endif
229                                         default:        LOG(L_ERR, "get_send_socket: BUG: don't know"
230                                                                                 " how to forward to af %d\n",
231                                                                                 to->s.sa_family);
232                                 }
233                         }else send_sock=bind_address;
234                         break;
235                 default:
236                         LOG(L_CRIT, "BUG: get_send_socket: unknown proto %d\n", proto);
237         }
238         return send_sock;
239 }
240
241
242
243 /* checks if the proto: host:port is one of the address we listen on;
244  * if port==0, the  port number is ignored
245  * if proto==0 (PROTO_NONE) the protocol is ignored
246  * returns 1 if true, 0 if false, -1 on error
247  * WARNING: uses str2ip6 so it will overwrite any previous
248  *  unsaved result of this function (static buffer)
249  */
250 int check_self(str* host, unsigned short port, unsigned short proto)
251 {
252         if (grep_sock_info(host, port, proto)) goto found;
253         /* try to look into the aliases*/
254         if (grep_aliases(host->s, host->len, port, proto)==0){
255                 DBG("check_self: host != me\n");
256                 return 0;
257         }
258 found:
259         return 1;
260 }
261
262
263
264 /* parameters:
265  *   msg - sip msg
266  *   p   - proxy structure to forward to
267  *   proto - protocol used
268  */
269 int forward_request(struct sip_msg* msg, struct proxy_l * p, int proto)
270 {
271         unsigned int len;
272         char* buf;
273         char md5[MD5_LEN];
274         struct dest_info send_info;
275         
276         buf=0;
277         
278         /* if error try next ip address if possible */
279         if (p->ok==0){
280                 if (p->host.h_addr_list[p->addr_idx+1])
281                         p->addr_idx++;
282                 else p->addr_idx=0;
283                 p->ok=1;
284         }
285         
286         hostent2su(&send_info.to, &p->host, p->addr_idx, 
287                                 (p->port)?p->port:SIP_PORT);
288         p->tx++;
289         p->tx_bytes+=len;
290         
291         
292         send_info.proto=proto;
293         send_info.id=0;
294         send_info.send_sock=get_send_socket(msg, &send_info.to,
295                                                                                         send_info.proto);
296         if (send_info.send_sock==0){
297                 LOG(L_ERR, "forward_req: ERROR: cannot forward to af %d, proto %d "
298                                 "no corresponding listening socket\n",
299                                 send_info.to.s.sa_family, send_info.proto);
300                 ser_error=E_NO_SOCKET;
301                 goto error;
302         }
303
304         /* calculate branch for outbound request;  if syn_branch is turned off,
305            calculate is from transaction key, i.e., as an md5 of From/To/CallID/
306            CSeq exactly the same way as TM does; good for reboot -- than messages
307            belonging to transaction lost due to reboot will still be forwarded
308            with the same branch parameter and will be match-able downstream
309
310        if it is turned on, we don't care about reboot; we simply put a simple
311            value in there; better for performance
312         */
313         if (syn_branch ) {
314                 *msg->add_to_branch_s='0';
315                 msg->add_to_branch_len=1;
316         } else {
317                 if (!char_msg_val( msg, md5 ))  { /* parses transaction key */
318                         LOG(L_ERR, "ERROR: forward_request: char_msg_val failed\n");
319                         goto error;
320                 }
321                 msg->hash_index=hash( msg->callid->body, get_cseq(msg)->number);
322                 if (!branch_builder( msg->hash_index, 0, md5, 0 /* 0-th branch */,
323                                         msg->add_to_branch_s, &msg->add_to_branch_len )) {
324                         LOG(L_ERR, "ERROR: forward_request: branch_builder failed\n");
325                         goto error;
326                 }
327         }
328
329         buf = build_req_buf_from_sip_req(msg, &len, send_info.send_sock,
330                                                                                         send_info.proto);
331         if (!buf){
332                 LOG(L_ERR, "ERROR: forward_request: building failed\n");
333                 goto error;
334         }
335          /* send it! */
336         DBG("Sending:\n%.*s.\n", (int)len, buf);
337         DBG("orig. len=%d, new_len=%d, proto=%d\n",
338                         msg->len, len, send_info.proto );
339         
340         if (run_onsend(msg, &send_info, buf, len)==0){
341                 LOG(L_INFO, "forward_request: request dropped (onsend_route)\n");
342                 STATS_TX_DROPS;
343                 goto error; /* error ? */
344         }
345         if (msg_send(&send_info, buf, len)<0){
346                 ser_error=E_SEND;
347                 p->errors++;
348                 p->ok=0;
349                 STATS_TX_DROPS;
350                 goto error;
351         }
352         
353         /* sent requests stats */
354         STATS_TX_REQUEST(  msg->first_line.u.request.method_value );
355         
356         pkg_free(buf);
357         /* received_buf & line_buf will be freed in receive_msg by free_lump_list*/
358         return 0;
359
360 error:
361         if (buf) pkg_free(buf);
362         return -1;
363 }
364
365
366
367 int update_sock_struct_from_via( union sockaddr_union* to,
368                                                                  struct sip_msg* msg,
369                                                                  struct via_body* via )
370 {
371         struct hostent* he;
372         str* name;
373         int err;
374         unsigned short port;
375
376         port=0;
377         if(via==msg->via1){ 
378                 /* _local_ reply, we ignore any rport or received value
379                  * (but we will send back to the original port if rport is
380                  *  present) */
381                 if ((msg->msg_flags&FL_FORCE_RPORT)||(via->rport))
382                         port=msg->rcv.src_port;
383                 else port=via->port;
384                 name=&(via->host); /* received=ip in 1st via is ignored (it's
385                                                           not added by us so it's bad) */
386         }else{
387                 /* "normal" reply, we use rport's & received value if present */
388                 if (via->rport && via->rport->value.s){
389                         DBG("update_sock_struct_from_via: using 'rport'\n");
390                         port=str2s(via->rport->value.s, via->rport->value.len, &err);
391                         if (err){
392                                 LOG(L_NOTICE, "ERROR: forward_reply: bad rport value(%.*s)\n",
393                                                 via->rport->value.len, via->rport->value.s);
394                                 port=0;
395                         }
396                 }
397                 if (via->received){
398                         DBG("update_sock_struct_from_via: using 'received'\n");
399                         name=&(via->received->value);
400                         /* making sure that we won't do SRV lookup on "received"
401                          * (possible if no DNS_IP_HACK is used)*/
402                         if (port==0) port=via->port?via->port:SIP_PORT; 
403                 }else{
404                         DBG("update_sock_struct_from_via: using via host\n");
405                         name=&(via->host);
406                         if (port==0) port=via->port;
407                 }
408         }
409         /* we do now a malloc/memcpy because gethostbyname loves \0-terminated 
410            strings; -jiri 
411            but only if host is not null terminated
412            (host.s[len] will always be ok for a via)
413             BTW: when is via->host.s non null terminated? tm copy? - andrei 
414             Yes -- it happened on generating a 408 by TM; -jiri
415             sip_resolvehost now accepts str -janakj
416         */
417         DBG("update_sock_struct_from_via: trying SRV lookup\n");
418         he=sip_resolvehost(name, &port, via->proto);
419         
420         if (he==0){
421                 LOG(L_NOTICE, "ERROR:forward_reply:resolve_host(%.*s) failure\n",
422                                 name->len, name->s);
423                 return -1;
424         }
425                 
426         hostent2su(to, he, 0, port);
427         return 1;
428 }
429
430
431
432 /* removes first via & sends msg to the second */
433 int forward_reply(struct sip_msg* msg)
434 {
435         char* new_buf;
436         struct dest_info dst;
437         unsigned int new_len;
438         struct sr_module *mod;
439 #ifdef USE_TCP
440         char* s;
441         int len;
442 #endif
443         memset(&dst, 0, sizeof(struct dest_info));      
444         new_buf=0;
445         /*check if first via host = us */
446         if (check_via){
447                 if (check_self(&msg->via1->host,
448                                         msg->via1->port?msg->via1->port:SIP_PORT,
449                                         msg->via1->proto)!=1){
450                         LOG(L_NOTICE, "ERROR: forward_reply: host in first via!=me :"
451                                         " %.*s:%d\n", msg->via1->host.len, msg->via1->host.s,
452                                                                         msg->via1->port);
453                         /* send error msg back? */
454                         goto error;
455                 }
456         }
457         /* quick hack, slower for multiple modules*/
458         for (mod=modules;mod;mod=mod->next){
459                 if ((mod->exports) && (mod->exports->response_f)){
460                         DBG("forward_reply: found module %s, passing reply to it\n",
461                                         mod->exports->name);
462                         if (mod->exports->response_f(msg)==0) goto skip;
463                 }
464         }
465
466         /* we have to forward the reply stateless, so we need second via -bogdan*/
467         if (parse_headers( msg, HDR_VIA2_F, 0 )==-1 
468                 || (msg->via2==0) || (msg->via2->error!=PARSE_OK))
469         {
470                 /* no second via => error */
471                 LOG(L_ERR, "ERROR: forward_reply: no 2nd via found in reply\n");
472                 goto error;
473         }
474
475         new_buf = build_res_buf_from_sip_res( msg, &new_len);
476         if (!new_buf){
477                 LOG(L_ERR, "ERROR: forward_reply: building failed\n");
478                 goto error;
479         }
480
481         dst.proto=msg->via2->proto;
482         if (update_sock_struct_from_via( &dst.to, msg, msg->via2 )==-1) goto error;
483
484
485 #ifdef USE_TCP
486         if (dst.proto==PROTO_TCP
487 #ifdef USE_TLS
488                         || dst.proto==PROTO_TLS
489 #endif
490                         ){
491                 /* find id in i param if it exists */
492                 if (msg->via1->i && msg->via1->i->value.s){
493                         s=msg->via1->i->value.s;
494                         len=msg->via1->i->value.len;
495                         DBG("forward_reply: i=%.*s\n",len, ZSW(s));
496                         if (reverse_hex2int(s, len, (unsigned int*)&dst.id)<0){
497                                 LOG(L_ERR, "ERROR: forward_reply: bad via i param \"%.*s\"\n",
498                                                 len, ZSW(s));
499                                         dst.id=0;
500                         }
501                 }               
502                                 
503         } 
504 #endif
505         if (msg_send(&dst, new_buf, new_len)<0) goto error;
506 #ifdef STATS
507         STATS_TX_RESPONSE(  (msg->first_line.u.reply.statuscode/100) );
508 #endif
509
510         DBG(" reply forwarded to %.*s:%d\n", 
511                         msg->via2->host.len, msg->via2->host.s,
512                         (unsigned short) msg->via2->port);
513
514         pkg_free(new_buf);
515 skip:
516         return 0;
517 error:
518         if (new_buf) pkg_free(new_buf);
519         return -1;
520 }