Coverage Report

Created: 2026-07-16 06:51

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/opensips/forward.c
Line
Count
Source
1
/*
2
 * Copyright (C) 2001-2003 FhG Fokus
3
 * Copyright (C) 2005-2009 Voice Sistem SRL
4
 *
5
 * This file is part of opensips, a free SIP server.
6
 *
7
 * opensips is free software; you can redistribute it and/or modify
8
 * it under the terms of the GNU General Public License as published by
9
 * the Free Software Foundation; either version 2 of the License, or
10
 * (at your option) any later version
11
 *
12
 * opensips is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU General Public License
18
 * along with this program; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
20
 *
21
 * History:
22
 * -------
23
 *  2001-??-??  created by andrei
24
 *  ????-??-??  lots of changes by a lot of people
25
 *  2003-01-23  support for determination of outbound interface added :
26
 *               get_out_socket (jiri)
27
 *  2003-01-24  reply to rport support added, contributed by
28
 *               Maxim Sobolev <sobomax@FreeBSD.org> and modified by andrei
29
 *  2003-02-11  removed calls to upd_send & tcp_send & replaced them with
30
 *               calls to msg_send (andrei)
31
 *  2003-03-19  replaced all mallocs/frees w/ pkg_malloc/pkg_free (andrei)
32
 *  2003-04-02  fixed get_send_socket for tcp fwd to udp (andrei)
33
 *  2003-04-03  added su_setport (andrei)
34
 *  2003-04-04  update_sock_struct_from_via now differentiates between
35
 *               local replies  & "normal" replies (andrei)
36
 *  2003-04-12  update_sock_struct_from via uses also FL_FORCE_RPORT for
37
 *               local replies (andrei)
38
 *  2003-08-21  check_self properly handles ipv6 addresses & refs   (andrei)
39
 *  2003-10-21  check_self updated to handle proto (andrei)
40
 *  2003-10-24  converted to the new socket_info lists (andrei)
41
 *  2004-10-10  modified check_self to use grep_sock_info (andrei)
42
 *  2004-11-08  added force_send_socket support in get_send_socket (andrei)
43
 *  2006-09-06  added new algorithm for building VIA branch parameter for
44
 *              stateless requests - it complies to RFC3261 requirement to be
45
 *              unique through time and space (bogdan)
46
 */
47
48
/*!
49
 * \file
50
 * \brief OpenSIPS Stateless forward support
51
 */
52
53
54
#include <string.h>
55
#include <stdio.h>
56
#include <stdlib.h>
57
#include <errno.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 "parser/msg_parser.h"
66
#include "parser/parse_from.h"
67
#include "dprint.h"
68
#include "ut.h"
69
#include "dset.h"
70
#include "mem/mem.h"
71
#include "msg_translator.h"
72
#include "sr_module.h"
73
#include "ip_addr.h"
74
#include "resolve.h"
75
#include "net/trans.h"
76
#include "name_alias.h"
77
#include "socket_info.h"
78
#include "core_stats.h"
79
#include "blacklists.h"
80
#include "msg_callbacks.h"
81
#include "md5utils.h"
82
83
84
85
/*! \brief return a socket_info_pointer to the sending socket
86
 * \note As opposed to
87
 * get_send_socket(), which returns process's default socket, get_out_socket
88
 * attempts to determine the outbound interface which will be used;
89
 * it creates a temporary connected socket to determine it; it will
90
 * be very likely noticeably slower, but it can deal better with
91
 * multihomed hosts
92
 */
93
const struct socket_info* get_out_socket(const union sockaddr_union* to, int proto)
94
0
{
95
0
  int temp_sock;
96
0
  socklen_t len;
97
0
  union sockaddr_union from;
98
0
  const struct socket_info* si;
99
0
  struct ip_addr ip, ip_dst;
100
101
0
  if (proto!=PROTO_UDP) {
102
0
    LM_CRIT("can only be called for UDP\n");
103
0
    return 0;
104
0
  }
105
106
0
  temp_sock=socket(to->s.sa_family, SOCK_DGRAM, 0 );
107
0
  if (temp_sock==-1) {
108
0
    LM_ERR("socket() failed: %s\n", strerror(errno));
109
0
    return 0;
110
0
  }
111
0
  if (connect(temp_sock, &to->s, sockaddru_len(*to))==-1) {
112
0
    LM_ERR("connect failed: %s\n", strerror(errno));
113
0
    goto error;
114
0
  }
115
0
  len=sizeof(from);
116
0
  if (getsockname(temp_sock, &from.s, &len)==-1) {
117
0
    LM_ERR("getsockname failed: %s\n", strerror(errno));
118
0
    goto error;
119
0
  }
120
0
  su2ip_addr(&ip, &from);
121
0
  si=find_si(&ip, 0, proto);
122
0
  if (si==0) {
123
0
    LM_ERR("outbound IP %s not found as listener\n", ip_addr2a(&ip));
124
0
    goto error;
125
0
  }
126
0
  close(temp_sock);
127
0
  LM_DBG("socket determined: %p\n", si );
128
0
  return si;
129
0
error:
130
0
  su2ip_addr( &ip_dst, to);
131
0
  LM_ERR("failed to find route to %s\n", ip_addr2a(&ip_dst));
132
0
  close(temp_sock);
133
0
  return 0;
134
0
}
135
136
137
138
/*! \brief returns a socket_info pointer to the sending socket or 0 on error
139
 * \param msg SIP message (can be null)
140
 * \param to  destination socket_union pointer
141
 * \param proto protocol
142
 *
143
 * \note if msg!=null and msg->force_send_socket, the force_send_socket will be used
144
 */
145
const struct socket_info* get_send_socket(struct sip_msg *msg,
146
                  const union sockaddr_union* to, int proto)
147
0
{
148
0
  const struct socket_info* send_sock, *bond_sock;
149
0
  struct socket_info_ref *bond_ref;
150
151
  /* check if send interface is not forced */
152
0
  if (msg && msg->force_send_socket){
153
0
    if (msg->force_send_socket->proto == PROTO_BOND) {
154
155
0
      bond_sock = msg->force_send_socket;
156
0
      msg->force_send_socket = NULL;
157
0
      for (bond_ref = bond_sock->bond_sis;
158
0
          bond_ref; bond_ref = bond_ref->next) {
159
160
0
        LM_DBG("checking socket [%.*s]:%d AF %d for "
161
0
          "destination  proto=%d and AF=%d\n",
162
0
          bond_ref->si->sock_str.len, bond_ref->si->sock_str.s,
163
0
          bond_ref->si->proto, bond_ref->si->address.af,
164
0
          proto, to->s.sa_family);
165
0
        if (!bond_ref->si ||
166
0
        (bond_ref->si->proto != proto) ||
167
0
        (bond_ref->si->address.af != to->s.sa_family))
168
0
          continue;
169
170
0
        msg->force_send_socket = bond_ref->si;
171
0
        LM_DBG("bond socket [%.*s] translated into [%.*s] for "
172
0
          "destination  proto=%d and AF=%d\n",
173
0
          bond_sock->name.len, bond_sock->name.s,
174
0
          bond_ref->si->sock_str.len, bond_ref->si->sock_str.s,
175
0
          proto, to->s.sa_family);
176
0
        break;
177
0
      }
178
179
0
      if (!msg->force_send_socket)
180
0
        LM_DBG("no bond member matching proto=%d and AF=%d\n",
181
0
          proto, to->s.sa_family);
182
0
    } else
183
    /* no bond forced socket, do extra checks */
184
0
    if (msg->force_send_socket->proto!=proto){
185
0
      LM_DBG("force_send_socket of different proto (%d)!\n", proto);
186
0
      msg->force_send_socket=find_si(&(msg->force_send_socket->address),
187
0
                      msg->force_send_socket->port_no,
188
0
                      proto);
189
0
    } else
190
0
    if (msg->force_send_socket->address.af!=to->s.sa_family){
191
0
      LM_DBG("force_send_socket of different AF (sock=%d, dst=%d)!\n",
192
0
        msg->force_send_socket->address.af, to->s.sa_family);
193
0
      msg->force_send_socket=NULL;
194
0
    } else
195
0
    if (msg->force_send_socket)
196
0
      return msg->force_send_socket;
197
0
    else
198
0
      LM_WARN("protocol/port/af mismatch\n");
199
0
  };
200
201
0
  if (mhomed && proto==PROTO_UDP)
202
0
    return get_out_socket(to, proto);
203
204
0
  send_sock=0;
205
  /* check if we need to change the socket (different address families -
206
   * eg: ipv4 -> ipv6 or ipv6 -> ipv4) */
207
0
  switch(proto){
208
0
    case PROTO_UDP:
209
0
      if (msg && msg->rcv.bind_address &&
210
0
      msg->rcv.bind_address->address.af==to->s.sa_family &&
211
0
      msg->rcv.bind_address->proto==PROTO_UDP) {
212
0
        send_sock = msg->rcv.bind_address;
213
0
        break;
214
0
      }
215
      /* default logic for all protos */
216
0
    default:
217
      /* we don't really know the sending address (we can find it out,
218
       * but we'll need also to see if we listen on it, and if yes on
219
       * which port -> too complicated*/
220
0
      send_sock = (to->s.sa_family==AF_INET) ?
221
0
        protos[proto].sendipv4 : protos[proto].sendipv6;
222
0
  }
223
0
  return send_sock;
224
0
}
225
226
227
228
/*! \brief checks if the proto: host:port is one of the address we listen on
229
 *
230
 * if port==0, the  port number is ignored
231
 * if proto==0 (PROTO_NONE) the protocol is ignored
232
 * returns 1 if true, 0 if false, -1 on error
233
 * WARNING: uses str2ip6 so it will overwrite any previous
234
 *  unsaved result of this function (static buffer)
235
 */
236
int check_self(str* host, unsigned short port, unsigned short proto)
237
0
{
238
0
  if (grep_sock_info(host, port, proto)) goto found;
239
  /* try to look into the aliases*/
240
0
  if (grep_aliases(host->s, host->len, port, proto)==0){
241
0
    LM_DBG("host != me\n");
242
0
    return 0;
243
0
  }
244
0
found:
245
0
  return 1;
246
0
}
247
248
249
250
static inline int set_sl_branch(struct sip_msg* msg)
251
0
{
252
0
  struct hdr_field *h_via;
253
0
  struct via_body  *b_via;
254
0
  str *branch;
255
0
  int via_parsed;
256
0
  char b_md5[MD5_LEN];
257
258
0
  via_parsed = 0;
259
0
  branch = 0;
260
261
  /* first VIA header must be parsed */
262
0
  for( h_via=msg->h_via1 ; h_via ; h_via=h_via->sibling ) {
263
264
0
    b_via = (struct via_body*)h_via->parsed;
265
0
    for( ; b_via ; b_via=b_via->next ) {
266
      /* check if there is any valid branch param */
267
0
      if (b_via->branch==0 || b_via->branch->value.s==0
268
0
      || b_via->branch->value.len==0 )
269
0
        continue;
270
0
      branch = &b_via->branch->value;
271
      /* check if the branch param has the magic cookie */
272
0
      if (branch->len <= (int)MCOOKIE_LEN
273
0
      || memcmp( branch->s, MCOOKIE, MCOOKIE_LEN)!=0 )
274
0
        continue;
275
      /* found a statefull branch -> use it */
276
0
      goto found;
277
0
    }
278
279
0
    if (!via_parsed) {
280
0
      if ( parse_headers(msg,HDR_EOH_F,0)<0 ) {
281
0
        LM_ERR("failed to parse all hdrs\n");
282
0
        return -1;
283
0
      }
284
0
      via_parsed = 1;
285
0
    }
286
0
  }
287
288
  /* no statefull branch :(.. -> use the branch from the last via */
289
0
found:
290
0
  if (branch==NULL) {
291
    /* no branch found :(.. -> try to use the From TAG param as 
292
     * a value to seed the MD5 - the From TAG is per call, so it gives
293
     * a bit of uniqueness; if this is empty, as a last resort, use the 
294
     * FROM URI (it cannot mis) */
295
0
    if ( parse_from_header(msg)!=0 )
296
0
    {
297
0
      LM_ERR("failed to extract FROM header\n");
298
0
      return -1;
299
0
    }
300
0
    if ( get_from(msg)->tag_value.len )
301
0
      branch = &get_from(msg)->tag_value;
302
0
    else
303
0
      branch = &get_from(msg)->uri;
304
0
  }
305
306
  /* make an MD5 over the found branch, to ensure a controlable 
307
   * length of the resulting branch */
308
0
  MD5StringArray ( b_md5, branch, 1 );
309
  /* and make a hash over transaction-related values */
310
0
  if ( parse_headers(msg, HDR_CALLID_F|HDR_CSEQ_F,0)==-1 ||
311
0
    msg->callid==NULL || msg->cseq==NULL )
312
0
  {
313
0
    LM_ERR("failed to extract CALLID or CSEQ hdr from SIP msg\n");
314
0
    return -1;
315
0
  }
316
  /* build the new branch */
317
0
  if (branch_builder(
318
0
    core_hash( &msg->callid->body, &get_cseq(msg)->number, 1<<16 ),
319
0
    0 /*labled - not used here */,
320
0
    b_md5,
321
0
    0 /*branch - not used here */,
322
0
    msg->add_to_branch_s, &msg->add_to_branch_len )==0 )
323
0
  {
324
0
    LM_ERR("branch_builder failed to construct the branch\n");
325
0
    return -1;
326
0
  }
327
328
0
  return 0;
329
0
}
330
331
332
333
int forward_request( struct sip_msg* msg, struct proxy_l * p)
334
0
{
335
0
  union sockaddr_union to;
336
0
  str buf;
337
0
  const struct socket_info* send_sock;
338
0
  const struct socket_info* last_sock;
339
340
0
  buf.s=NULL;
341
342
  /* calculate branch for outbound request - if the branch buffer is already
343
   * set (maybe by an upper level as TM), used it; otherwise computes
344
   * the branch for stateless fwd. . According to the latest discussions
345
   * on the topic, you should reuse the latest statefull branch
346
   * --bogdan */
347
0
  if ( msg->add_to_branch_len==0 ) {
348
0
    if (set_sl_branch(msg)!=0) {
349
0
      LM_ERR("unable to compute and add stateless VIA branch\n");
350
0
      goto error;
351
0
    }
352
0
  }
353
354
0
  msg_callback_process(msg, REQ_PRE_FORWARD, (void *)p);
355
356
0
  hostent2su( &to, &p->host, p->addr_idx, (p->port)?p->port:SIP_PORT);
357
0
  last_sock = 0;
358
359
0
  if (getb0flags(msg) & tcp_no_new_conn_bflag)
360
0
    tcp_no_new_conn = 1;
361
362
0
  do {
363
0
    send_sock=get_send_socket( msg, &to, p->proto);
364
0
    if (send_sock==0){
365
0
      LM_ERR("cannot forward to af %d, proto %d no corresponding"
366
0
        "listening socket\n", to.s.sa_family, p->proto);
367
0
      ser_error=E_NO_SOCKET;
368
0
      continue;
369
0
    }
370
371
0
    if ( last_sock!=send_sock ) {
372
373
0
      if (buf.s)
374
0
        pkg_free(buf.s);
375
376
0
      buf.s = build_req_buf_from_sip_req( msg, (unsigned int*)&buf.len,
377
0
        send_sock, p->proto, NULL, 0 /*flags*/);
378
0
      if (!buf.s){
379
0
        LM_ERR("building req buf failed\n");
380
0
        tcp_no_new_conn = 0;
381
0
        goto error;
382
0
      }
383
384
0
      last_sock = send_sock;
385
0
    }
386
387
0
    if (check_blacklists( p->proto, &to, buf.s, buf.len)) {
388
0
      LM_DBG("blocked by blacklists\n");
389
0
      ser_error=E_IP_BLOCKED;
390
0
      continue;
391
0
    }
392
393
    /* send it! */
394
0
    LM_DBG("sending:\n%.*s.\n", buf.len, buf.s);
395
0
    LM_DBG("orig. len=%d, new_len=%d, proto=%d\n",
396
0
      msg->len, buf.len, p->proto );
397
398
0
    if (msg_send(send_sock, p->proto, &to, 0, buf.s, buf.len, msg)<0){
399
0
      ser_error=E_SEND;
400
0
      continue;
401
0
    }
402
403
0
    slcb_run_req_out( msg, &buf, &to, send_sock, p->proto);
404
405
0
    ser_error = 0;
406
0
    break;
407
408
0
  }while( get_next_su( p, &to, (ser_error==E_IP_BLOCKED)?0:1)==0 );
409
410
0
  tcp_no_new_conn = 0;
411
412
0
  if (ser_error) {
413
0
    update_stat( drp_reqs, 1);
414
0
    goto error;
415
0
  }
416
417
  /* sent requests stats */
418
0
  update_stat( fwd_reqs, 1);
419
420
0
  pkg_free(buf.s);
421
  /* received_buf & line_buf will be freed in receive_msg by free_lump_list*/
422
0
  return 0;
423
424
0
error:
425
0
  if (buf.s) pkg_free(buf.s);
426
0
  return -1;
427
0
}
428
429
430
431
int update_sock_struct_from_via( union sockaddr_union* to,
432
                 struct sip_msg* msg,
433
                 struct via_body* via )
434
0
{
435
0
  struct hostent* he;
436
0
  str* name;
437
0
  int err;
438
0
  unsigned short port;
439
440
0
  port=0;
441
0
  if(via==msg->via1){
442
    /* _local_ reply, we ignore any rport or received value
443
     * (but we will send back to the original port if rport is
444
     *  present) */
445
0
    if ((msg->msg_flags&FL_FORCE_RPORT)||(via->rport))
446
0
      port=msg->rcv.src_port;
447
0
    else port=via->port;
448
0
    if(via->maddr)
449
0
      name= &(via->maddr->value);
450
0
    else
451
0
      name=&(via->host); /* received=ip in 1st via is ignored (it's
452
                not added by us so it's bad) */
453
0
  }else{
454
    /* "normal" reply, we use rport's & received value if present */
455
0
    if (via->rport && via->rport->value.s){
456
0
      LM_DBG("using 'rport'\n");
457
0
      port=str2s(via->rport->value.s, via->rport->value.len, &err);
458
0
      if (err){
459
0
        LM_NOTICE("bad rport value(%.*s)\n",
460
0
          via->rport->value.len,via->rport->value.s);
461
0
        port=0;
462
0
      }
463
0
    }
464
465
0
    if (via->maddr){
466
0
      name= &(via->maddr->value);
467
0
      if (port==0) port=via->port?via->port:SIP_PORT;
468
0
    } else if (via->received){
469
0
      LM_DBG("using 'received'\n");
470
0
      name=&(via->received->value);
471
      /* making sure that we won't do SRV lookup on "received" */
472
0
      if (port==0) port=via->port?via->port:SIP_PORT;
473
0
    }else{
474
0
      LM_DBG("using via host\n");
475
0
      name=&(via->host);
476
0
      if (port==0) port=via->port;
477
0
    }
478
0
  }
479
0
  LM_DBG("trying SRV lookup\n");
480
0
  he=sip_resolvehost(name, &port, &via->proto, 0, 0);
481
482
0
  if (he==0){
483
0
    LM_NOTICE("resolve_host(%.*s) failure\n", name->len, name->s);
484
0
    return -1;
485
0
  }
486
487
0
  hostent2su( to, he, 0, port);
488
0
  return 1;
489
0
}
490
491
492
493
/*! \brief removes first via & sends msg to the second */
494
int forward_reply(struct sip_msg* msg)
495
0
{
496
0
  char* new_buf;
497
0
  union sockaddr_union* to;
498
0
  unsigned int new_len;
499
0
  struct sr_module *mod;
500
0
  int proto;
501
0
  unsigned int id; /* used only by tcp*/
502
0
  const struct socket_info *send_sock;
503
0
  char* s;
504
0
  int len;
505
506
0
  to=0;
507
0
  id=0;
508
0
  new_buf=0;
509
  /*check if first via host = us */
510
0
  if (check_via){
511
0
    if (check_self(&msg->via1->host,
512
0
          msg->via1->port?msg->via1->port:SIP_PORT,
513
0
          msg->via1->proto)!=1){
514
0
      LM_ERR("host in first via!=me : %.*s:%d\n",
515
0
        msg->via1->host.len, msg->via1->host.s, msg->via1->port);
516
      /* send error msg back? */
517
0
      goto error;
518
0
    }
519
0
  }
520
  /* quick hack, slower for multiple modules*/
521
0
  for (mod=modules;mod;mod=mod->next){
522
0
    if ((mod->exports) && (mod->exports->response_f)){
523
0
      LM_DBG("found module %s, passing reply to it\n",
524
0
          mod->exports->name);
525
0
      if (mod->exports->response_f(msg)==0) goto skip;
526
0
    }
527
0
  }
528
529
  /* if stateless fwd was disabled, we cannot have stateless replies here*/
530
0
  if (sl_fwd_disabled)
531
0
    goto skip;
532
533
  /* we have to forward the reply stateless, so we need second via -bogdan*/
534
0
  if (parse_headers( msg, HDR_VIA2_F, 0 )==-1
535
0
    || (msg->via2==0) || (msg->via2->error!=PARSE_OK))
536
0
  {
537
    /* no second via => error */
538
0
    LM_ERR("no 2nd via found in [%.*s] [%.*s] reply from [%s] for callid [%.*s]\n",
539
0
      msg->first_line.u.reply.status.len, msg->first_line.u.reply.status.s,
540
0
      msg->cseq->body.len, msg->cseq->body.s,
541
0
      ip_addr2a(&msg->rcv.src_ip),
542
0
      msg->callid->body.len, msg->callid->body.s);
543
0
    goto error;
544
0
  }
545
546
0
  to=(union sockaddr_union*)pkg_malloc(sizeof(union sockaddr_union));
547
0
  if (to==0){
548
0
    LM_ERR("out of pkg memory\n");
549
0
    goto error;
550
0
  }
551
552
0
  proto=msg->via2->proto;
553
0
  if (update_sock_struct_from_via( to, msg, msg->via2 )==-1) goto error;
554
555
0
  if (is_tcp_based_proto(proto)){
556
    /* find id in i param if it exists */
557
0
    if (msg->via1->i&&msg->via1->i->value.s){
558
0
      s=msg->via1->i->value.s;
559
0
      len=msg->via1->i->value.len;
560
0
      if (reverse_hex2int(s, len, &id)<0)
561
0
        id = 0;
562
0
    }
563
0
  }
564
565
0
  send_sock = get_send_socket(msg, to, proto);
566
567
0
  new_buf = build_res_buf_from_sip_res( msg, &new_len, send_sock,0);
568
0
  if (!new_buf){
569
0
    LM_ERR("failed to build rpl from req failed\n");
570
0
    goto error;
571
0
  }
572
573
0
  if (msg->flags & tcp_no_new_conn_rplflag)
574
0
    tcp_no_new_conn = 1;
575
576
0
  if (msg_send(send_sock, proto, to, id, new_buf, new_len, msg)<0) {
577
0
    tcp_no_new_conn = 0;
578
0
    update_stat( drp_rpls, 1);
579
0
    goto error0;
580
0
  }
581
0
  tcp_no_new_conn = 0;
582
583
0
  update_stat( fwd_rpls, 1);
584
  /*
585
   * If no port is specified in the second via, then this
586
   * message output a wrong port number - zero. Despite that
587
   * the correct port is choosen in update_sock_struct_from_via,
588
   * as its visible with su_getport(to); .
589
   */
590
0
  LM_DBG("reply forwarded to %.*s:%d\n", msg->via2->host.len,
591
0
    msg->via2->host.s, (unsigned short) msg->via2->port);
592
593
0
  pkg_free(new_buf);
594
0
  pkg_free(to);
595
0
skip:
596
0
  return 0;
597
0
error:
598
0
  update_stat( err_rpls, 1);
599
0
error0:
600
0
  if (new_buf) pkg_free(new_buf);
601
0
  if (to) pkg_free(to);
602
0
  return -1;
603
0
}