~noskcaj/ubuntu/saucy/sflphone/merge-1.2.3-2

« back to all changes in this revision

Viewing changes to daemon/libs/pjproject/pjlib-util/src/pjlib-util/stun_simple_client.c

  • Committer: Jackson Doak
  • Date: 2013-07-10 21:04:46 UTC
  • mfrom: (20.1.3 sid)
  • Revision ID: noskcaj@ubuntu.com-20130710210446-y8f587vza807icr9
Properly merged from upstream.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
/* $Id: stun_simple_client.c 3896 2011-12-05 02:12:38Z bennylp $ */
2
 
/* 
3
 
 * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
4
 
 * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
5
 
 *
6
 
 * This program 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
 
 * This program 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 
19
 
 */
20
 
#include <pjlib-util/stun_simple.h>
21
 
#include <pjlib-util/errno.h>
22
 
#include <pj/compat/socket.h>
23
 
#include <pj/log.h>
24
 
#include <pj/os.h>
25
 
#include <pj/pool.h>
26
 
#include <pj/rand.h>
27
 
#include <pj/sock_select.h>
28
 
#include <pj/string.h>
29
 
 
30
 
 
31
 
enum { MAX_REQUEST = 4 };
32
 
static int stun_timer[] = {500, 500, 500, 500 };
33
 
#define STUN_MAGIC 0x2112A442
34
 
 
35
 
#define THIS_FILE       "stun_client.c"
36
 
#define LOG_ADDR(addr)  pj_inet_ntoa(addr.sin_addr), pj_ntohs(addr.sin_port)
37
 
 
38
 
#define TRACE_(x)       PJ_LOG(6,x)
39
 
 
40
 
PJ_DEF(pj_status_t) pjstun_get_mapped_addr( pj_pool_factory *pf,
41
 
                                            int sock_cnt, pj_sock_t sock[],
42
 
                                            const pj_str_t *srv1, int port1,
43
 
                                            const pj_str_t *srv2, int port2,
44
 
                                            pj_sockaddr_in mapped_addr[])
45
 
{
46
 
    unsigned srv_cnt;
47
 
    pj_sockaddr_in srv_addr[2];
48
 
    int i, j, send_cnt = 0, nfds;
49
 
    pj_pool_t *pool;
50
 
    struct query_rec {
51
 
        struct {
52
 
            pj_uint32_t mapped_addr;
53
 
            pj_uint32_t mapped_port;
54
 
        } srv[2];
55
 
    } *rec;
56
 
    void       *out_msg;
57
 
    pj_size_t   out_msg_len;
58
 
    int wait_resp = 0;
59
 
    pj_status_t status;
60
 
 
61
 
    PJ_CHECK_STACK();
62
 
 
63
 
    TRACE_((THIS_FILE, "Entering pjstun_get_mapped_addr()"));
64
 
 
65
 
    /* Create pool. */
66
 
    pool = pj_pool_create(pf, "stun%p", 400, 400, NULL);
67
 
    if (!pool)
68
 
        return PJ_ENOMEM;
69
 
 
70
 
 
71
 
    /* Allocate client records */
72
 
    rec = (struct query_rec*) pj_pool_calloc(pool, sock_cnt, sizeof(*rec));
73
 
    if (!rec) {
74
 
        status = PJ_ENOMEM;
75
 
        goto on_error;
76
 
    }
77
 
 
78
 
    TRACE_((THIS_FILE, "  Memory allocated."));
79
 
 
80
 
    /* Create the outgoing BIND REQUEST message template */
81
 
    status = pjstun_create_bind_req( pool, &out_msg, &out_msg_len, 
82
 
                                      pj_rand(), pj_rand());
83
 
    if (status != PJ_SUCCESS)
84
 
        goto on_error;
85
 
 
86
 
    TRACE_((THIS_FILE, "  Binding request created."));
87
 
 
88
 
    /* Resolve servers. */
89
 
    status = pj_sockaddr_in_init(&srv_addr[0], srv1, (pj_uint16_t)port1);
90
 
    if (status != PJ_SUCCESS)
91
 
        goto on_error;
92
 
 
93
 
    srv_cnt = 1;
94
 
 
95
 
    if (srv2 && port2) {
96
 
        status = pj_sockaddr_in_init(&srv_addr[1], srv2, (pj_uint16_t)port2);
97
 
        if (status != PJ_SUCCESS)
98
 
            goto on_error;
99
 
 
100
 
        if (srv_addr[1].sin_addr.s_addr != srv_addr[0].sin_addr.s_addr &&
101
 
            srv_addr[1].sin_port != srv_addr[0].sin_port)
102
 
        {
103
 
            srv_cnt++;
104
 
        }
105
 
    }
106
 
 
107
 
    TRACE_((THIS_FILE, "  Server initialized, using %d server(s)", srv_cnt));
108
 
 
109
 
    /* Init mapped addresses to zero */
110
 
    pj_memset(mapped_addr, 0, sock_cnt * sizeof(pj_sockaddr_in));
111
 
 
112
 
    /* We need these many responses */
113
 
    wait_resp = sock_cnt * srv_cnt;
114
 
 
115
 
    TRACE_((THIS_FILE, "  Done initialization."));
116
 
 
117
 
#if defined(PJ_SELECT_NEEDS_NFDS) && PJ_SELECT_NEEDS_NFDS!=0
118
 
    nfds = -1;
119
 
    for (i=0; i<sock_cnt; ++i) {
120
 
        if (sock[i] > nfds) {
121
 
            nfds = sock[i];
122
 
        }
123
 
    }
124
 
#else
125
 
    nfds = FD_SETSIZE-1;
126
 
#endif
127
 
 
128
 
    /* Main retransmission loop. */
129
 
    for (send_cnt=0; send_cnt<MAX_REQUEST; ++send_cnt) {
130
 
        pj_time_val next_tx, now;
131
 
        pj_fd_set_t r;
132
 
        int select_rc;
133
 
 
134
 
        PJ_FD_ZERO(&r);
135
 
 
136
 
        /* Send messages to servers that has not given us response. */
137
 
        for (i=0; i<sock_cnt && status==PJ_SUCCESS; ++i) {
138
 
            for (j=0; j<srv_cnt && status==PJ_SUCCESS; ++j) {
139
 
                pjstun_msg_hdr *msg_hdr = (pjstun_msg_hdr*) out_msg;
140
 
                pj_ssize_t sent_len;
141
 
 
142
 
                if (rec[i].srv[j].mapped_port != 0)
143
 
                    continue;
144
 
 
145
 
                /* Modify message so that we can distinguish response. */
146
 
                msg_hdr->tsx[2] = pj_htonl(i);
147
 
                msg_hdr->tsx[3] = pj_htonl(j);
148
 
 
149
 
                /* Send! */
150
 
                sent_len = out_msg_len;
151
 
                status = pj_sock_sendto(sock[i], out_msg, &sent_len, 0,
152
 
                                        (pj_sockaddr_t*)&srv_addr[j],
153
 
                                        sizeof(pj_sockaddr_in));
154
 
            }
155
 
        }
156
 
 
157
 
        /* All requests sent.
158
 
         * The loop below will wait for responses until all responses have
159
 
         * been received (i.e. wait_resp==0) or timeout occurs, which then
160
 
         * we'll go to the next retransmission iteration.
161
 
         */
162
 
        TRACE_((THIS_FILE, "  Request(s) sent, counter=%d", send_cnt));
163
 
 
164
 
        /* Calculate time of next retransmission. */
165
 
        pj_gettimeofday(&next_tx);
166
 
        next_tx.sec += (stun_timer[send_cnt]/1000);
167
 
        next_tx.msec += (stun_timer[send_cnt]%1000);
168
 
        pj_time_val_normalize(&next_tx);
169
 
 
170
 
        for (pj_gettimeofday(&now), select_rc=1; 
171
 
             status==PJ_SUCCESS && select_rc>=1 && wait_resp>0 
172
 
               && PJ_TIME_VAL_LT(now, next_tx); 
173
 
             pj_gettimeofday(&now)) 
174
 
        {
175
 
            pj_time_val timeout;
176
 
 
177
 
            timeout = next_tx;
178
 
            PJ_TIME_VAL_SUB(timeout, now);
179
 
 
180
 
            for (i=0; i<sock_cnt; ++i) {
181
 
                PJ_FD_SET(sock[i], &r);
182
 
            }
183
 
 
184
 
            select_rc = pj_sock_select(nfds+1, &r, NULL, NULL, &timeout);
185
 
            TRACE_((THIS_FILE, "  select() rc=%d", select_rc));
186
 
            if (select_rc < 1)
187
 
                continue;
188
 
 
189
 
            for (i=0; i<sock_cnt; ++i) {
190
 
                int sock_idx, srv_idx;
191
 
                pj_ssize_t len;
192
 
                pjstun_msg msg;
193
 
                pj_sockaddr_in addr;
194
 
                int addrlen = sizeof(addr);
195
 
                pjstun_mapped_addr_attr *attr;
196
 
                char recv_buf[128];
197
 
 
198
 
                if (!PJ_FD_ISSET(sock[i], &r))
199
 
                    continue;
200
 
 
201
 
                len = sizeof(recv_buf);
202
 
                status = pj_sock_recvfrom( sock[i], recv_buf, 
203
 
                                           &len, 0,
204
 
                                           (pj_sockaddr_t*)&addr,
205
 
                                           &addrlen);
206
 
 
207
 
                if (status != PJ_SUCCESS) {
208
 
                    char errmsg[PJ_ERR_MSG_SIZE];
209
 
 
210
 
                    PJ_LOG(4,(THIS_FILE, "recvfrom() error ignored: %s",
211
 
                              pj_strerror(status, errmsg,sizeof(errmsg)).ptr));
212
 
 
213
 
                    /* Ignore non-PJ_SUCCESS status.
214
 
                     * It possible that other SIP entity is currently 
215
 
                     * sending SIP request to us, and because SIP message
216
 
                     * is larger than STUN, we could get EMSGSIZE when
217
 
                     * we call recvfrom().
218
 
                     */
219
 
                    status = PJ_SUCCESS;
220
 
                    continue;
221
 
                }
222
 
 
223
 
                status = pjstun_parse_msg(recv_buf, len, &msg);
224
 
                if (status != PJ_SUCCESS) {
225
 
                    char errmsg[PJ_ERR_MSG_SIZE];
226
 
 
227
 
                    PJ_LOG(4,(THIS_FILE, "STUN parsing error ignored: %s",
228
 
                              pj_strerror(status, errmsg,sizeof(errmsg)).ptr));
229
 
 
230
 
                    /* Also ignore non-successful parsing. This may not
231
 
                     * be STUN response at all. See the comment above.
232
 
                     */
233
 
                    status = PJ_SUCCESS;
234
 
                    continue;
235
 
                }
236
 
 
237
 
                sock_idx = pj_ntohl(msg.hdr->tsx[2]);
238
 
                srv_idx = pj_ntohl(msg.hdr->tsx[3]);
239
 
 
240
 
                if (sock_idx<0 || sock_idx>=sock_cnt || sock_idx!=i ||
241
 
                        srv_idx<0 || srv_idx>=2)
242
 
                {
243
 
                    status = PJLIB_UTIL_ESTUNININDEX;
244
 
                    continue;
245
 
                }
246
 
 
247
 
                if (pj_ntohs(msg.hdr->type) != PJSTUN_BINDING_RESPONSE) {
248
 
                    status = PJLIB_UTIL_ESTUNNOBINDRES;
249
 
                    continue;
250
 
                }
251
 
 
252
 
                if (rec[sock_idx].srv[srv_idx].mapped_port != 0) {
253
 
                    /* Already got response */
254
 
                    continue;
255
 
                }
256
 
 
257
 
                /* From this part, we consider the packet as a valid STUN
258
 
                 * response for our request.
259
 
                 */
260
 
                --wait_resp;
261
 
 
262
 
                if (pjstun_msg_find_attr(&msg, PJSTUN_ATTR_ERROR_CODE) != NULL) {
263
 
                    status = PJLIB_UTIL_ESTUNRECVERRATTR;
264
 
                    continue;
265
 
                }
266
 
 
267
 
                attr = (pjstun_mapped_addr_attr*) 
268
 
                       pjstun_msg_find_attr(&msg, PJSTUN_ATTR_MAPPED_ADDR);
269
 
                if (!attr) {
270
 
                    attr = (pjstun_mapped_addr_attr*) 
271
 
                           pjstun_msg_find_attr(&msg, PJSTUN_ATTR_XOR_MAPPED_ADDR);
272
 
                    if (!attr || attr->family != 1) {
273
 
                        status = PJLIB_UTIL_ESTUNNOMAP;
274
 
                        continue;
275
 
                    }
276
 
                }
277
 
 
278
 
                rec[sock_idx].srv[srv_idx].mapped_addr = attr->addr;
279
 
                rec[sock_idx].srv[srv_idx].mapped_port = attr->port;
280
 
                if (pj_ntohs(attr->hdr.type) == PJSTUN_ATTR_XOR_MAPPED_ADDR) {
281
 
                    rec[sock_idx].srv[srv_idx].mapped_addr ^= pj_htonl(STUN_MAGIC);
282
 
                    rec[sock_idx].srv[srv_idx].mapped_port ^= pj_htons(STUN_MAGIC >> 16);
283
 
                }
284
 
            }
285
 
        }
286
 
 
287
 
        /* The best scenario is if all requests have been replied.
288
 
         * Then we don't need to go to the next retransmission iteration.
289
 
         */
290
 
        if (wait_resp <= 0)
291
 
            break;
292
 
    }
293
 
 
294
 
    TRACE_((THIS_FILE, "  All responses received, calculating result.."));
295
 
 
296
 
    for (i=0; i<sock_cnt && status==PJ_SUCCESS; ++i) {
297
 
        if (srv_cnt == 1) {
298
 
            mapped_addr[i].sin_family = pj_AF_INET();
299
 
            mapped_addr[i].sin_addr.s_addr = rec[i].srv[0].mapped_addr;
300
 
            mapped_addr[i].sin_port = (pj_uint16_t)rec[i].srv[0].mapped_port;
301
 
 
302
 
            if (rec[i].srv[0].mapped_addr == 0 || rec[i].srv[0].mapped_port == 0) {
303
 
                status = PJLIB_UTIL_ESTUNNOTRESPOND;
304
 
                break;
305
 
            }
306
 
        } else if (rec[i].srv[0].mapped_addr == rec[i].srv[1].mapped_addr &&
307
 
                   rec[i].srv[0].mapped_port == rec[i].srv[1].mapped_port)
308
 
        {
309
 
            mapped_addr[i].sin_family = pj_AF_INET();
310
 
            mapped_addr[i].sin_addr.s_addr = rec[i].srv[0].mapped_addr;
311
 
            mapped_addr[i].sin_port = (pj_uint16_t)rec[i].srv[0].mapped_port;
312
 
 
313
 
            if (rec[i].srv[0].mapped_addr == 0 || rec[i].srv[0].mapped_port == 0) {
314
 
                status = PJLIB_UTIL_ESTUNNOTRESPOND;
315
 
                break;
316
 
            }
317
 
        } else {
318
 
            status = PJLIB_UTIL_ESTUNSYMMETRIC;
319
 
            break;
320
 
        }
321
 
    }
322
 
 
323
 
    TRACE_((THIS_FILE, "  Pool usage=%d of %d", pj_pool_get_used_size(pool),
324
 
            pj_pool_get_capacity(pool)));
325
 
 
326
 
    pj_pool_release(pool);
327
 
 
328
 
    TRACE_((THIS_FILE, "  Done."));
329
 
    return status;
330
 
 
331
 
on_error:
332
 
    if (pool) pj_pool_release(pool);
333
 
    return status;
334
 
}
335