summaryrefslogtreecommitdiff
path: root/agent/util.c
blob: 6cf6bd334e337cc5048f7f7549a8e08c78300d4b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114

#include <string.h>
#include <stdlib.h>

#include <arpa/inet.h>

#include <glib.h>

#include <udp.h>

#include <agent.h>

/* format is:
 *   type/ip/port
 */
NiceCandidate *
nice_candidate_from_string (const gchar *s)
{
  NiceCandidateType type;
  NiceCandidate *candidate;
  NiceAddress *addr;
  gchar *first_slash;
  gchar *last_slash;
  gchar tmp[128];
  guint len;
  guint32 ip;
  guint16 port;

  if (s == NULL || s[0] == '\0')
    return NULL;

  switch (s[0])
    {
    case 'H':
      type = NICE_CANDIDATE_TYPE_HOST;
      break;
    case 'S':
      type = NICE_CANDIDATE_TYPE_SERVER_REFLEXIVE;
      break;
    case 'P':
      type = NICE_CANDIDATE_TYPE_PEER_REFLEXIVE;
      break;
    case 'R':
      type = NICE_CANDIDATE_TYPE_RELAYED;
      break;
    default:
      return NULL;
    }

  /* extract IP address */

  first_slash = index (s, '/');
  last_slash = rindex (s, '/');

  if (first_slash == NULL ||
      last_slash == NULL ||
      first_slash == last_slash)
    return NULL;

  len = last_slash - first_slash - 1;

  if (len > sizeof (tmp) - 1)
    return NULL;

  strncpy (tmp, first_slash + 1, len);
  tmp[len] = '\0';

  if (inet_pton (AF_INET, tmp, &ip) < 1)
    return NULL;

  /* extract port */

  port = strtol (last_slash + 1, NULL, 10);

  candidate = nice_candidate_new (type);
  addr = nice_address_new ();
  nice_address_set_ipv4 (addr, ntohl (ip));
  candidate->addr = *addr;
  candidate->port = port;

  return candidate;
}

gchar *
nice_candidate_to_string (NiceCandidate *candidate)
{
  gchar *addr_tmp;
  gchar *ret;
  gchar type;

  switch (candidate->type)
    {
    case NICE_CANDIDATE_TYPE_HOST:
      type = 'H';
      break;
    case NICE_CANDIDATE_TYPE_SERVER_REFLEXIVE:
      type = 'S';
      break;
    case NICE_CANDIDATE_TYPE_PEER_REFLEXIVE:
      type = 'P';
      break;
    case NICE_CANDIDATE_TYPE_RELAYED:
      type = 'R';
      break;
    default:
      return NULL;
    }

  addr_tmp = nice_address_to_string (&(candidate->addr));
  ret = g_strdup_printf ("%c/%s/%d", type, addr_tmp, candidate->port);
  g_free (addr_tmp);
  return ret;
}