1
/* $Id: turn_sock.c 3596 2011-06-22 10:57:11Z bennylp $ */
3
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
4
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
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.
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.
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
20
#include <pjnath/turn_sock.h>
21
#include <pj/activesock.h>
22
#include <pj/assert.h>
27
#include <pj/ioqueue.h>
35
#define INIT 0x1FFFFFFF
41
pj_turn_session *sess;
47
pj_turn_alloc_param alloc_param;
49
pj_turn_sock_cfg setting;
51
pj_bool_t destroy_request;
55
pj_turn_tp_type conn_type;
56
pj_activesock_t *active_sock;
57
pj_ioqueue_op_key_t send_key;
62
* Callback prototypes.
64
static pj_status_t turn_on_send_pkt(pj_turn_session *sess,
65
const pj_uint8_t *pkt,
67
const pj_sockaddr_t *dst_addr,
68
unsigned dst_addr_len);
69
static void turn_on_channel_bound(pj_turn_session *sess,
70
const pj_sockaddr_t *peer_addr,
73
static void turn_on_rx_data(pj_turn_session *sess,
76
const pj_sockaddr_t *peer_addr,
78
static void turn_on_state(pj_turn_session *sess,
79
pj_turn_state_t old_state,
80
pj_turn_state_t new_state);
82
static pj_bool_t on_data_read(pj_activesock_t *asock,
86
pj_size_t *remainder);
87
static pj_bool_t on_connect_complete(pj_activesock_t *asock,
92
static void destroy(pj_turn_sock *turn_sock);
93
static void timer_cb(pj_timer_heap_t *th, pj_timer_entry *e);
97
PJ_DEF(void) pj_turn_sock_cfg_default(pj_turn_sock_cfg *cfg)
99
pj_bzero(cfg, sizeof(*cfg));
100
cfg->qos_type = PJ_QOS_TYPE_BEST_EFFORT;
101
cfg->qos_ignore_error = PJ_TRUE;
107
PJ_DEF(pj_status_t) pj_turn_sock_create(pj_stun_config *cfg,
109
pj_turn_tp_type conn_type,
110
const pj_turn_sock_cb *cb,
111
const pj_turn_sock_cfg *setting,
113
pj_turn_sock **p_turn_sock)
115
pj_turn_sock *turn_sock;
116
pj_turn_session_cb sess_cb;
117
pj_turn_sock_cfg default_setting;
119
const char *name_tmpl;
122
PJ_ASSERT_RETURN(cfg && p_turn_sock, PJ_EINVAL);
123
PJ_ASSERT_RETURN(af==pj_AF_INET() || af==pj_AF_INET6(), PJ_EINVAL);
124
PJ_ASSERT_RETURN(conn_type!=PJ_TURN_TP_TCP || PJ_HAS_TCP, PJ_EINVAL);
127
pj_turn_sock_cfg_default(&default_setting);
128
setting = &default_setting;
133
name_tmpl = "udprel%p";
136
name_tmpl = "tcprel%p";
139
PJ_ASSERT_RETURN(!"Invalid TURN conn_type", PJ_EINVAL);
140
name_tmpl = "tcprel%p";
144
/* Create and init basic data structure */
145
pool = pj_pool_create(cfg->pf, name_tmpl, PJNATH_POOL_LEN_TURN_SOCK,
146
PJNATH_POOL_INC_TURN_SOCK, NULL);
147
turn_sock = PJ_POOL_ZALLOC_T(pool, pj_turn_sock);
148
turn_sock->pool = pool;
149
turn_sock->obj_name = pool->obj_name;
150
turn_sock->user_data = user_data;
152
turn_sock->conn_type = conn_type;
154
/* Copy STUN config (this contains ioqueue, timer heap, etc.) */
155
pj_memcpy(&turn_sock->cfg, cfg, sizeof(*cfg));
157
/* Copy setting (QoS parameters etc */
158
pj_memcpy(&turn_sock->setting, setting, sizeof(*setting));
162
pj_memcpy(&turn_sock->cb, cb, sizeof(*cb));
166
status = pj_lock_create_recursive_mutex(pool, turn_sock->obj_name,
168
if (status != PJ_SUCCESS) {
174
pj_timer_entry_init(&turn_sock->timer, TIMER_NONE, turn_sock, &timer_cb);
176
/* Init TURN session */
177
pj_bzero(&sess_cb, sizeof(sess_cb));
178
sess_cb.on_send_pkt = &turn_on_send_pkt;
179
sess_cb.on_channel_bound = &turn_on_channel_bound;
180
sess_cb.on_rx_data = &turn_on_rx_data;
181
sess_cb.on_state = &turn_on_state;
182
status = pj_turn_session_create(cfg, pool->obj_name, af, conn_type,
183
&sess_cb, 0, turn_sock, &turn_sock->sess);
184
if (status != PJ_SUCCESS) {
189
/* Note: socket and ioqueue will be created later once the TURN server
193
*p_turn_sock = turn_sock;
200
static void destroy(pj_turn_sock *turn_sock)
202
if (turn_sock->lock) {
203
pj_lock_acquire(turn_sock->lock);
206
if (turn_sock->sess) {
207
pj_turn_session_set_user_data(turn_sock->sess, NULL);
208
pj_turn_session_shutdown(turn_sock->sess);
209
turn_sock->sess = NULL;
212
if (turn_sock->active_sock) {
213
pj_activesock_close(turn_sock->active_sock);
214
turn_sock->active_sock = NULL;
217
if (turn_sock->lock) {
218
pj_lock_release(turn_sock->lock);
219
pj_lock_destroy(turn_sock->lock);
220
turn_sock->lock = NULL;
223
if (turn_sock->pool) {
224
pj_pool_t *pool = turn_sock->pool;
225
turn_sock->pool = NULL;
226
pj_pool_release(pool);
231
PJ_DEF(void) pj_turn_sock_destroy(pj_turn_sock *turn_sock)
233
pj_lock_acquire(turn_sock->lock);
234
turn_sock->destroy_request = PJ_TRUE;
236
if (turn_sock->sess) {
237
pj_turn_session_shutdown(turn_sock->sess);
238
/* This will ultimately call our state callback, and when
239
* session state is DESTROYING we will schedule a timer to
242
pj_lock_release(turn_sock->lock);
244
pj_lock_release(turn_sock->lock);
252
static void timer_cb(pj_timer_heap_t *th, pj_timer_entry *e)
254
pj_turn_sock *turn_sock = (pj_turn_sock*)e->user_data;
263
PJ_LOG(5,(turn_sock->obj_name, "Destroying TURN"));
267
pj_assert(!"Invalid timer id");
274
static void show_err(pj_turn_sock *turn_sock, const char *title,
277
PJ_PERROR(4,(turn_sock->obj_name, status, title));
280
/* On error, terminate session */
281
static void sess_fail(pj_turn_sock *turn_sock, const char *title,
284
show_err(turn_sock, title, status);
285
if (turn_sock->sess) {
286
pj_turn_session_destroy(turn_sock->sess, status);
293
PJ_DEF(pj_status_t) pj_turn_sock_set_user_data( pj_turn_sock *turn_sock,
296
PJ_ASSERT_RETURN(turn_sock, PJ_EINVAL);
297
turn_sock->user_data = user_data;
304
PJ_DEF(void*) pj_turn_sock_get_user_data(pj_turn_sock *turn_sock)
306
PJ_ASSERT_RETURN(turn_sock, NULL);
307
return turn_sock->user_data;
313
PJ_DEF(pj_status_t) pj_turn_sock_get_info(pj_turn_sock *turn_sock,
314
pj_turn_session_info *info)
316
PJ_ASSERT_RETURN(turn_sock && info, PJ_EINVAL);
318
if (turn_sock->sess) {
319
return pj_turn_session_get_info(turn_sock->sess, info);
321
pj_bzero(info, sizeof(*info));
322
info->state = PJ_TURN_STATE_NULL;
328
* Lock the TURN socket. Application may need to call this function to
329
* synchronize access to other objects to avoid deadlock.
331
PJ_DEF(pj_status_t) pj_turn_sock_lock(pj_turn_sock *turn_sock)
333
return pj_lock_acquire(turn_sock->lock);
337
* Unlock the TURN socket.
339
PJ_DEF(pj_status_t) pj_turn_sock_unlock(pj_turn_sock *turn_sock)
341
return pj_lock_release(turn_sock->lock);
345
* Set STUN message logging for this TURN session.
347
PJ_DEF(void) pj_turn_sock_set_log( pj_turn_sock *turn_sock,
350
pj_turn_session_set_log(turn_sock->sess, flags);
356
PJ_DEF(pj_status_t) pj_turn_sock_set_software_name( pj_turn_sock *turn_sock,
359
return pj_turn_session_set_software_name(turn_sock->sess, sw);
365
PJ_DEF(pj_status_t) pj_turn_sock_alloc(pj_turn_sock *turn_sock,
366
const pj_str_t *domain,
368
pj_dns_resolver *resolver,
369
const pj_stun_auth_cred *cred,
370
const pj_turn_alloc_param *param)
374
PJ_ASSERT_RETURN(turn_sock && domain, PJ_EINVAL);
375
PJ_ASSERT_RETURN(turn_sock->sess, PJ_EINVALIDOP);
377
/* Copy alloc param. We will call session_alloc() only after the
378
* server address has been resolved.
381
pj_turn_alloc_param_copy(turn_sock->pool, &turn_sock->alloc_param, param);
383
pj_turn_alloc_param_default(&turn_sock->alloc_param);
388
status = pj_turn_session_set_credential(turn_sock->sess, cred);
389
if (status != PJ_SUCCESS) {
390
sess_fail(turn_sock, "Error setting credential", status);
396
status = pj_turn_session_set_server(turn_sock->sess, domain, default_port,
398
if (status != PJ_SUCCESS) {
399
sess_fail(turn_sock, "Error setting TURN server", status);
403
/* Done for now. The next work will be done when session state moved
413
PJ_DEF(pj_status_t) pj_turn_sock_set_perm( pj_turn_sock *turn_sock,
415
const pj_sockaddr addr[],
418
if (turn_sock->sess == NULL)
419
return PJ_EINVALIDOP;
421
return pj_turn_session_set_perm(turn_sock->sess, addr_cnt, addr, options);
427
PJ_DEF(pj_status_t) pj_turn_sock_sendto( pj_turn_sock *turn_sock,
428
const pj_uint8_t *pkt,
430
const pj_sockaddr_t *addr,
433
PJ_ASSERT_RETURN(turn_sock && addr && addr_len, PJ_EINVAL);
435
if (turn_sock->sess == NULL)
436
return PJ_EINVALIDOP;
438
return pj_turn_session_sendto(turn_sock->sess, pkt, pkt_len,
443
* Bind a peer address to a channel number.
445
PJ_DEF(pj_status_t) pj_turn_sock_bind_channel( pj_turn_sock *turn_sock,
446
const pj_sockaddr_t *peer,
449
PJ_ASSERT_RETURN(turn_sock && peer && addr_len, PJ_EINVAL);
450
PJ_ASSERT_RETURN(turn_sock->sess != NULL, PJ_EINVALIDOP);
452
return pj_turn_session_bind_channel(turn_sock->sess, peer, addr_len);
457
* Notification when outgoing TCP socket has been connected.
459
static pj_bool_t on_connect_complete(pj_activesock_t *asock,
462
pj_turn_sock *turn_sock;
464
turn_sock = (pj_turn_sock*) pj_activesock_get_user_data(asock);
466
if (status != PJ_SUCCESS) {
467
sess_fail(turn_sock, "TCP connect() error", status);
471
if (turn_sock->conn_type != PJ_TURN_TP_UDP) {
472
PJ_LOG(5,(turn_sock->obj_name, "TCP connected"));
475
/* Kick start pending read operation */
476
status = pj_activesock_start_read(asock, turn_sock->pool,
477
PJ_TURN_MAX_PKT_LEN, 0);
480
pj_ioqueue_op_key_init(&turn_sock->send_key, sizeof(turn_sock->send_key));
482
/* Send Allocate request */
483
status = pj_turn_session_alloc(turn_sock->sess, &turn_sock->alloc_param);
484
if (status != PJ_SUCCESS) {
485
sess_fail(turn_sock, "Error sending ALLOCATE", status);
492
static pj_uint16_t GETVAL16H(const pj_uint8_t *buf, unsigned pos)
494
return (pj_uint16_t) ((buf[pos + 0] << 8) | \
495
(buf[pos + 1] << 0));
498
/* Quick check to determine if there is enough packet to process in the
499
* incoming buffer. Return the packet length, or zero if there's no packet.
501
static unsigned has_packet(pj_turn_sock *turn_sock, const void *buf, pj_size_t bufsize)
505
if (turn_sock->conn_type == PJ_TURN_TP_UDP)
508
/* Quickly check if this is STUN message, by checking the first two bits and
509
* size field which must be multiple of 4 bytes
511
is_stun = ((((pj_uint8_t*)buf)[0] & 0xC0) == 0) &&
512
((GETVAL16H((const pj_uint8_t*)buf, 2) & 0x03)==0);
515
pj_size_t msg_len = GETVAL16H((const pj_uint8_t*)buf, 2);
516
return (msg_len+20 <= bufsize) ? msg_len+20 : 0;
518
/* This must be ChannelData. */
519
pj_turn_channel_data cd;
524
/* Decode ChannelData packet */
525
pj_memcpy(&cd, buf, sizeof(pj_turn_channel_data));
526
cd.length = pj_ntohs(cd.length);
528
if (bufsize >= cd.length+sizeof(cd))
529
return (cd.length+sizeof(cd)+3) & (~3);
536
* Notification from ioqueue when incoming UDP packet is received.
538
static pj_bool_t on_data_read(pj_activesock_t *asock,
542
pj_size_t *remainder)
544
pj_turn_sock *turn_sock;
545
pj_bool_t ret = PJ_TRUE;
547
turn_sock = (pj_turn_sock*) pj_activesock_get_user_data(asock);
548
pj_lock_acquire(turn_sock->lock);
550
if (status == PJ_SUCCESS && turn_sock->sess) {
551
/* Report incoming packet to TURN session, repeat while we have
552
* "packet" in the buffer (required for stream-oriented transports)
556
//PJ_LOG(5,(turn_sock->pool->obj_name,
557
// "Incoming data, %lu bytes total buffer", size));
559
while ((pkt_len=has_packet(turn_sock, data, size)) != 0) {
560
pj_size_t parsed_len;
561
//const pj_uint8_t *pkt = (const pj_uint8_t*)data;
563
//PJ_LOG(5,(turn_sock->pool->obj_name,
564
// "Packet start: %02X %02X %02X %02X",
565
// pkt[0], pkt[1], pkt[2], pkt[3]));
567
//PJ_LOG(5,(turn_sock->pool->obj_name,
568
// "Processing %lu bytes packet of %lu bytes total buffer",
571
parsed_len = (unsigned)size;
572
pj_turn_session_on_rx_pkt(turn_sock->sess, data, size, &parsed_len);
574
/* parsed_len may be zero if we have parsing error, so use our
575
* previous calculation to exhaust the bad packet.
578
parsed_len = pkt_len;
580
if (parsed_len < (unsigned)size) {
581
*remainder = size - parsed_len;
582
pj_memmove(data, ((char*)data)+parsed_len, *remainder);
588
//PJ_LOG(5,(turn_sock->pool->obj_name,
589
// "Buffer size now %lu bytes", size));
591
} else if (status != PJ_SUCCESS &&
592
turn_sock->conn_type != PJ_TURN_TP_UDP)
594
sess_fail(turn_sock, "TCP connection closed", status);
600
pj_lock_release(turn_sock->lock);
607
* Callback from TURN session to send outgoing packet.
609
static pj_status_t turn_on_send_pkt(pj_turn_session *sess,
610
const pj_uint8_t *pkt,
612
const pj_sockaddr_t *dst_addr,
613
unsigned dst_addr_len)
615
pj_turn_sock *turn_sock = (pj_turn_sock*)
616
pj_turn_session_get_user_data(sess);
617
pj_ssize_t len = pkt_len;
620
if (turn_sock == NULL) {
621
/* We've been destroyed */
622
// https://trac.pjsip.org/repos/ticket/1316
623
//pj_assert(!"We should shutdown gracefully");
624
return PJ_EINVALIDOP;
627
PJ_UNUSED_ARG(dst_addr);
628
PJ_UNUSED_ARG(dst_addr_len);
630
status = pj_activesock_send(turn_sock->active_sock, &turn_sock->send_key,
632
if (status != PJ_SUCCESS && status != PJ_EPENDING) {
633
show_err(turn_sock, "socket send()", status);
641
* Callback from TURN session when a channel is successfully bound.
643
static void turn_on_channel_bound(pj_turn_session *sess,
644
const pj_sockaddr_t *peer_addr,
649
PJ_UNUSED_ARG(peer_addr);
650
PJ_UNUSED_ARG(addr_len);
651
PJ_UNUSED_ARG(ch_num);
656
* Callback from TURN session upon incoming data.
658
static void turn_on_rx_data(pj_turn_session *sess,
661
const pj_sockaddr_t *peer_addr,
664
pj_turn_sock *turn_sock = (pj_turn_sock*)
665
pj_turn_session_get_user_data(sess);
666
if (turn_sock == NULL) {
667
/* We've been destroyed */
671
if (turn_sock->cb.on_rx_data) {
672
(*turn_sock->cb.on_rx_data)(turn_sock, pkt, pkt_len,
673
peer_addr, addr_len);
679
* Callback from TURN session when state has changed
681
static void turn_on_state(pj_turn_session *sess,
682
pj_turn_state_t old_state,
683
pj_turn_state_t new_state)
685
pj_turn_sock *turn_sock = (pj_turn_sock*)
686
pj_turn_session_get_user_data(sess);
689
if (turn_sock == NULL) {
690
/* We've been destroyed */
694
/* Notify app first */
695
if (turn_sock->cb.on_state) {
696
(*turn_sock->cb.on_state)(turn_sock, old_state, new_state);
699
/* Make sure user hasn't destroyed us in the callback */
700
if (turn_sock->sess && new_state == PJ_TURN_STATE_RESOLVED) {
701
pj_turn_session_info info;
702
pj_turn_session_get_info(turn_sock->sess, &info);
703
new_state = info.state;
706
if (turn_sock->sess && new_state == PJ_TURN_STATE_RESOLVED) {
708
* Once server has been resolved, initiate outgoing TCP
709
* connection to the server.
711
pj_turn_session_info info;
712
char addrtxt[PJ_INET6_ADDRSTRLEN+8];
715
pj_activesock_cb asock_cb;
717
/* Close existing connection, if any. This happens when
718
* we're switching to alternate TURN server when either TCP
719
* connection or ALLOCATE request failed.
721
if (turn_sock->active_sock) {
722
pj_activesock_close(turn_sock->active_sock);
723
turn_sock->active_sock = NULL;
726
/* Get server address from session info */
727
pj_turn_session_get_info(sess, &info);
729
if (turn_sock->conn_type == PJ_TURN_TP_UDP)
730
sock_type = pj_SOCK_DGRAM();
732
sock_type = pj_SOCK_STREAM();
735
status = pj_sock_socket(turn_sock->af, sock_type, 0, &sock);
736
if (status != PJ_SUCCESS) {
737
pj_turn_sock_destroy(turn_sock);
741
/* Apply QoS, if specified */
742
status = pj_sock_apply_qos2(sock, turn_sock->setting.qos_type,
743
&turn_sock->setting.qos_params,
744
(turn_sock->setting.qos_ignore_error?2:1),
745
turn_sock->pool->obj_name, NULL);
746
if (status != PJ_SUCCESS && !turn_sock->setting.qos_ignore_error) {
747
pj_turn_sock_destroy(turn_sock);
751
/* Create active socket */
752
pj_bzero(&asock_cb, sizeof(asock_cb));
753
asock_cb.on_data_read = &on_data_read;
754
asock_cb.on_connect_complete = &on_connect_complete;
755
status = pj_activesock_create(turn_sock->pool, sock,
757
turn_sock->cfg.ioqueue, &asock_cb,
759
&turn_sock->active_sock);
760
if (status != PJ_SUCCESS) {
761
pj_turn_sock_destroy(turn_sock);
765
PJ_LOG(5,(turn_sock->pool->obj_name,
767
pj_sockaddr_print(&info.server, addrtxt,
768
sizeof(addrtxt), 3)));
770
/* Initiate non-blocking connect */
772
status=pj_activesock_start_connect(turn_sock->active_sock,
775
pj_sockaddr_get_len(&info.server));
776
if (status == PJ_SUCCESS) {
777
on_connect_complete(turn_sock->active_sock, PJ_SUCCESS);
778
} else if (status != PJ_EPENDING) {
779
pj_turn_sock_destroy(turn_sock);
783
on_connect_complete(turn_sock->active_sock, PJ_SUCCESS);
786
/* Done for now. Subsequent work will be done in
787
* on_connect_complete() callback.
791
if (new_state >= PJ_TURN_STATE_DESTROYING && turn_sock->sess) {
792
pj_time_val delay = {0, 0};
794
turn_sock->sess = NULL;
795
pj_turn_session_set_user_data(sess, NULL);
797
if (turn_sock->timer.id) {
798
pj_timer_heap_cancel(turn_sock->cfg.timer_heap, &turn_sock->timer);
799
turn_sock->timer.id = 0;
802
turn_sock->timer.id = TIMER_DESTROY;
803
pj_timer_heap_schedule(turn_sock->cfg.timer_heap, &turn_sock->timer,