Coverage Report

Created: 2026-10-28 06:08

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/opensips/socket_info.c
Line
Count
Source
1
/*
2
 * Copyright (C) 2001-2003 FhG Fokus
3
 *
4
 * This file is part of opensips, a free SIP server.
5
 *
6
 * opensips is free software; you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation; either version 2 of the License, or
9
 * (at your option) any later version
10
 *
11
 * opensips is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
19
 *
20
 *
21
 * This file contains code that initializes and handles ser listen addresses
22
 * lists (struct socket_info). It is used mainly on startup.
23
 *
24
 * History:
25
 * --------
26
 *  2003-10-22  created by andrei
27
 *  2004-10-10  added grep_sock_info (andrei)
28
 *  2004-11-08  added find_si (andrei)
29
 *  2007-01-11  auto_aliases option added (bogdan)
30
 */
31
32
/*!
33
 * \file
34
 * \brief Find & manage listen addresses
35
 */
36
37
38
#include <string.h>
39
#include <errno.h>
40
#include <unistd.h>
41
#include <sys/types.h>
42
#include <sys/socket.h>
43
#include <sys/utsname.h>
44
#include <stdio.h>
45
46
#include <sys/ioctl.h>
47
#include <net/if.h>
48
#ifdef HAVE_SYS_SOCKIO_H
49
#include <sys/sockio.h>
50
#endif
51
52
#include "str.h"
53
#include "globals.h"
54
#include "socket_info.h"
55
#include "dprint.h"
56
#include "mem/mem.h"
57
#include "ut.h"
58
#include "pt_scaling.h"
59
#include "resolve.h"
60
#include "name_alias.h"
61
#include "net/trans.h"
62
63
#ifdef __OS_linux
64
#include <features.h>     /* for GLIBC version testing */
65
#if defined(__GLIBC_PREREQ)
66
#if __GLIBC_PREREQ(2, 4)
67
#include <ifaddrs.h>
68
#define HAVE_IFADDRS
69
#endif
70
#endif
71
#endif
72
73
0
#define MAX_PROC_BUFFER 256
74
75
/* list manip. functions (internal use only) */
76
77
/* list with BOND sockets only - this is pretty static right now */
78
static struct socket_info_full *bond_sockets;
79
80
/* append */
81
#define sock_listadd(head, el) \
82
0
  do{\
83
0
    if (*(head)==0) *(head)=(el); \
84
0
    else{ \
85
0
      for((el)->next=*(head); (el)->next->next;\
86
0
          (el)->next=(el)->next->next); \
87
0
      (el)->next->next=(el); \
88
0
      (el)->prev=(el)->next; \
89
0
      (el)->next=0; \
90
0
    }\
91
0
  }while(0)
92
93
94
/* insert after "after" */
95
#define sock_listins(el, after) \
96
  do{ \
97
    if ((after)){\
98
      (el)->next=(after)->next; \
99
      if ((after)->next) (after)->next->prev=(el); \
100
      (after)->next=(el); \
101
      (el)->prev=(after); \
102
    }else{ /* after==0 = list head */ \
103
      (after)=(el); \
104
      (el)->next=(el)->prev=0; \
105
    }\
106
  }while(0)
107
108
109
#define sock_listrm(head, el) \
110
0
  do {\
111
0
    if (*(head)==(el)) *(head)=(el)->next; \
112
0
    if ((el)->next) (el)->next->prev=(el)->prev; \
113
0
    if ((el)->prev) (el)->prev->next=(el)->next; \
114
0
  }while(0)
115
116
117
/* another helper function, it just creates a socket_info struct */
118
struct socket_info_full* new_sock_info(struct socket_id *sid, str *orig_name)
119
0
{
120
0
  struct socket_info_full *sif;
121
0
  struct socket_info *si;
122
123
0
  sif=(struct socket_info_full*) pkg_malloc(sizeof(*sif));
124
0
  if (sif==NULL) goto error;
125
0
  memset(sif, 0, sizeof(*sif));
126
0
  si = &sif->socket_info;
127
0
  si->socket=-1;
128
0
  si->last_real_ports = &sif->last_real_ports;
129
130
0
  if (sid->name) {
131
0
    si->name.len=strlen(sid->name);
132
0
    si->name.s=(char*)pkg_malloc(si->name.len+1); /* include \0 */
133
0
    if (si->name.s==0) goto error;
134
0
    memcpy(si->name.s, sid->name, si->name.len+1);
135
0
  }
136
137
0
  if (orig_name && orig_name->s && orig_name->len) {
138
0
    si->orig_name.s = pkg_malloc(orig_name->len + 1);
139
0
    if (si->orig_name.s == 0) {
140
0
      LM_ERR("pkg memory allocation failure\n");
141
0
      goto error;
142
0
    }
143
0
    memcpy(si->orig_name.s, orig_name->s, orig_name->len);
144
0
    si->orig_name.s[orig_name->len] = '\0';
145
0
    si->orig_name.len = orig_name->len;
146
0
  }
147
148
  /* set port & proto */
149
0
  si->port_no=sid->port;
150
0
  si->proto=sid->proto;
151
0
  si->flags=sid->flags;
152
153
  /* advertised socket information */
154
  /* Make sure the adv_sock_string is initialized, because if there is
155
   * no adv_sock_name, no other code will initialize it!
156
   */
157
0
  si->adv_sock_str.s=NULL;
158
0
  si->adv_sock_str.len=0;
159
0
  si->adv_port = 0; /* Here to help grep_sock_info along. */
160
0
  if(sid->adv_name) {
161
0
    si->adv_name_str.len=strlen(sid->adv_name);
162
0
    si->adv_name_str.s=(char *)pkg_malloc(si->adv_name_str.len+1);
163
0
    if (si->adv_name_str.s==0) goto error;
164
0
    memcpy(si->adv_name_str.s, sid->adv_name, si->adv_name_str.len+1);
165
0
    if (!sid->adv_port) sid->adv_port=si->port_no ;
166
0
    si->adv_port_str.s=pkg_malloc(10);
167
0
    if (si->adv_port_str.s==0) goto error;
168
0
    si->adv_port_str.len=snprintf(si->adv_port_str.s, 10, "%hu",
169
0
      (unsigned short)sid->adv_port);
170
0
    si->adv_port = sid->adv_port;
171
0
  }
172
173
  /* store the tag info too */
174
0
  if (sid->tag) {
175
0
    si->tag.len = strlen(sid->tag);
176
0
    si->tag.s=(char*)pkg_malloc(si->tag.len+1); /* include \0 */
177
0
    if (si->tag.s==0) goto error;
178
0
    memcpy(si->tag.s, sid->tag, si->tag.len+1);
179
0
  }
180
181
0
  if (si->proto!=PROTO_UDP && si->proto!=PROTO_SCTP &&
182
0
          si->proto!=PROTO_HEP_UDP) {
183
0
    if (sid->workers)
184
0
      LM_WARN("number of workers per non UDP-based <%.*s> listener not "
185
0
        "supported -> ignoring...\n", si->name.len, si->name.s);
186
0
    if (sid->auto_scaling_profile)
187
0
      LM_WARN("auto-scaling for non UDP-based <%.*s> listener not "
188
0
        "supported -> ignoring...\n", si->name.len, si->name.s);
189
0
  } else {
190
0
    if (sid->workers)
191
0
      si->workers = sid->workers;
192
0
    si->tos = sid->tos;
193
0
    if (sid->auto_scaling_profile) {
194
0
      si->s_profile = get_scaling_profile(sid->auto_scaling_profile);
195
0
      if (si->s_profile==NULL) {
196
0
        LM_WARN("scaling profile <%s> in listener <%.*s> not defined "
197
0
          "-> ignoring it...\n", sid->auto_scaling_profile,
198
0
          si->name.len, si->name.s);
199
0
      } else {
200
0
        auto_scaling_enabled = 1;
201
0
      }
202
0
    } else if (udp_auto_scaling_profile) {
203
0
      si->s_profile = get_scaling_profile(udp_auto_scaling_profile);
204
0
      if (si->s_profile==NULL) {
205
0
        LM_WARN("scaling profile <%s> in udp_workers not defined "
206
0
          "-> ignoring it...\n", udp_auto_scaling_profile);
207
0
      } else {
208
0
        auto_scaling_enabled = 1;
209
0
      }
210
0
    }
211
0
  }
212
0
  return sif;
213
0
error:
214
0
  LM_ERR("pkg memory allocation error\n");
215
0
  if (sif) {
216
0
    free_sock_info(sif);
217
0
    pkg_free(sif);
218
0
  }
219
0
  return 0;
220
0
}
221
222
223
224
/*  delete a socket_info struct */
225
void free_sock_info(struct socket_info_full* sif)
226
0
{
227
0
  if(sif){
228
0
    struct socket_info_ref *bond_si, *next_bond_si;
229
0
    struct socket_info *si = &sif->socket_info;
230
0
    if(si->name.s) pkg_free(si->name.s);
231
0
    if(si->orig_name.s) pkg_free(si->orig_name.s);
232
0
    if(si->tag.s) pkg_free(si->tag.s);
233
0
    if(si->sock_str.s) pkg_free(si->sock_str.s);
234
0
    if(si->address_str.s) pkg_free(si->address_str.s);
235
0
    if(si->port_no_str.s) pkg_free(si->port_no_str.s);
236
0
    if(si->adv_name_str.s) pkg_free(si->adv_name_str.s);
237
0
    if(si->adv_port_str.s) pkg_free(si->adv_port_str.s);
238
0
    if(si->adv_sock_str.s) pkg_free(si->adv_sock_str.s);
239
0
    if(si->tag_sock_str.s) pkg_free(si->tag_sock_str.s);
240
0
    for (bond_si = si->bond_sis; bond_si; bond_si = next_bond_si) {
241
0
      next_bond_si = bond_si->next;
242
0
      pkg_free(bond_si);
243
0
    }
244
0
  }
245
0
}
246
247
248
static void free_socket_id_list(struct socket_id *list)
249
0
{
250
0
  struct socket_id *sid, *next_sid;
251
0
  struct socket_bond_elem *be, *next_be;
252
253
0
  for (sid = list; sid; sid = next_sid) {
254
0
    next_sid = sid->next;
255
0
    for (be = sid->bond_list; be; be = next_be) {
256
0
      next_be = be->next;
257
0
      if (be->name)
258
0
        pkg_free(be->name);
259
0
      pkg_free(be);
260
0
    }
261
0
    pkg_free(sid);
262
0
  }
263
0
}
264
265
266
int fix_bond_socket_list(struct socket_id *list)
267
0
{
268
0
  struct socket_id *sid;
269
0
  struct socket_id *next_sid;
270
0
  struct socket_bond_elem *be;
271
0
  struct socket_info_full *sif = NULL;
272
0
  struct socket_info_full *orig_sif;
273
0
  struct socket_info_ref *ref;
274
0
  const struct socket_info *bond_si;
275
0
  str bond_spec, host;
276
0
  int port, proto, found_any;
277
278
0
  for (sid = list; sid; sid = next_sid) {
279
280
0
    next_sid = sid->next;
281
282
0
    if (sid->proto!=PROTO_BOND) {
283
0
      LM_BUG("non-bond socket found in the list\n");
284
0
      goto error;
285
0
    }
286
287
0
    sif = new_sock_info(sid, NULL);
288
0
    if (!sif) {
289
0
      LM_ERR("failed to build socket info for bond <%s>\n", sid->name);
290
0
      goto error;
291
0
    }
292
293
0
    for (be = sid->bond_list; be; be = be->next) {
294
0
      bond_spec.s = be->name;
295
0
      bond_spec.len = strlen(be->name);
296
0
      found_any = 0;
297
0
      if (parse_phostport(bond_spec.s, bond_spec.len, &host.s, &host.len,
298
0
          &port, &proto) != 0) {
299
0
        LM_WARN("failed to parse bond member <%s> for bond <%s>\n",
300
0
          be->name, sid->name);
301
0
        continue;
302
0
      }
303
304
0
      bond_si = grep_internal_sock_info(&host, (unsigned short)port,
305
0
        (unsigned short)proto);
306
0
      if (bond_si) {
307
0
        ref = pkg_malloc(sizeof(*ref));
308
0
        if (!ref) {
309
0
          LM_ERR("pkg memory allocation failed while building "
310
0
            "bond <%s>\n", sid->name);
311
0
          goto error;
312
0
        }
313
0
        ref->si = bond_si;
314
0
        ref->next = sif->socket_info.bond_sis;
315
0
        sif->socket_info.bond_sis = ref;
316
317
0
        LM_DBG("bond socket [%.*s] including real socket [%.*s]\n",
318
0
          sif->socket_info.name.len, sif->socket_info.name.s,
319
0
          bond_si->sock_str.len, bond_si->sock_str.s);
320
0
        continue;
321
0
      }
322
323
0
      orig_sif = NULL;
324
0
      while ((orig_sif = grep_sock_by_orig_name((unsigned short)proto,
325
0
          &host, (unsigned short)port, orig_sif))) {
326
0
        bond_si = &orig_sif->socket_info;
327
328
0
        ref = pkg_malloc(sizeof(*ref));
329
0
        if (!ref) {
330
0
          LM_ERR("pkg memory allocation failed while building "
331
0
            "bond <%s>\n", sid->name);
332
0
          goto error;
333
0
        }
334
0
        ref->si = bond_si;
335
0
        ref->next = sif->socket_info.bond_sis;
336
0
        sif->socket_info.bond_sis = ref;
337
0
        found_any = 1;
338
339
0
        LM_DBG("bond socket [%.*s] including real socket [%.*s] by "
340
0
          "orig_name\n",
341
0
          sif->socket_info.name.len, sif->socket_info.name.s,
342
0
          bond_si->sock_str.len, bond_si->sock_str.s);
343
0
      }
344
345
0
      if (!found_any) {
346
0
        LM_WARN("failed to resolve bond member <%s> for bond <%s>\n",
347
0
          be->name, sid->name);
348
0
      }
349
0
    }
350
351
0
    if (!sif->socket_info.bond_sis) {
352
0
      LM_ERR("bond socket <%s> has no valid members\n", sid->name);
353
0
      goto error;
354
0
    }
355
356
    /* double linked list */
357
0
    sif->next = bond_sockets;
358
0
    if (bond_sockets)
359
0
      bond_sockets->prev = sif;
360
0
    bond_sockets = sif;
361
362
    /* free current element */
363
0
    sid->next = NULL;
364
0
    free_socket_id_list(sid);
365
0
  }
366
367
0
  return 0;
368
0
error:
369
0
  if (sif) {
370
0
    free_sock_info(sif);
371
0
    pkg_free(sif);
372
0
  }
373
0
  free_socket_id_list(sid);
374
0
  return -1;
375
0
}
376
377
378
/* checks if the proto: host:port is one of the address we listen on
379
 * and returns the corresponding socket_info structure.
380
 * if port==0, the  port number is ignored
381
 * if proto==0 (PROTO_NONE) the protocol is ignored
382
 * returns  0 if not found
383
 * WARNING: uses str2ip6 so it will overwrite any previous
384
 *  unsaved result of this function (static buffer)
385
 */
386
const struct socket_info* grep_sock_info_ext(str* host, unsigned short port,
387
                    unsigned short proto, int check_tags)
388
0
{
389
0
  char* hname;
390
0
  int h_len;
391
0
  const struct socket_info* si = NULL;
392
0
  struct socket_info_full* sif;
393
0
  struct socket_info_full ** list;
394
0
  unsigned short c_proto;
395
0
  struct ip_addr* ip6;
396
397
0
  h_len=host->len;
398
0
  hname=host->s;
399
400
0
  if (proto == PROTO_BOND) {
401
0
    if (!check_tags)
402
0
      goto not_found;
403
0
    for (sif = bond_sockets; sif; sif = sif->next) {
404
0
      si = &sif->socket_info;
405
0
      if (h_len == si->name.len &&
406
0
      strncasecmp(hname, si->name.s, si->name.len) == 0)
407
0
        goto found;
408
0
    }
409
0
    goto not_found;
410
0
  }
411
412
0
  if ((h_len>2)&&((*hname)=='[')&&(hname[h_len-1]==']')){
413
    /* ipv6 reference, skip [] */
414
0
    hname++;
415
0
    h_len-=2;
416
0
  }
417
418
0
  c_proto=proto?proto:PROTO_UDP;
419
0
  do{
420
    /* "proto" is all the time valid here */
421
0
    list=get_sock_info_list(c_proto);
422
423
0
    if (list==0){
424
0
      LM_WARN("unknown proto %d\n", c_proto);
425
0
      goto not_found; /* false */
426
0
    }
427
0
    for (sif=*list; sif; sif=sif->next){
428
0
      si = &sif->socket_info;
429
0
      LM_DBG("checking if host==us: %d==%d && "
430
0
          " [%.*s] == [%.*s]\n",
431
0
            h_len,
432
0
            si->name.len,
433
0
            h_len, hname,
434
0
            si->name.len, si->name.s
435
0
        );
436
437
0
      if (check_tags && port==0 && si->tag.s && h_len==si->tag.len &&
438
0
      strncasecmp(hname, si->tag.s, si->tag.len)==0 )
439
0
        goto found;
440
441
0
      if (port) {
442
0
        LM_DBG("checking if port %d matches port %d\n",
443
0
            si->port_no, port);
444
0
        if ((si->port_no != 0 || protos[c_proto].default_port != port) &&
445
0
            (si->port_no == 0 || si->port_no != port) &&
446
0
            si->adv_port!=port) {
447
0
          continue;
448
0
        }
449
0
      }
450
0
      if ( (h_len==si->name.len) &&
451
0
        (strncasecmp(hname, si->name.s,
452
0
             si->name.len)==0) /*slower*/)
453
        /* comp. must be case insensitive, host names
454
         * can be written in mixed case, it will also match
455
         * ipv6 addresses if we are lucky*/
456
0
        goto found;
457
      /* Check if the adv. name of this socket matches */
458
0
      if ( (h_len==si->adv_name_str.len) &&
459
0
        (strncasecmp(hname, si->adv_name_str.s,
460
0
          si->adv_name_str.len)==0) /*slower*/)
461
        /* comp. must be case insensitive, host names
462
        * can be in mixed case, it will also match
463
        * ipv6 addresses if we are lucky*/
464
0
        goto found;
465
      /* if no advertised is specified on the interface, we should check
466
       * if it is the global address */
467
0
      if (!si->adv_name_str.len && default_global_address->s &&
468
0
        h_len == default_global_address->len &&
469
0
        (strncasecmp(hname, default_global_address->s,
470
0
          default_global_address->len)==0) /*slower*/)
471
        /* this might match sockets that are not supposed to
472
         * match, when using multiple listeners for the same
473
         * protocol; but in that case the default_global_address
474
         * concept is broken, since there is no way to choose
475
         * the right socket */
476
0
        goto found;
477
      /* check if host == ip address */
478
      /* ipv6 case is uglier, host can be [3ffe::1] */
479
0
      ip6=str2ip6(host);
480
0
      if (ip6){
481
0
        if (ip_addr_cmp(ip6, &si->address))
482
0
          goto found; /* match */
483
0
        else
484
0
        if (si->adv_name_str.len && ip_addr_cmp(ip6,&si->adv_address))
485
0
          goto found;
486
0
        else
487
0
          continue; /* no match, but this is an ipv6 address
488
                 so no point in trying ipv4 */
489
0
      }
490
      /* ipv4 */
491
0
      if (  (!(si->flags&SI_IS_IP)) &&
492
0
          (h_len==si->address_str.len) &&
493
0
        (memcmp(hname, si->address_str.s,
494
0
                  si->address_str.len)==0)
495
0
        )
496
0
        goto found;
497
0
    }
498
0
  }while( (proto==0) && (c_proto=next_proto(c_proto)) );
499
0
not_found:
500
0
  return 0;
501
0
found:
502
0
  return si;
503
0
}
504
505
506
507
/* checks if the proto: ip:port is one of the address we listen on
508
 * and returns the corresponding socket_info structure.
509
 * (same as grep_socket_info, but use ip addr instead)
510
 * if port==0, the  port number is ignored
511
 * if proto==0 (PROTO_NONE) the protocol is ignored
512
 * returns  0 if not found
513
 * WARNING: uses str2ip6 so it will overwrite any previous
514
 *  unsaved result of this function (static buffer)
515
 */
516
const struct socket_info* find_si(const struct ip_addr* ip, unsigned short port,
517
                        unsigned short proto)
518
0
{
519
0
  const struct socket_info* si = NULL;
520
0
  struct socket_info_full* sif;
521
0
  struct socket_info_full** list;
522
0
  unsigned short c_proto;
523
524
0
  c_proto=proto?proto:PROTO_UDP;
525
0
  do{
526
    /* get the proper sock_list */
527
0
    list=get_sock_info_list(c_proto);
528
529
0
    if (list==0){
530
0
      LM_WARN("unknown proto %d\n", c_proto);
531
0
      goto not_found; /* false */
532
0
    }
533
0
    for (sif=*list; sif; sif=sif->next){
534
0
      si = &sif->socket_info;
535
0
      if (port) {
536
0
        if (si->port_no!=port) {
537
0
          continue;
538
0
        }
539
0
      }
540
0
      if (ip_addr_cmp(ip, &si->address) || ip_addr_cmp(ip, &si->adv_address))
541
0
        goto found;
542
0
    }
543
0
  }while( (proto==0) && (c_proto=next_proto(c_proto)) );
544
0
not_found:
545
0
  return 0;
546
0
found:
547
0
  return si;
548
0
}
549
550
551
/* parses the specified `spec` and returns an associated
552
 * socket_info*, if it could be found */
553
const struct socket_info* parse_sock_info(str *addr)
554
0
{
555
0
  int port, proto;
556
0
  str host;
557
558
0
  if (!addr || !addr->s)
559
0
    return NULL;
560
561
0
  if (parse_phostport(addr->s, addr->len, &host.s, &host.len,
562
0
    &port, &proto) != 0) {
563
0
    return NULL;
564
0
  }
565
566
0
  return grep_internal_sock_info(&host, (unsigned short) port,
567
0
    (unsigned short) proto);
568
0
}
569
570
struct socket_info_full* grep_sock_by_orig_name(unsigned short proto, str *host,
571
    unsigned short port, struct socket_info_full *resume)
572
0
{
573
0
  struct socket_info_full *sif, **list;
574
0
  str *name;
575
576
0
  if (!host || !host->s)
577
0
    return NULL;
578
579
0
  if (proto == PROTO_NONE)
580
0
    proto = PROTO_UDP;
581
0
  if (proto >= PROTO_LAST || protos[proto].id == PROTO_NONE)
582
0
    return NULL;
583
584
0
  if (resume)
585
0
    sif = resume->next;
586
0
  else {
587
0
    list = get_sock_info_list(proto);
588
0
    if (!list || !*list)
589
0
      return NULL;
590
0
    sif = *list;
591
0
  }
592
593
0
  for (; sif; sif = sif->next) {
594
0
    name = &sif->socket_info.orig_name;
595
0
    if (!name->s)
596
0
      continue;
597
0
    if (name->len != host->len ||
598
0
        memcmp(name->s, host->s, name->len) != 0)
599
0
      continue;
600
601
0
    if (port && (sif->socket_info.port_no != 0 ||
602
0
        protos[proto].default_port != port) &&
603
0
        (sif->socket_info.port_no == 0 ||
604
0
        sif->socket_info.port_no != port) &&
605
0
        sif->socket_info.adv_port != port)
606
0
      continue;
607
608
0
    return sif;
609
0
  }
610
611
0
  return NULL;
612
0
}
613
614
615
/* adds a new sock_info structure to the corresponding list
616
 * return  0 on success, -1 on error */
617
int new_sock2list(struct socket_id *sid, str *orig_name,
618
    struct socket_info_full** list)
619
0
{
620
0
  struct socket_info_full* si;
621
622
0
  si = new_sock_info(sid, orig_name);
623
0
  if (si==0){
624
0
    LM_ERR("new_sock_info failed\n");
625
0
    goto error;
626
0
  }
627
628
0
  sock_listadd(list, si);
629
0
  return 0;
630
0
error:
631
0
  return -1;
632
0
}
633
634
void push_sock2list(struct socket_info_full *si)
635
0
{
636
0
  sock_listadd(&protos[si->socket_info.proto].listeners, si);
637
0
}
638
639
void pop_sock2list(struct socket_info_full *si)
640
0
{
641
0
  sock_listrm(&protos[si->socket_info.proto].listeners, si);
642
0
}
643
644
int update_default_socket_info(struct socket_info *si)
645
0
{
646
0
  switch (si->address.af) {
647
0
    case AF_INET:
648
0
      if (protos[si->proto].sendipv4 &&
649
0
          (protos[si->proto].sendipv4->flags&SI_IS_LO) == 0)
650
0
        return 0;
651
0
      protos[si->proto].sendipv4 = si;
652
0
      return 1;
653
0
    case AF_INET6:
654
0
      if (protos[si->proto].sendipv6 &&
655
0
          (protos[si->proto].sendipv6->flags&SI_IS_LO) == 0)
656
0
        return 0;
657
0
      protos[si->proto].sendipv6 = si;
658
0
      return 1;
659
0
    default:
660
      /* do nothing */
661
0
      return 0;
662
0
  }
663
0
}
664
665
void remove_default_socket_info(struct socket_info *si)
666
0
{
667
0
  struct socket_info_full *sif;
668
0
  switch (si->address.af) {
669
0
    case AF_INET:
670
0
      if (si != protos[si->proto].sendipv4)
671
0
        return;
672
0
      protos[si->proto].sendipv4 = NULL;
673
0
      break;
674
0
    case AF_INET6:
675
0
      if (si != protos[si->proto].sendipv6)
676
0
        return;
677
0
      protos[si->proto].sendipv6 = NULL;
678
0
      break;
679
0
    default:
680
      /* do nothing */
681
0
      return;
682
0
  }
683
0
  for (sif = protos[si->proto].listeners; sif; sif = sif->next)
684
0
    if (update_default_socket_info(&sif->socket_info))
685
0
      return;
686
0
}
687
688
/* add all family type addresses of interface if_name to the socket_info array
689
 * WARNING: it only works with ipv6 addresses on FreeBSD
690
 * return: -1 on error, 0 on success
691
 */
692
static int expand_interface(const struct socket_info *si, struct socket_info_full** list)
693
0
{
694
0
  int ret = -1;
695
0
  struct ip_addr addr;
696
0
  struct socket_id sid;
697
0
  str orig_name = si->name;
698
699
0
  sid.port = si->port_no;
700
0
  sid.proto = si->proto;
701
0
  sid.workers = si->workers;
702
0
  sid.tos = si->tos;
703
0
  sid.auto_scaling_profile = si->s_profile?si->s_profile->name:NULL;
704
0
  sid.adv_port = si->adv_port;
705
0
  sid.adv_name = si->adv_name_str.s; /* it is NULL terminated */
706
0
  sid.tag = si->tag.s; /* it is NULL terminated */
707
0
#ifdef HAVE_IFADDRS
708
  /* use the getifaddrs interface to get all the interfaces */
709
0
  struct ifaddrs *addrs;
710
0
  struct ifaddrs *it;
711
712
0
  if (getifaddrs(&addrs) != 0) {
713
0
    LM_ERR("cannot get interfaces list: %s(%d)\n", strerror(errno), errno);
714
0
    return -1;
715
0
  }
716
717
0
  for (it = addrs; it; it = it->ifa_next) {
718
0
    if (!it->ifa_addr)
719
0
      continue;
720
721
0
    if (si->name.len == 0 || (strcmp(si->name.s, it->ifa_name) == 0)) {
722
0
      if (it->ifa_addr->sa_family != AF_INET &&
723
0
          it->ifa_addr->sa_family != AF_INET6)
724
0
        continue;
725
      /*
726
       * if it is ipv6, and there was no explicit interface specified,
727
       * make sure we don't add any "scoped" interface
728
       */
729
0
      if (it->ifa_addr->sa_family == AF_INET6 &&
730
0
          (((struct sockaddr_in6 *)(void *)it->ifa_addr)->sin6_scope_id != 0))
731
732
0
        continue;
733
0
      sockaddr2ip_addr(&addr, it->ifa_addr);
734
0
      if ((sid.name = ip_addr2a(&addr)) == 0)
735
0
        goto end;
736
0
      sid.flags = si->flags;
737
0
      if (it->ifa_flags & IFF_LOOPBACK)
738
0
        sid.flags |= SI_IS_LO;
739
0
      if (new_sock2list(&sid, &orig_name, list) != 0) {
740
0
        LM_ERR("clone_sock2list failed\n");
741
0
        goto end;
742
0
      }
743
0
      ret = 0;
744
0
    }
745
0
  }
746
0
end:
747
0
  freeifaddrs(addrs);
748
0
  return ret;
749
#else
750
  struct ifconf ifc;
751
  struct ifreq ifr;
752
  struct ifreq ifrcopy;
753
  char*  last;
754
  char* p;
755
  int size;
756
  int lastlen;
757
  int s;
758
759
#ifdef HAVE_SOCKADDR_SA_LEN
760
  #ifndef MAX
761
    #define MAX(a,b) ( ((a)>(b))?(a):(b))
762
  #endif
763
#endif
764
  /* ipv4 or ipv6 only*/
765
  s=socket(AF_INET, SOCK_DGRAM, 0);
766
  lastlen=0;
767
  ifc.ifc_req=0;
768
  for (size=100; ; size*=2){
769
    ifc.ifc_len=size*sizeof(struct ifreq);
770
    ifc.ifc_req=(struct ifreq*) pkg_malloc(size*sizeof(struct ifreq));
771
    if (ifc.ifc_req==0){
772
      LM_ERR("memory allocation failure\n");
773
      goto error;
774
    }
775
    if (ioctl(s, SIOCGIFCONF, &ifc)==-1){
776
      if(errno==EBADF) goto error; /* invalid descriptor => no such ifs*/
777
      LM_ERR("ioctl failed: %s\n", strerror(errno));
778
      goto error;
779
    }
780
    if  ((lastlen) && (ifc.ifc_len==lastlen)) break; /*success,
781
                               len not changed*/
782
    lastlen=ifc.ifc_len;
783
    /* try a bigger array*/
784
    pkg_free(ifc.ifc_req);
785
  }
786
787
  last=(char*)ifc.ifc_req+ifc.ifc_len;
788
  for(p=(char*)ifc.ifc_req; p<last;
789
      p+=
790
      #ifdef __OS_linux
791
        sizeof(ifr) /* works on x86_64 too */
792
      #else
793
        (sizeof(ifr.ifr_name)+
794
        #ifdef  HAVE_SOCKADDR_SA_LEN
795
          MAX(ifr.ifr_addr.sa_len, sizeof(struct sockaddr))
796
        #else
797
          ( (ifr.ifr_addr.sa_family==AF_INET)?
798
            sizeof(struct sockaddr_in):
799
            ((ifr.ifr_addr.sa_family==AF_INET6)?
800
            sizeof(struct sockaddr_in6):sizeof(struct sockaddr)) )
801
        #endif
802
        )
803
      #endif
804
    )
805
  {
806
    /* copy contents into ifr structure
807
     * warning: it might be longer (e.g. ipv6 address) */
808
    memcpy(&ifr, p, sizeof(ifr));
809
    if (ifr.ifr_addr.sa_family!=AF_INET){
810
      /*printf("strange family %d skipping...\n",
811
          ifr->ifr_addr.sa_family);*/
812
      continue;
813
    }
814
815
    /*get flags*/
816
    ifrcopy=ifr;
817
    if (ioctl(s, SIOCGIFFLAGS,  &ifrcopy)!=-1){ /* ignore errors */
818
      /* ignore down ifs only if listening on all of them*/
819
      if (si->name.len==0){
820
        /* if if not up, skip it*/
821
        if (!(ifrcopy.ifr_flags & IFF_UP)) continue;
822
      }
823
    }
824
825
    if (si->name.len == 0 ||
826
      strncmp(si->name.s, ifr.ifr_name, sizeof(ifr.ifr_name))==0){
827
828
      /*add address*/
829
      sockaddr2ip_addr(&addr,
830
          (struct sockaddr*)(p+(long)&((struct ifreq*)0)->ifr_addr));
831
      if ((sid.name=ip_addr2a(&addr))==0) goto error;
832
      sid.flags = si->flags;
833
      /* check if loopback */
834
      if (ifrcopy.ifr_flags & IFF_LOOPBACK)
835
        sid.flags|=SI_IS_LO;
836
      /* add it to one of the lists */
837
      if (new_sock2list(&sid, &orig_name, list) != 0) {
838
        LM_ERR("clone_sock2list failed\n");
839
        goto error;
840
      }
841
      ret=0;
842
    }
843
      /*
844
      printf("%s:\n", ifr->ifr_name);
845
      printf("        ");
846
      print_sockaddr(&(ifr->ifr_addr));
847
      printf("        ");
848
      ls_ifflags(ifr->ifr_name, family, options);
849
      printf("\n");*/
850
  }
851
  pkg_free(ifc.ifc_req); /*clean up*/
852
  close(s);
853
  return  ret;
854
error:
855
  if (ifc.ifc_req) pkg_free(ifc.ifc_req);
856
  if (s >= 0)
857
    close(s);
858
  return -1;
859
#endif
860
0
}
861
862
863
0
#define STR_IMATCH(str, buf) ((str).len==strlen(buf) && strncasecmp(buf, (str).s, (str).len)==0)
864
0
#define ACCEPT_SUBDOMAIN_ALIAS(flags) flags & SI_ACCEPT_SUBDOMAIN_ALIAS
865
866
int is_localhost(struct socket_info *si)
867
0
{
868
0
  return (STR_IMATCH(si->name, "localhost") ||
869
0
      STR_IMATCH(si->name, "127.0.0.1") ||
870
0
      STR_IMATCH(si->name, "0:0:0:0:0:0:0:1") || STR_IMATCH(si->name, "::1"));
871
0
}
872
873
int fix_socket(struct socket_info_full *sif, int add_aliases)
874
0
{
875
0
  char** h;
876
0
  char* tmp;
877
0
  int len;
878
0
  struct hostent* he;
879
0
  struct socket_info *si = &sif->socket_info;
880
881
  /* fix the number of processes per interface */
882
0
  if (!si->workers && is_udp_based_proto(si->proto))
883
0
    si->workers = udp_workers_no;
884
0
  if (si->port_no==0)
885
0
    si->port_no= protos[si->proto].default_port;
886
887
0
  tmp=int2str(si->port_no, &len);
888
0
  if (len>=MAX_PORT_LEN){
889
0
    LM_ERR("bad port number: %d\n", si->port_no);
890
0
    return -1;
891
0
  }
892
893
0
  si->port_no_str.s=(char*)pkg_malloc(len+1);
894
0
  if (si->port_no_str.s==0){
895
0
    LM_ERR("out of pkg memory.\n");
896
0
    goto error;
897
0
  }
898
0
  memcpy(si->port_no_str.s, tmp, len+1);
899
0
  si->port_no_str.len=len;
900
  /* get "official hostnames", all the aliases etc. */
901
0
  he=resolvehost(si->name.s,0);
902
0
  if (he==0){
903
0
    LM_ERR("could not resolve %s\n", si->name.s);
904
0
    goto error;
905
0
  }
906
  /* check if we got the official name */
907
0
  if (strcasecmp(he->h_name, si->name.s)!=0){
908
0
    if (add_aliases && add_alias(si->name.s, si->name.len,
909
0
        si->port_no, si->proto, ACCEPT_SUBDOMAIN_ALIAS(si->flags))<0){
910
0
      LM_ERR("add_alias failed\n");
911
0
    }
912
    /* change the official name */
913
0
    pkg_free(si->name.s);
914
0
    si->name.s=(char*)pkg_malloc(strlen(he->h_name)+1);
915
0
    if (si->name.s==0){
916
0
      LM_ERR("out of pkg memory.\n");
917
0
      goto error;
918
0
    }
919
0
    si->name.len=strlen(he->h_name);
920
0
    memcpy(si->name.s, he->h_name, si->name.len+1);
921
0
  }
922
  /* add the aliases*/
923
0
  if (add_aliases) {
924
0
    for(h=he->h_aliases; h && *h; h++)
925
0
      if (add_alias(*h, strlen(*h), si->port_no, si->proto,
926
0
              ACCEPT_SUBDOMAIN_ALIAS(si->flags))<0){
927
0
        LM_ERR("add_alias failed\n");
928
0
      }
929
0
  }
930
0
  hostent2ip_addr(&si->address, he, 0); /*convert to ip_addr
931
                           format*/
932
0
  if ((tmp=ip_addr2a(&si->address))==0) goto error;
933
0
  if (si->address.af == AF_INET6) {
934
0
    si->address_str.s=(char*)pkg_malloc(strlen(tmp)+1+2);
935
0
    if (si->address_str.s==0){
936
0
      LM_ERR("out of pkg memory.\n");
937
0
      goto error;
938
0
    }
939
0
    si->address_str.s[0] = '[';
940
0
    memcpy( si->address_str.s+1 , tmp, strlen(tmp));
941
0
    si->address_str.s[1+strlen(tmp)] = ']';
942
0
    si->address_str.s[2+strlen(tmp)] = '\0';
943
0
    si->address_str.len=strlen(tmp) + 2;
944
0
  } else {
945
0
    si->address_str.s=(char*)pkg_malloc(strlen(tmp)+1);
946
0
    if (si->address_str.s==0){
947
0
      LM_ERR("out of pkg memory.\n");
948
0
      goto error;
949
0
    }
950
0
    memcpy(si->address_str.s, tmp, strlen(tmp)+1);
951
0
    si->address_str.len=strlen(tmp);
952
0
  }
953
  /* set is_ip (1 if name is an ip address, 0 otherwise) */
954
0
  if ( auto_aliases && (si->address_str.len==si->name.len) &&
955
0
      (strncasecmp(si->address_str.s, si->name.s,
956
0
              si->address_str.len)==0)
957
0
    ){
958
0
      si->flags|=SI_IS_IP;
959
      /* do rev. DNS on it (for aliases)*/
960
0
      he=rev_resolvehost(&si->address);
961
0
      if (he==0){
962
0
        LM_WARN("could not rev. resolve %s\n", si->name.s);
963
0
      }else{
964
        /* add the aliases*/
965
0
        if (add_alias(he->h_name, strlen(he->h_name),
966
0
          si->port_no, si->proto, ACCEPT_SUBDOMAIN_ALIAS(si->flags))<0){
967
0
          LM_ERR("add_alias failed\n");
968
0
        }
969
0
        for(h=he->h_aliases; h && *h; h++)
970
0
          if (add_alias(*h,strlen(*h),si->port_no,si->proto,
971
0
            ACCEPT_SUBDOMAIN_ALIAS(si->flags))<0){
972
0
            LM_ERR(" add_alias failed\n");
973
0
          }
974
0
      }
975
0
  }
976
977
  /* Now build an ip_addr structure for the adv_name, if there is one
978
   * so that find_si can find it later easily.  Doing this so that
979
   * we can force_send_socket() on an advertised name.  Generally there
980
   * is little interest in dealing with an advertised name as anything
981
   * other than an opaque string that we blindly put into the SIP
982
   * message.
983
   */
984
0
    if(si->adv_name_str.len) {
985
    /* If adv_name_str is already an IP, this is kinda foolish cus it
986
     * converts it to ip_addr, then to he, then here we go back to
987
     * ip_addr, but it's either that, or we duplicate the logic to
988
     * check for an ip address here, and still we might have to call
989
     * resolvehost().
990
     */
991
0
    he=resolvehost(si->adv_name_str.s,0);
992
0
    if (he==0){
993
0
      LM_ERR("ERROR: fix_socket_list: could not resolve "
994
0
          "advertised name %s\n", si->adv_name_str.s);
995
0
      goto error;
996
0
    }
997
0
    hostent2ip_addr(&si->adv_address, he, 0); /*convert to ip_addr */
998
999
0
    if (si->adv_address.af == AF_INET6 /* translates to IPv6 */
1000
0
    && str2ip6(&si->adv_name_str)!=NULL /* it's an actual IP */
1001
0
    && si->adv_name_str.s[0]!='['  )    /* not enclosed */
1002
0
    {
1003
0
      tmp = pkg_malloc( si->adv_name_str.len +2 );
1004
0
      if (tmp==NULL) {
1005
0
        LM_ERR("failed to convert advertized IPv6 "
1006
0
          "to enclosed format\n");
1007
0
        goto error;
1008
0
      }
1009
0
      tmp[0] = '[';
1010
0
      memcpy( tmp+1, si->adv_name_str.s, si->adv_name_str.len);
1011
0
      tmp[si->adv_name_str.len+1] = ']';
1012
0
      pkg_free(si->adv_name_str.s);
1013
0
      si->adv_name_str.s = tmp;
1014
0
      si->adv_name_str.len += 2;
1015
0
    }
1016
1017
    /* build and set string encoding for the adv socket info
1018
     * This is usefful for the usrloc module when it's generating
1019
     * or updating the socket on a location record, so we'll generate
1020
     * it up front just like the regular sock_str so we don't have
1021
     * to worry about it later.
1022
     */
1023
0
    tmp = socket2str( si, 0, &si->adv_sock_str.len, 1);
1024
0
    if (tmp==0) {
1025
0
      LM_ERR("ERROR: fix_socket_list: failed to convert "
1026
0
            "socket to string (adv)\n");
1027
0
      goto error;
1028
0
    }
1029
0
    si->adv_sock_str.s=(char*)pkg_malloc(si->adv_sock_str.len);
1030
0
    if (si->adv_sock_str.s==0) {
1031
0
      LM_ERR("ERROR: fix_socket_list: out of memory.\n");
1032
0
      goto error;
1033
0
    }
1034
0
    memcpy(si->adv_sock_str.s, tmp, si->adv_sock_str.len);
1035
0
  }
1036
1037
0
  if (si->tag.len) {
1038
    /* build and set string encoding for the tagged socket info */
1039
0
    tmp = socket2str( si, 0, &si->tag_sock_str.len, 2);
1040
0
    if (tmp==0) {
1041
0
      LM_ERR("failed to convert tag socket to string\n");
1042
0
      goto error;
1043
0
    }
1044
0
    si->tag_sock_str.s=(char*)pkg_malloc(si->tag_sock_str.len);
1045
0
    if (si->tag_sock_str.s==0) {
1046
0
      LM_ERR("out of pkg memory.\n");
1047
0
      goto error;
1048
0
    }
1049
0
    memcpy(si->tag_sock_str.s, tmp, si->tag_sock_str.len);
1050
0
  }
1051
1052
  /* build and set string encoding for the real socket info */
1053
0
  tmp = socket2str( si, 0, &si->sock_str.len, 0);
1054
0
  if (tmp==0) {
1055
0
    LM_ERR("failed to convert socket to string\n");
1056
0
    goto error;
1057
0
  }
1058
0
  si->sock_str.s=(char*)pkg_malloc(si->sock_str.len);
1059
0
  if (si->sock_str.s==0) {
1060
0
    LM_ERR("out of pkg memory.\n");
1061
0
    goto error;
1062
0
  }
1063
0
  memcpy(si->sock_str.s, tmp, si->sock_str.len);
1064
1065
#ifdef USE_MCAST
1066
  /* Check if it is an multicast address and
1067
   * set the flag if so
1068
   */
1069
  if (is_mcast(&si->address)) {
1070
    si->flags |= SI_IS_MCAST;
1071
  }
1072
#endif /* USE_MCAST */
1073
1074
#ifdef EXTRA_DEBUG
1075
  printf("              %.*s [%s]:%s%s%s\n", si->name.len,
1076
    si->name.s, si->address_str.s, si->port_no_str.s,
1077
                  si->flags & SI_IS_MCAST ? " mcast" : "",
1078
                  is_anycast(si) ? " anycast" : "");
1079
#endif
1080
0
  return 0;
1081
0
error:
1082
0
  return -1;
1083
0
}
1084
1085
/* fixes a socket list => resolve addresses,
1086
 * interface names, fills missing members, remove duplicates */
1087
int fix_socket_list(struct socket_info_full **list)
1088
0
{
1089
0
  struct socket_info_full* sif;
1090
0
  struct socket_info* si;
1091
0
  struct socket_info_full* l;
1092
0
  struct socket_info_full* next;
1093
1094
  /* try to change all the interface names into addresses
1095
   *  --ugly hack */
1096
1097
0
  for (sif=*list;sif;){
1098
0
    next=sif->next;
1099
0
    si = &sif->socket_info;
1100
    // fix the SI_IS_LO flag for sockets specified by IP/hostname as expand_interface
1101
    // below will only do it for sockets specified using the network interface name
1102
0
    if (is_localhost(si))
1103
0
      si->flags |= SI_IS_LO;
1104
0
    if (expand_interface(si, list)!=-1){
1105
      /* success => remove current entry (shift the entire array)*/
1106
0
      sock_listrm(list, sif);
1107
0
      free_sock_info(sif);
1108
0
    }
1109
0
    sif=next;
1110
0
  }
1111
  /* get ips & fill the port numbers*/
1112
#ifdef EXTRA_DEBUG
1113
  LM_DBG("listening on \n");
1114
#endif
1115
0
  for (sif=*list;sif;sif=sif->next){
1116
0
    si = &sif->socket_info;
1117
0
    if (fix_socket(sif, auto_aliases) < 0) {
1118
0
      sock_listrm(list, sif);
1119
0
      free_sock_info(sif);
1120
0
    }
1121
0
  }
1122
  /* removing duplicate addresses*/
1123
0
  for (sif=*list;sif; sif=sif->next){
1124
0
    for (l=sif->next;l;){
1125
0
      next=l->next;
1126
0
      si = &sif->socket_info;
1127
0
      const struct socket_info *sl = &l->socket_info;
1128
0
      if ((si->port_no==sl->port_no) &&
1129
0
        (si->address.af==sl->address.af) &&
1130
0
        (memcmp(si->address.u.addr, sl->address.u.addr, si->address.len)
1131
0
          == 0)
1132
0
        ){
1133
#ifdef EXTRA_DEBUG
1134
        printf("removing duplicate %s [%s] ==  %s [%s]\n",
1135
            si->name.s, si->address_str.s,
1136
             sl->name.s, sl->address_str.s);
1137
#endif
1138
        /* add the name to the alias list*/
1139
0
        if ((!(sl->flags& SI_IS_IP)) && (
1140
0
            (sl->name.len!=si->name.len)||
1141
0
            (strncmp(sl->name.s, si->name.s, si->name.len)!=0))
1142
0
          )
1143
0
          if (add_alias(sl->name.s,sl->name.len,sl->port_no,sl->proto,
1144
0
              ACCEPT_SUBDOMAIN_ALIAS(sl->flags))<0)
1145
0
            LM_ERR(" add_alias failed\n");
1146
1147
        /* remove l*/
1148
0
        sock_listrm(list, l);
1149
0
        free_sock_info(l);
1150
0
      }
1151
0
      l=next;
1152
0
    }
1153
0
  }
1154
1155
#ifdef USE_MCAST
1156
       /* Remove invalid multicast entries */
1157
  sif=*list;
1158
  while(sif){
1159
    si = &sif->socket_info;
1160
    if ((si->flags & SI_IS_MCAST) &&
1161
        (si->proto != PROTO_UDP)
1162
       ){
1163
      LM_WARN("removing entry %s:%s [%s]:%s\n",
1164
          get_proto_name(si->proto), si->name.s,
1165
          si->address_str.s, si->port_no_str.s);
1166
      l = sif;
1167
      sif=sif->next;
1168
      sock_listrm(list, l);
1169
      free_sock_info(l);
1170
    } else {
1171
      sif=sif->next;
1172
    }
1173
  }
1174
#endif /* USE_MCAST */
1175
1176
0
  return 0;
1177
0
}
1178
1179
1180
1181
1182
1183
/*
1184
 * This function will retrieve a list of all ip addresses and ports that
1185
 * OpenSIPS is listening on, with respect to the transport protocol specified
1186
 * with 'protocol'.
1187
 *
1188
 * The first parameter, ipList, is a pointer to a pointer. It will be assigned
1189
 * a new block of memory holding the IP Addresses and ports being listened to 
1190
 * with respect to 'protocol'.  The array maps a 2D array into a 1 dimensional 
1191
 * space, and is layed out as follows:
1192
 *
1193
 * The first NUM_IP_OCTETS indices will be the IP address, and the next index
1194
 * the port.  So if NUM_IP_OCTETS is equal to 4 and there are two IP addresses
1195
 * found, then:
1196
 *
1197
 *  - ipList[0] will be the first octet of the first ip address
1198
 *  - ipList[3] will be the last octet of the first ip address.
1199
 *  - iplist[4] will be the port of the first ip address
1200
 *  -
1201
 *  - iplist[5] will be the first octet of the first ip address,
1202
 *  - and so on.
1203
 *
1204
 * The function will return the number of sockets which were found.  This can
1205
 * be used to index into ipList.
1206
 *
1207
 * NOTE: This function assigns a block of memory equal to:
1208
 *
1209
 *            returnedValue * (NUM_IP_OCTETS + 1) * sizeof(int);
1210
 *
1211
 *       Therefore it is CRUCIAL that you free ipList when you are done with
1212
 *       its contents, to avoid a nasty memory leak.
1213
 */
1214
0
int get_socket_list_from_proto(unsigned int **ipList, int protocol) {
1215
1216
0
  struct socket_info_full  *sif;
1217
0
  struct socket_info_full ** list;
1218
1219
0
  int num_ip_octets   = 4;
1220
0
  int numberOfSockets = 0;
1221
0
  int currentRow      = 0;
1222
1223
  /* I hate to use #ifdefs, but this is necessary because of the way
1224
   * get_sock_info_list() is defined.  */
1225
0
  if (protocol == PROTO_TCP)
1226
0
  {
1227
0
    return 0;
1228
0
  }
1229
1230
0
  if (protocol == PROTO_TLS)
1231
0
  {
1232
0
    return 0;
1233
0
  }
1234
1235
  /* Retrieve the list of sockets with respect to the given protocol. */
1236
0
  list=get_sock_info_list(protocol);
1237
1238
  /* Find out how many sockets are in the list.  We need to know this so
1239
   * we can malloc an array to assign to ipList. */
1240
0
  for(sif=list?*list:0; sif; sif=sif->next){
1241
    /* We only support IPV4 at this point. */
1242
0
    if (sif->socket_info.address.af == AF_INET) {
1243
0
      numberOfSockets++;
1244
0
    }
1245
0
  }
1246
1247
  /* There are no open sockets with respect to the given protocol. */
1248
0
  if (numberOfSockets == 0)
1249
0
  {
1250
0
    return 0;
1251
0
  }
1252
1253
0
  *ipList = pkg_malloc(numberOfSockets *
1254
0
      (num_ip_octets + 1) * (int)sizeof(int));
1255
1256
  /* We couldn't allocate memory for the IP List.  So all we can do is
1257
   * fail. */
1258
0
  if (*ipList == NULL) {
1259
0
    LM_ERR("no more pkg memory");
1260
0
    return 0;
1261
0
  }
1262
1263
1264
  /* We need to search the list again.  So find the front of the list. */
1265
0
  list=get_sock_info_list(protocol);
1266
1267
  /* Extract out the IP Addresses and ports.  */
1268
0
  for(sif=list?*list:0; sif; sif=sif->next){
1269
0
    const struct socket_info *si = &sif->socket_info;
1270
1271
    /* We currently only support IPV4. */
1272
0
    if (si->address.af != AF_INET) {
1273
0
      continue;
1274
0
    }
1275
1276
0
    (*ipList)[currentRow*(num_ip_octets + 1)  ] =
1277
0
      si->address.u.addr[0];
1278
0
    (*ipList)[currentRow*(num_ip_octets + 1)+1] =
1279
0
      si->address.u.addr[1];
1280
0
    (*ipList)[currentRow*(num_ip_octets + 1)+2] =
1281
0
      si->address.u.addr[2];
1282
0
    (*ipList)[currentRow*(num_ip_octets + 1)+3] =
1283
0
      si->address.u.addr[3];
1284
0
    (*ipList)[currentRow*(num_ip_octets + 1)+4] =
1285
0
      si->port_no;
1286
1287
0
    currentRow++;
1288
0
  }
1289
1290
0
  return numberOfSockets;
1291
0
}
1292
1293
/*
1294
 * Takes a 'line' (from the proc file system), parses out the ipAddress,
1295
 * address, and stores the number of bytes waiting in 'rx_queue'
1296
 *
1297
 * Returns 1 on success, and 0 on a failed parse.
1298
 *
1299
 * Note: The format of ipAddress is as defined in the comments of
1300
 * get_socket_list_from_proto() in this file.
1301
 *
1302
 */
1303
static int parse_proc_net_line(char *line, unsigned int *ipAddress, int *rx_queue)
1304
0
{
1305
0
  int i;
1306
1307
0
  unsigned int ipOctetExtractionMask = 0xFF;
1308
1309
0
  char *currColonLocation;
1310
0
  char *nextNonNumericalChar;
1311
0
  char *currentLocationInLine = line;
1312
1313
0
  unsigned int parsedInteger[4];
1314
1315
  /* Example line from /proc/net/tcp or /proc/net/udp:
1316
   *
1317
   *  sl  local_address rem_address   st tx_queue rx_queue
1318
   *  21: 5A0A0B0A:CAC7 1C016E0A:0016 01 00000000:00000000
1319
   *
1320
   * Algorithm:
1321
   *
1322
   *  1) Find the location of the first  ':'
1323
   *  2) Parse out the IP Address into an integer
1324
   *  3) Find the location of the second ':'
1325
   *  4) Parse out the port number.
1326
   *  5) Find the location of the fourth ':'
1327
   *  6) Parse out the rx_queue.
1328
   */
1329
1330
0
  for (i = 0; i < 4; i++) {
1331
1332
0
    currColonLocation = strchr(currentLocationInLine, ':');
1333
1334
    /* We didn't find all the needed ':', so fail. */
1335
0
    if (currColonLocation == NULL) {
1336
0
      return 0;
1337
0
    }
1338
1339
    /* Parse out the integer, keeping the location of the next
1340
     * non-numerical character.  */
1341
0
    parsedInteger[i] =
1342
0
      (int) strtol(++currColonLocation, &nextNonNumericalChar,
1343
0
          16);
1344
1345
    /* strtol()'s specifications specify that the second parameter
1346
     * is set to the first parameter when a number couldn't be
1347
     * parsed out.  This means the parse was unsuccesful.  */
1348
0
    if (nextNonNumericalChar == currColonLocation) {
1349
0
      return 0;
1350
0
    }
1351
1352
    /* Reset the currentLocationInLine to the last non-numerical
1353
     * character, so that next iteration of this loop, we can find
1354
     * the next colon location. */
1355
0
    currentLocationInLine = nextNonNumericalChar;
1356
1357
0
  }
1358
1359
  /* Extract out the segments of the IP Address.  They are stored in
1360
   * reverse network byte order. */
1361
0
  for (i = 0; i < NUM_IP_OCTETS; i++) {
1362
1363
0
    ipAddress[i] =
1364
0
      parsedInteger[0] & (ipOctetExtractionMask << i*8);
1365
1366
0
    ipAddress[i] >>= i*8;
1367
1368
0
  }
1369
1370
0
  ipAddress[NUM_IP_OCTETS] = parsedInteger[1];
1371
1372
0
  *rx_queue = parsedInteger[3];
1373
1374
0
  return 1;
1375
1376
0
}
1377
1378
1379
/*
1380
 * Returns 1 if ipOne was found in ipArray, and 0 otherwise.
1381
 *
1382
 * The format of ipOne and ipArray are described in the comments of
1383
 * get_socket_list_from_proto() in this file.
1384
 *
1385
 * */
1386
static int match_ip_and_port(unsigned int *ipOne, unsigned int *ipArray, int sizeOf_ipArray)
1387
0
{
1388
0
  int curIPAddrIdx;
1389
0
  int curOctetIdx;
1390
0
  int ipArrayIndex;
1391
1392
  /* Loop over every IP Address */
1393
0
  for (curIPAddrIdx = 0; curIPAddrIdx < sizeOf_ipArray; curIPAddrIdx++) {
1394
1395
    /* Check for octets that don't match.  If one is found, skip the
1396
     * rest.  */
1397
0
    for (curOctetIdx = 0; curOctetIdx < NUM_IP_OCTETS + 1; curOctetIdx++) {
1398
1399
      /* We've encoded a 2D array as a 1D array.  So find out
1400
       * our position in the 1D array. */
1401
0
      ipArrayIndex =
1402
0
        curIPAddrIdx * (NUM_IP_OCTETS + 1) + curOctetIdx;
1403
1404
0
      if (ipOne[curOctetIdx] != ipArray[ipArrayIndex]) {
1405
0
        break;
1406
0
      }
1407
0
    }
1408
1409
    /* If the index from the inner loop is equal to NUM_IP_OCTETS
1410
     * + 1, then that means that every octet (and the port with the
1411
     * + 1) matched. */
1412
0
    if (curOctetIdx == NUM_IP_OCTETS + 1) {
1413
0
      return 1;
1414
0
    }
1415
1416
0
  }
1417
1418
0
  return 0;
1419
0
}
1420
1421
1422
/*
1423
 * Returns the number of bytes waiting to be consumed on the network interfaces
1424
 * assigned the IP Addresses specified in interfaceList.  The check will be
1425
 * limited to the TCP or UDP transport exclusively.  Specifically:
1426
 *
1427
 * - If forTCP is non-zero, the check involves only the TCP transport.
1428
 * - if forTCP is zero, the check involves only the UDP transport.
1429
 *
1430
 * Note: This only works on linux systems supporting the /proc/net/[tcp|udp]
1431
 *       interface.  On other systems, zero will always be returned.
1432
 */
1433
static int get_used_waiting_queue(
1434
    int forTCP, unsigned int *interfaceList, int listSize)
1435
0
{
1436
0
  FILE *fp;
1437
0
  char *fileToOpen;
1438
1439
0
  char lineBuffer[MAX_PROC_BUFFER];
1440
0
  unsigned int  ipAddress[NUM_IP_OCTETS+1];
1441
0
  int  rx_queue;
1442
0
  int  waitingQueueSize = 0;
1443
1444
0
  if (listSize==0 || interfaceList==NULL)
1445
0
    return 0;
1446
1447
  /* Set up the file we want to open. */
1448
0
  if (forTCP) {
1449
0
    fileToOpen = "/proc/net/tcp";
1450
0
  } else {
1451
0
    fileToOpen = "/proc/net/udp";
1452
0
  }
1453
1454
0
  fp = fopen(fileToOpen, "r");
1455
1456
0
  if (fp == NULL) {
1457
0
    LM_DBG("Could not open %s. openserMsgQueu eDepth and its related"
1458
0
        " alarms will not be available.\n", fileToOpen);
1459
0
    return 0;
1460
0
  }
1461
1462
  /* Read in every line of the file, parse out the ip address, port, and
1463
   * rx_queue, and compare to our list of interfaces we are listening on.
1464
   * Add up rx_queue for those lines which match our known interfaces. */
1465
0
  while (fgets(lineBuffer, MAX_PROC_BUFFER, fp)!=NULL) {
1466
1467
    /* Parse out the ip address, port, and rx_queue. */
1468
0
    if(parse_proc_net_line(lineBuffer, ipAddress, &rx_queue)) {
1469
1470
      /* Only add rx_queue if the line just parsed corresponds
1471
       * to an interface we are listening on.  We do this
1472
       * check because it is possible that this system has
1473
       * other network interfaces that OpenSER has been told
1474
       * to ignore. */
1475
0
      if (match_ip_and_port(ipAddress, interfaceList, listSize)) {
1476
0
        waitingQueueSize += rx_queue;
1477
0
      }
1478
0
    }
1479
0
  }
1480
1481
0
  fclose(fp);
1482
1483
0
  return waitingQueueSize;
1484
0
}
1485
1486
/*
1487
 * Returns the sum of the number of bytes waiting to be consumed on all network
1488
 * interfaces and transports that OpenSIPS is listening on.
1489
 *
1490
 * Note: This currently only works on systems supporting the /proc/net/[tcp|udp]
1491
 *       interface.  On other systems, zero will always be returned.  To change
1492
 *       this in the future, add an equivalent for get_used_waiting_queue().
1493
 */
1494
int get_total_bytes_waiting(int only_proto)
1495
0
{
1496
0
  static unsigned int *UDPList  = NULL;
1497
0
  static unsigned int *TCPList  = NULL;
1498
0
  static unsigned int *TLSList  = NULL;
1499
1500
0
  static int numUDPSockets  = -1;
1501
0
  static int numTCPSockets  = -1;
1502
0
  static int numTLSSockets  = -1;
1503
1504
0
  int bytesWaiting = 0;
1505
1506
  /* Extract out the IP address address for UDP, TCP, and TLS, keeping
1507
   * track of the number of IP addresses from each transport  */
1508
0
  if (numUDPSockets==-1)
1509
0
    numUDPSockets  = get_socket_list_from_proto(&UDPList,  PROTO_UDP);
1510
0
  if (numTCPSockets==-1)
1511
0
    numTCPSockets  = get_socket_list_from_proto(&TCPList,  PROTO_TCP);
1512
0
  if (numTLSSockets==-1)
1513
0
    numTLSSockets  = get_socket_list_from_proto(&TLSList,  PROTO_TLS);
1514
1515
  /* Find out the number of bytes waiting on our interface list over all
1516
   * UDP and TCP transports. */
1517
0
  if (only_proto==PROTO_NONE) {
1518
0
    bytesWaiting  += get_used_waiting_queue(0, UDPList,  numUDPSockets);
1519
0
    bytesWaiting  += get_used_waiting_queue(1, TCPList,  numTCPSockets);
1520
0
    bytesWaiting  += get_used_waiting_queue(1, TLSList,  numTLSSockets);
1521
0
  } else if (only_proto==PROTO_UDP) {
1522
0
    bytesWaiting  += get_used_waiting_queue(0, UDPList,  numUDPSockets);
1523
0
  } else if (only_proto==PROTO_TCP) {
1524
0
    bytesWaiting  += get_used_waiting_queue(1, TCPList,  numTCPSockets);
1525
0
  } else if (only_proto==PROTO_TLS) {
1526
0
    bytesWaiting  += get_used_waiting_queue(1, TLSList,  numTLSSockets);
1527
0
  }
1528
1529
0
  return bytesWaiting;
1530
0
}
1531
1532
1533
1534
void print_aliases(void)
1535
0
{
1536
0
  struct host_alias* a;
1537
1538
0
  for(a=aliases; a; a=a->next)
1539
0
    if (a->port)
1540
0
      printf("             %s: %.*s:%d\n", get_proto_name(a->proto),
1541
0
          a->alias.len, a->alias.s, a->port);
1542
0
    else
1543
0
      printf("             %s: %.*s:*\n", get_proto_name(a->proto),
1544
0
          a->alias.len, a->alias.s);
1545
0
}
1546
1547
/*
1548
 * Arguments :
1549
 *    sock - socket to have buffer increased
1550
 *    buff_choice - 0 for receive buff, 1 for send buff
1551
 *    buff_max - max size of socket buffer we are looking for
1552
 *    buff_increment - increment nr of bytes after reaching limit
1553
 *
1554
 *  Returns :
1555
 *    0 in case of success
1556
 *    1 in case of failure
1557
*/
1558
int probe_max_sock_buff(int sock,int buff_choice,int buff_max,int buff_increment)
1559
0
{
1560
0
  unsigned int optval, ioptval, ioptvallen, foptval, foptvallen, voptval, voptvallen;
1561
0
  int phase=0;
1562
0
  int buff_opt;
1563
0
  char *info;
1564
1565
0
  if (buff_choice == 0)
1566
0
  {
1567
0
    info = "rcv";
1568
0
    buff_opt = SO_RCVBUF;
1569
0
  }
1570
0
  else if (buff_choice == 1)
1571
0
  {
1572
0
    info = "snd";
1573
0
    buff_opt = SO_SNDBUF;
1574
0
  }
1575
0
  else
1576
0
  {
1577
0
    LM_WARN("Called with unimplemented buff_choice - %d\n",buff_choice);
1578
0
    return 1;
1579
0
  }
1580
1581
  /* try to increase buffer size as much as we can */
1582
0
  ioptvallen=sizeof(ioptval);
1583
0
  if (getsockopt( sock, SOL_SOCKET, buff_opt, (void*) &ioptval,
1584
0
        &ioptvallen) == -1 )
1585
0
  {
1586
0
    LM_ERR("getsockopt: %s\n", strerror(errno));
1587
0
    return -1;
1588
0
  }
1589
0
  if ( ioptval==0 )
1590
0
  {
1591
0
    LM_DBG(" getsockopt: %s initially set to 0; resetting to %d\n",
1592
0
      info,buff_increment );
1593
0
    ioptval=buff_increment;
1594
0
  } else LM_DBG("getsockopt: %s is initially %d\n",info, ioptval );
1595
0
  for (optval=ioptval; ;  ) {
1596
    /* increase size; double in initial phase, add linearly later */
1597
0
    if (phase==0) optval <<= 1; else optval+=buff_increment;
1598
0
    if (optval > maxbuffer){
1599
0
      if (phase==1) break;
1600
0
      else { phase=1; optval >>=1; continue; }
1601
0
    }
1602
    /* LM_DBG("trying : %d\n", optval ); */
1603
0
    if (setsockopt( sock, SOL_SOCKET, buff_opt,
1604
0
      (void*)&optval, sizeof(optval)) ==-1){
1605
      /* Solaris returns -1 if asked size too big; Linux ignores */
1606
0
      LM_DBG("setsockopt: SOL_SOCKET failed"
1607
0
          " for %d, phase %d: %s\n", optval, phase, strerror(errno));
1608
      /* if setting buffer size failed and still in the aggressive
1609
         phase, try less aggressively; otherwise give up */
1610
0
      if (phase==0) { phase=1; optval >>=1 ; continue; }
1611
0
      else break;
1612
0
    }
1613
    /* verify if change has taken effect */
1614
    /* Linux note -- otherwise I would never know that; funny thing: Linux
1615
       doubles size for which we asked in setsockopt */
1616
0
    voptvallen=sizeof(voptval);
1617
0
    if (getsockopt( sock, SOL_SOCKET, buff_opt, (void*) &voptval,
1618
0
        &voptvallen) == -1 )
1619
0
    {
1620
0
      LM_ERR("getsockopt: %s\n", strerror(errno));
1621
0
      return -1;
1622
0
    } else {
1623
      /*LM_DBG("setting %s: set=%d,verify=%d\n",info,
1624
        optval, voptval);*/
1625
0
      if (voptval<optval) {
1626
0
        LM_DBG("setting %s buf to %d had no effect\n",info,optval);
1627
        /* if setting buffer size failed and still in the aggressive
1628
        phase, try less aggressively; otherwise give up */
1629
0
        if (phase==0) { phase=1; optval >>=1 ; continue; }
1630
0
        else break;
1631
0
      }
1632
0
    }
1633
1634
0
  } /* for ... */
1635
0
  foptvallen=sizeof(foptval);
1636
0
  if (getsockopt( sock, SOL_SOCKET, buff_opt, (void*) &foptval,
1637
0
        &foptvallen) == -1 )
1638
0
  {
1639
0
    LM_ERR("getsockopt: %s\n", strerror(errno));
1640
0
    return -1;
1641
0
  }
1642
0
  LM_DBG("using %s buffer of %d kb\n",info, (foptval/1024));
1643
1644
0
  return 0;
1645
0
}
1646
1647
struct socket_id *socket_info2id(struct socket_info *si)
1648
0
{
1649
0
  static struct socket_id sid;
1650
1651
0
  memset(&sid, 0, sizeof sid);
1652
0
  sid.name = si->name.s;
1653
0
  sid.adv_name = si->adv_sock_str.s;
1654
0
  sid.tag = si->tag.s;
1655
0
  if (si->s_profile)
1656
0
    sid.auto_scaling_profile = si->s_profile->name;
1657
0
  sid.adv_port = si->adv_port;
1658
0
  sid.proto = si->proto;
1659
0
  sid.port = si->port_no;
1660
0
  sid.workers = si->workers;
1661
0
  return &sid;
1662
0
}