Coverage Report

Created: 2023-03-26 07:11

/src/ntp-dev/libntp/decodenetnum.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * decodenetnum - return a net number (this is crude, but careful)
3
 */
4
#include <config.h>
5
#include <sys/types.h>
6
#include <ctype.h>
7
#ifdef HAVE_SYS_SOCKET_H
8
#include <sys/socket.h>
9
#endif
10
#ifdef HAVE_NETINET_IN_H
11
#include <netinet/in.h>
12
#endif
13
14
#include "ntp.h"
15
#include "ntp_stdlib.h"
16
#include "ntp_assert.h"
17
18
/*
19
 * decodenetnum   convert text IP address and port to sockaddr_u
20
 *
21
 * Returns 0 for failure, 1 for success.
22
 */
23
int
24
decodenetnum(
25
  const char *num,
26
  sockaddr_u *netnum
27
  )
28
815
{
29
815
  struct addrinfo hints, *ai = NULL;
30
815
  int err;
31
815
  u_short port;
32
815
  const char *cp;
33
815
  const char *port_str;
34
815
  char *pp;
35
815
  char *np;
36
815
  char name[80];
37
38
815
  REQUIRE(num != NULL);
39
40
815
  if (strlen(num) >= sizeof(name)) {
41
1
    return 0;
42
1
  }
43
44
814
  port_str = NULL;
45
814
  if ('[' != num[0]) {
46
    /*
47
     * to distinguish IPv6 embedded colons from a port
48
     * specification on an IPv4 address, assume all 
49
     * legal IPv6 addresses have at least two colons.
50
     */
51
728
    pp = strchr(num, ':');
52
728
    if (NULL == pp)
53
261
      cp = num;  /* no colons */
54
467
    else if (NULL != strchr(pp + 1, ':'))
55
404
      cp = num;  /* two or more colons */
56
63
    else {     /* one colon */
57
63
      strlcpy(name, num, sizeof(name));
58
63
      cp = name;
59
63
      pp = strchr(cp, ':');
60
63
      *pp = '\0';
61
63
      port_str = pp + 1;
62
63
    }
63
728
  } else {
64
86
    cp = num + 1;
65
86
    np = name; 
66
407
    while (*cp && ']' != *cp)
67
321
      *np++ = *cp++;
68
86
    *np = 0;
69
86
    if (']' == cp[0] && ':' == cp[1] && '\0' != cp[2])
70
16
      port_str = &cp[2];
71
86
    cp = name; 
72
86
  }
73
814
  ZERO(hints);
74
814
  hints.ai_flags = Z_AI_NUMERICHOST;
75
814
  err = getaddrinfo(cp, "ntp", &hints, &ai);
76
814
  if (err != 0)
77
814
    return 0;
78
0
  INSIST(ai->ai_addrlen <= sizeof(*netnum));
79
0
  ZERO(*netnum);
80
0
  memcpy(netnum, ai->ai_addr, ai->ai_addrlen);
81
0
  freeaddrinfo(ai);
82
0
  if (NULL == port_str || 1 != sscanf(port_str, "%hu", &port))
83
0
    port = NTP_PORT;
84
0
  SET_PORT(netnum, port);
85
0
  return 1;
86
814
}