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