~ubuntu-branches/ubuntu/maverick/sflphone/maverick

« back to all changes in this revision

Viewing changes to sflphone-common/libs/pjproject/pjsip/src/pjsua-lib/pjsua_core.c

  • Committer: Bazaar Package Importer
  • Author(s): Francois Marier
  • Date: 2010-06-03 15:59:46 UTC
  • Revision ID: james.westby@ubuntu.com-20100603155946-ybe8d8o8zx8lp0m8
Tags: upstream-0.9.8.3
ImportĀ upstreamĀ versionĀ 0.9.8.3

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/* $Id: pjsua_core.c 3021 2009-11-20 23:33:07Z bennylp $ */
 
2
/* 
 
3
 * Copyright (C) 2008-2009 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
 *  Additional permission under GNU GPL version 3 section 7:
 
21
 *
 
22
 *  If you modify this program, or any covered work, by linking or
 
23
 *  combining it with the OpenSSL project's OpenSSL library (or a
 
24
 *  modified version of that library), containing parts covered by the
 
25
 *  terms of the OpenSSL or SSLeay licenses, Teluu Inc. (http://www.teluu.com)
 
26
 *  grants you additional permission to convey the resulting work.
 
27
 *  Corresponding Source for a non-source form of such a combination
 
28
 *  shall include the source code for the parts of OpenSSL used as well
 
29
 *  as that of the covered work.
 
30
 */
 
31
#include <pjsua-lib/pjsua.h>
 
32
#include <pjsua-lib/pjsua_internal.h>
 
33
 
 
34
 
 
35
#define THIS_FILE   "pjsua_core.c"
 
36
 
 
37
 
 
38
/* Internal prototypes */
 
39
static void resolve_stun_entry(pjsua_stun_resolve *sess);
 
40
 
 
41
 
 
42
/* PJSUA application instance. */
 
43
struct pjsua_data pjsua_var;
 
44
 
 
45
 
 
46
PJ_DEF(struct pjsua_data*) pjsua_get_var(void)
 
47
{
 
48
    return &pjsua_var;
 
49
}
 
50
 
 
51
 
 
52
/* Display error */
 
53
PJ_DEF(void) pjsua_perror( const char *sender, const char *title, 
 
54
                           pj_status_t status)
 
55
{
 
56
    char errmsg[PJ_ERR_MSG_SIZE];
 
57
 
 
58
    pj_strerror(status, errmsg, sizeof(errmsg));
 
59
    PJ_LOG(1,(sender, "%s: %s [status=%d]", title, errmsg, status));
 
60
}
 
61
 
 
62
 
 
63
static void init_data()
 
64
{
 
65
    unsigned i;
 
66
 
 
67
    pj_bzero(&pjsua_var, sizeof(pjsua_var));
 
68
 
 
69
    for (i=0; i<PJ_ARRAY_SIZE(pjsua_var.acc); ++i)
 
70
        pjsua_var.acc[i].index = i;
 
71
    
 
72
    for (i=0; i<PJ_ARRAY_SIZE(pjsua_var.tpdata); ++i)
 
73
        pjsua_var.tpdata[i].index = i;
 
74
 
 
75
    pjsua_var.stun_status = PJ_EUNKNOWN;
 
76
    pjsua_var.nat_status = PJ_EPENDING;
 
77
    pj_list_init(&pjsua_var.stun_res);
 
78
 
 
79
    pjsua_config_default(&pjsua_var.ua_cfg);
 
80
}
 
81
 
 
82
 
 
83
PJ_DEF(void) pjsua_logging_config_default(pjsua_logging_config *cfg)
 
84
{
 
85
    pj_bzero(cfg, sizeof(*cfg));
 
86
 
 
87
    cfg->msg_logging = PJ_TRUE;
 
88
    cfg->level = 5;
 
89
    cfg->console_level = 4;
 
90
    cfg->decor = PJ_LOG_HAS_SENDER | PJ_LOG_HAS_TIME | 
 
91
                 PJ_LOG_HAS_MICRO_SEC | PJ_LOG_HAS_NEWLINE |
 
92
                 PJ_LOG_HAS_SPACE;
 
93
#if defined(PJ_WIN32) && PJ_WIN32 != 0
 
94
    cfg->decor |= PJ_LOG_HAS_COLOR;
 
95
#endif
 
96
}
 
97
 
 
98
PJ_DEF(void) pjsua_logging_config_dup(pj_pool_t *pool,
 
99
                                      pjsua_logging_config *dst,
 
100
                                      const pjsua_logging_config *src)
 
101
{
 
102
    pj_memcpy(dst, src, sizeof(*src));
 
103
    pj_strdup_with_null(pool, &dst->log_filename, &src->log_filename);
 
104
}
 
105
 
 
106
PJ_DEF(void) pjsua_config_default(pjsua_config *cfg)
 
107
{
 
108
    pj_bzero(cfg, sizeof(*cfg));
 
109
 
 
110
    cfg->max_calls = ((PJSUA_MAX_CALLS) < 4) ? (PJSUA_MAX_CALLS) : 4;
 
111
    cfg->thread_cnt = 1;
 
112
    cfg->nat_type_in_sdp = 1;
 
113
    cfg->stun_ignore_failure = PJ_TRUE;
 
114
    cfg->force_lr = PJ_TRUE;
 
115
    cfg->enable_unsolicited_mwi = PJ_TRUE;
 
116
#if defined(PJMEDIA_HAS_SRTP) && (PJMEDIA_HAS_SRTP != 0)
 
117
    cfg->use_srtp = PJSUA_DEFAULT_USE_SRTP;
 
118
    cfg->srtp_secure_signaling = PJSUA_DEFAULT_SRTP_SECURE_SIGNALING;
 
119
#endif
 
120
    cfg->hangup_forked_call = PJ_TRUE;
 
121
 
 
122
    pjsip_timer_setting_default(&cfg->timer_setting);
 
123
}
 
124
 
 
125
PJ_DEF(void) pjsua_config_dup(pj_pool_t *pool,
 
126
                              pjsua_config *dst,
 
127
                              const pjsua_config *src)
 
128
{
 
129
    unsigned i;
 
130
 
 
131
    pj_memcpy(dst, src, sizeof(*src));
 
132
 
 
133
    for (i=0; i<src->outbound_proxy_cnt; ++i) {
 
134
        pj_strdup_with_null(pool, &dst->outbound_proxy[i],
 
135
                            &src->outbound_proxy[i]);
 
136
    }
 
137
 
 
138
    for (i=0; i<src->cred_count; ++i) {
 
139
        pjsip_cred_dup(pool, &dst->cred_info[i], &src->cred_info[i]);
 
140
    }
 
141
 
 
142
    pj_strdup_with_null(pool, &dst->user_agent, &src->user_agent);
 
143
    pj_strdup_with_null(pool, &dst->stun_domain, &src->stun_domain);
 
144
    pj_strdup_with_null(pool, &dst->stun_host, &src->stun_host);
 
145
 
 
146
    for (i=0; i<src->stun_srv_cnt; ++i) {
 
147
        pj_strdup_with_null(pool, &dst->stun_srv[i], &src->stun_srv[i]);
 
148
    }
 
149
}
 
150
 
 
151
PJ_DEF(void) pjsua_msg_data_init(pjsua_msg_data *msg_data)
 
152
{
 
153
    pj_bzero(msg_data, sizeof(*msg_data));
 
154
    pj_list_init(&msg_data->hdr_list);
 
155
}
 
156
 
 
157
PJ_DEF(void) pjsua_transport_config_default(pjsua_transport_config *cfg)
 
158
{
 
159
    pj_bzero(cfg, sizeof(*cfg));
 
160
    pjsip_tls_setting_default(&cfg->tls_setting);
 
161
}
 
162
 
 
163
PJ_DEF(void) pjsua_transport_config_dup(pj_pool_t *pool,
 
164
                                        pjsua_transport_config *dst,
 
165
                                        const pjsua_transport_config *src)
 
166
{
 
167
    PJ_UNUSED_ARG(pool);
 
168
    pj_memcpy(dst, src, sizeof(*src));
 
169
}
 
170
 
 
171
PJ_DEF(void) pjsua_acc_config_default(pjsua_acc_config *cfg)
 
172
{
 
173
    pj_bzero(cfg, sizeof(*cfg));
 
174
 
 
175
    cfg->reg_timeout = PJSUA_REG_INTERVAL;
 
176
    cfg->unreg_timeout = PJSUA_UNREG_TIMEOUT;
 
177
    pjsip_publishc_opt_default(&cfg->publish_opt);
 
178
    cfg->unpublish_max_wait_time_msec = PJSUA_UNPUBLISH_MAX_WAIT_TIME_MSEC;
 
179
    cfg->transport_id = PJSUA_INVALID_ID;
 
180
    cfg->allow_contact_rewrite = PJ_TRUE;
 
181
    cfg->require_100rel = pjsua_var.ua_cfg.require_100rel;
 
182
    cfg->require_timer = pjsua_var.ua_cfg.require_timer;
 
183
    cfg->timer_setting = pjsua_var.ua_cfg.timer_setting;
 
184
    cfg->ka_interval = 15;
 
185
    cfg->ka_data = pj_str("\r\n");
 
186
#if defined(PJMEDIA_HAS_SRTP) && (PJMEDIA_HAS_SRTP != 0)
 
187
    cfg->use_srtp = pjsua_var.ua_cfg.use_srtp;
 
188
    cfg->srtp_secure_signaling = pjsua_var.ua_cfg.srtp_secure_signaling;
 
189
#endif
 
190
}
 
191
 
 
192
PJ_DEF(void) pjsua_buddy_config_default(pjsua_buddy_config *cfg)
 
193
{
 
194
    pj_bzero(cfg, sizeof(*cfg));
 
195
}
 
196
 
 
197
PJ_DEF(void) pjsua_media_config_default(pjsua_media_config *cfg)
 
198
{
 
199
    pj_bzero(cfg, sizeof(*cfg));
 
200
 
 
201
    cfg->clock_rate = PJSUA_DEFAULT_CLOCK_RATE;
 
202
    cfg->snd_clock_rate = 0;
 
203
    cfg->channel_count = 1;
 
204
    cfg->audio_frame_ptime = PJSUA_DEFAULT_AUDIO_FRAME_PTIME;
 
205
    cfg->max_media_ports = PJSUA_MAX_CONF_PORTS;
 
206
    cfg->has_ioqueue = PJ_TRUE;
 
207
    cfg->thread_cnt = 1;
 
208
    cfg->quality = PJSUA_DEFAULT_CODEC_QUALITY;
 
209
    cfg->ilbc_mode = PJSUA_DEFAULT_ILBC_MODE;
 
210
    cfg->ec_tail_len = PJSUA_DEFAULT_EC_TAIL_LEN;
 
211
    cfg->snd_rec_latency = PJMEDIA_SND_DEFAULT_REC_LATENCY;
 
212
    cfg->snd_play_latency = PJMEDIA_SND_DEFAULT_PLAY_LATENCY;
 
213
    cfg->jb_init = cfg->jb_min_pre = cfg->jb_max_pre = cfg->jb_max = -1;
 
214
    cfg->snd_auto_close_time = 1;
 
215
 
 
216
    cfg->ice_max_host_cands = -1;
 
217
    pj_ice_sess_options_default(&cfg->ice_opt);
 
218
 
 
219
    cfg->turn_conn_type = PJ_TURN_TP_UDP;
 
220
}
 
221
 
 
222
 
 
223
/*****************************************************************************
 
224
 * This is a very simple PJSIP module, whose sole purpose is to display
 
225
 * incoming and outgoing messages to log. This module will have priority
 
226
 * higher than transport layer, which means:
 
227
 *
 
228
 *  - incoming messages will come to this module first before reaching
 
229
 *    transaction layer.
 
230
 *
 
231
 *  - outgoing messages will come to this module last, after the message
 
232
 *    has been 'printed' to contiguous buffer by transport layer and
 
233
 *    appropriate transport instance has been decided for this message.
 
234
 *
 
235
 */
 
236
 
 
237
/* Notification on incoming messages */
 
238
static pj_bool_t logging_on_rx_msg(pjsip_rx_data *rdata)
 
239
{
 
240
    PJ_LOG(4,(THIS_FILE, "RX %d bytes %s from %s %s:%d:\n"
 
241
                         "%.*s\n"
 
242
                         "--end msg--",
 
243
                         rdata->msg_info.len,
 
244
                         pjsip_rx_data_get_info(rdata),
 
245
                         rdata->tp_info.transport->type_name,
 
246
                         rdata->pkt_info.src_name,
 
247
                         rdata->pkt_info.src_port,
 
248
                         (int)rdata->msg_info.len,
 
249
                         rdata->msg_info.msg_buf));
 
250
    
 
251
    /* Always return false, otherwise messages will not get processed! */
 
252
    return PJ_FALSE;
 
253
}
 
254
 
 
255
/* Notification on outgoing messages */
 
256
static pj_status_t logging_on_tx_msg(pjsip_tx_data *tdata)
 
257
{
 
258
    
 
259
    /* Important note:
 
260
     *  tp_info field is only valid after outgoing messages has passed
 
261
     *  transport layer. So don't try to access tp_info when the module
 
262
     *  has lower priority than transport layer.
 
263
     */
 
264
 
 
265
    PJ_LOG(4,(THIS_FILE, "TX %d bytes %s to %s %s:%d:\n"
 
266
                         "%.*s\n"
 
267
                         "--end msg--",
 
268
                         (tdata->buf.cur - tdata->buf.start),
 
269
                         pjsip_tx_data_get_info(tdata),
 
270
                         tdata->tp_info.transport->type_name,
 
271
                         tdata->tp_info.dst_name,
 
272
                         tdata->tp_info.dst_port,
 
273
                         (int)(tdata->buf.cur - tdata->buf.start),
 
274
                         tdata->buf.start));
 
275
 
 
276
    /* Always return success, otherwise message will not get sent! */
 
277
    return PJ_SUCCESS;
 
278
}
 
279
 
 
280
/* The module instance. */
 
281
static pjsip_module pjsua_msg_logger = 
 
282
{
 
283
    NULL, NULL,                         /* prev, next.          */
 
284
    { "mod-pjsua-log", 13 },            /* Name.                */
 
285
    -1,                                 /* Id                   */
 
286
    PJSIP_MOD_PRIORITY_TRANSPORT_LAYER-1,/* Priority            */
 
287
    NULL,                               /* load()               */
 
288
    NULL,                               /* start()              */
 
289
    NULL,                               /* stop()               */
 
290
    NULL,                               /* unload()             */
 
291
    &logging_on_rx_msg,                 /* on_rx_request()      */
 
292
    &logging_on_rx_msg,                 /* on_rx_response()     */
 
293
    &logging_on_tx_msg,                 /* on_tx_request.       */
 
294
    &logging_on_tx_msg,                 /* on_tx_response()     */
 
295
    NULL,                               /* on_tsx_state()       */
 
296
 
 
297
};
 
298
 
 
299
 
 
300
/*****************************************************************************
 
301
 * Another simple module to handle incoming OPTIONS request
 
302
 */
 
303
 
 
304
/* Notification on incoming request */
 
305
static pj_bool_t options_on_rx_request(pjsip_rx_data *rdata)
 
306
{
 
307
    pjsip_tx_data *tdata;
 
308
    pjsip_response_addr res_addr;
 
309
    pjmedia_transport_info tpinfo;
 
310
    pjmedia_sdp_session *sdp;
 
311
    const pjsip_hdr *cap_hdr;
 
312
    pj_status_t status;
 
313
 
 
314
    /* Only want to handle OPTIONS requests */
 
315
    if (pjsip_method_cmp(&rdata->msg_info.msg->line.req.method,
 
316
                         pjsip_get_options_method()) != 0)
 
317
    {
 
318
        return PJ_FALSE;
 
319
    }
 
320
 
 
321
    /* Don't want to handle if shutdown is in progress */
 
322
    if (pjsua_var.thread_quit_flag) {
 
323
        pjsip_endpt_respond_stateless(pjsua_var.endpt, rdata, 
 
324
                                      PJSIP_SC_TEMPORARILY_UNAVAILABLE, NULL,
 
325
                                      NULL, NULL);
 
326
        return PJ_TRUE;
 
327
    }
 
328
 
 
329
    /* Create basic response. */
 
330
    status = pjsip_endpt_create_response(pjsua_var.endpt, rdata, 200, NULL, 
 
331
                                         &tdata);
 
332
    if (status != PJ_SUCCESS) {
 
333
        pjsua_perror(THIS_FILE, "Unable to create OPTIONS response", status);
 
334
        return PJ_TRUE;
 
335
    }
 
336
 
 
337
    /* Add Allow header */
 
338
    cap_hdr = pjsip_endpt_get_capability(pjsua_var.endpt, PJSIP_H_ALLOW, NULL);
 
339
    if (cap_hdr) {
 
340
        pjsip_msg_add_hdr(tdata->msg, 
 
341
                          (pjsip_hdr*) pjsip_hdr_clone(tdata->pool, cap_hdr));
 
342
    }
 
343
 
 
344
    /* Add Accept header */
 
345
    cap_hdr = pjsip_endpt_get_capability(pjsua_var.endpt, PJSIP_H_ACCEPT, NULL);
 
346
    if (cap_hdr) {
 
347
        pjsip_msg_add_hdr(tdata->msg, 
 
348
                          (pjsip_hdr*) pjsip_hdr_clone(tdata->pool, cap_hdr));
 
349
    }
 
350
 
 
351
    /* Add Supported header */
 
352
    cap_hdr = pjsip_endpt_get_capability(pjsua_var.endpt, PJSIP_H_SUPPORTED, NULL);
 
353
    if (cap_hdr) {
 
354
        pjsip_msg_add_hdr(tdata->msg, 
 
355
                          (pjsip_hdr*) pjsip_hdr_clone(tdata->pool, cap_hdr));
 
356
    }
 
357
 
 
358
    /* Add Allow-Events header from the evsub module */
 
359
    cap_hdr = pjsip_evsub_get_allow_events_hdr(NULL);
 
360
    if (cap_hdr) {
 
361
        pjsip_msg_add_hdr(tdata->msg, 
 
362
                          (pjsip_hdr*) pjsip_hdr_clone(tdata->pool, cap_hdr));
 
363
    }
 
364
 
 
365
    /* Add User-Agent header */
 
366
    if (pjsua_var.ua_cfg.user_agent.slen) {
 
367
        const pj_str_t USER_AGENT = { "User-Agent", 10};
 
368
        pjsip_hdr *h;
 
369
 
 
370
        h = (pjsip_hdr*) pjsip_generic_string_hdr_create(tdata->pool,
 
371
                                                         &USER_AGENT,
 
372
                                                         &pjsua_var.ua_cfg.user_agent);
 
373
        pjsip_msg_add_hdr(tdata->msg, h);
 
374
    }
 
375
 
 
376
    /* Get media socket info, make sure transport is ready */
 
377
    if (pjsua_var.calls[0].med_tp) {
 
378
        pjmedia_transport_info_init(&tpinfo);
 
379
        pjmedia_transport_get_info(pjsua_var.calls[0].med_tp, &tpinfo);
 
380
 
 
381
        /* Add SDP body, using call0's RTP address */
 
382
        status = pjmedia_endpt_create_sdp(pjsua_var.med_endpt, tdata->pool, 1,
 
383
                                          &tpinfo.sock_info, &sdp);
 
384
        if (status == PJ_SUCCESS) {
 
385
            pjsip_create_sdp_body(tdata->pool, sdp, &tdata->msg->body);
 
386
        }
 
387
    }
 
388
 
 
389
    /* Send response statelessly */
 
390
    pjsip_get_response_addr(tdata->pool, rdata, &res_addr);
 
391
    status = pjsip_endpt_send_response(pjsua_var.endpt, &res_addr, tdata, NULL, NULL);
 
392
    if (status != PJ_SUCCESS)
 
393
        pjsip_tx_data_dec_ref(tdata);
 
394
 
 
395
    return PJ_TRUE;
 
396
}
 
397
 
 
398
 
 
399
/* The module instance. */
 
400
static pjsip_module pjsua_options_handler = 
 
401
{
 
402
    NULL, NULL,                         /* prev, next.          */
 
403
    { "mod-pjsua-options", 17 },        /* Name.                */
 
404
    -1,                                 /* Id                   */
 
405
    PJSIP_MOD_PRIORITY_APPLICATION,     /* Priority             */
 
406
    NULL,                               /* load()               */
 
407
    NULL,                               /* start()              */
 
408
    NULL,                               /* stop()               */
 
409
    NULL,                               /* unload()             */
 
410
    &options_on_rx_request,             /* on_rx_request()      */
 
411
    NULL,                               /* on_rx_response()     */
 
412
    NULL,                               /* on_tx_request.       */
 
413
    NULL,                               /* on_tx_response()     */
 
414
    NULL,                               /* on_tsx_state()       */
 
415
 
 
416
};
 
417
 
 
418
 
 
419
/*****************************************************************************
 
420
 * These two functions are the main callbacks registered to PJSIP stack
 
421
 * to receive SIP request and response messages that are outside any
 
422
 * dialogs and any transactions.
 
423
 */
 
424
 
 
425
/*
 
426
 * Handler for receiving incoming requests.
 
427
 *
 
428
 * This handler serves multiple purposes:
 
429
 *  - it receives requests outside dialogs.
 
430
 *  - it receives requests inside dialogs, when the requests are
 
431
 *    unhandled by other dialog usages. Example of these
 
432
 *    requests are: MESSAGE.
 
433
 */
 
434
static pj_bool_t mod_pjsua_on_rx_request(pjsip_rx_data *rdata)
 
435
{
 
436
    pj_bool_t processed = PJ_FALSE;
 
437
 
 
438
    PJSUA_LOCK();
 
439
 
 
440
    if (rdata->msg_info.msg->line.req.method.id == PJSIP_INVITE_METHOD) {
 
441
 
 
442
        processed = pjsua_call_on_incoming(rdata);
 
443
    }
 
444
 
 
445
    PJSUA_UNLOCK();
 
446
 
 
447
    return processed;
 
448
}
 
449
 
 
450
 
 
451
/*
 
452
 * Handler for receiving incoming responses.
 
453
 *
 
454
 * This handler serves multiple purposes:
 
455
 *  - it receives strayed responses (i.e. outside any dialog and
 
456
 *    outside any transactions).
 
457
 *  - it receives responses coming to a transaction, when pjsua
 
458
 *    module is set as transaction user for the transaction.
 
459
 *  - it receives responses inside a dialog, when these responses
 
460
 *    are unhandled by other dialog usages.
 
461
 */
 
462
static pj_bool_t mod_pjsua_on_rx_response(pjsip_rx_data *rdata)
 
463
{
 
464
    PJ_UNUSED_ARG(rdata);
 
465
    return PJ_FALSE;
 
466
}
 
467
 
 
468
 
 
469
/*****************************************************************************
 
470
 * Logging.
 
471
 */
 
472
 
 
473
/* Log callback */
 
474
static void log_writer(int level, const char *buffer, int len)
 
475
{
 
476
    /* Write to file, stdout or application callback. */
 
477
 
 
478
    if (pjsua_var.log_file) {
 
479
        pj_ssize_t size = len;
 
480
        pj_file_write(pjsua_var.log_file, buffer, &size);
 
481
        /* This will slow things down considerably! Don't do it!
 
482
         pj_file_flush(pjsua_var.log_file);
 
483
        */
 
484
    }
 
485
 
 
486
    if (level <= (int)pjsua_var.log_cfg.console_level) {
 
487
        if (pjsua_var.log_cfg.cb)
 
488
            (*pjsua_var.log_cfg.cb)(level, buffer, len);
 
489
        else
 
490
            pj_log_write(level, buffer, len);
 
491
    }
 
492
}
 
493
 
 
494
 
 
495
/*
 
496
 * Application can call this function at any time (after pjsua_create(), of
 
497
 * course) to change logging settings.
 
498
 */
 
499
PJ_DEF(pj_status_t) pjsua_reconfigure_logging(const pjsua_logging_config *cfg)
 
500
{
 
501
    pj_status_t status;
 
502
 
 
503
    /* Save config. */
 
504
    pjsua_logging_config_dup(pjsua_var.pool, &pjsua_var.log_cfg, cfg);
 
505
 
 
506
    /* Redirect log function to ours */
 
507
    pj_log_set_log_func( &log_writer );
 
508
 
 
509
    /* Set decor */
 
510
    pj_log_set_decor(pjsua_var.log_cfg.decor);
 
511
 
 
512
    /* Set log level */
 
513
    pj_log_set_level(pjsua_var.log_cfg.level);
 
514
 
 
515
    /* Close existing file, if any */
 
516
    if (pjsua_var.log_file) {
 
517
        pj_file_close(pjsua_var.log_file);
 
518
        pjsua_var.log_file = NULL;
 
519
    }
 
520
 
 
521
    /* If output log file is desired, create the file: */
 
522
    if (pjsua_var.log_cfg.log_filename.slen) {
 
523
        unsigned flags = PJ_O_WRONLY;
 
524
        flags |= pjsua_var.log_cfg.log_file_flags;
 
525
        status = pj_file_open(pjsua_var.pool, 
 
526
                              pjsua_var.log_cfg.log_filename.ptr,
 
527
                              flags, 
 
528
                              &pjsua_var.log_file);
 
529
 
 
530
        if (status != PJ_SUCCESS) {
 
531
            pjsua_perror(THIS_FILE, "Error creating log file", status);
 
532
            return status;
 
533
        }
 
534
    }
 
535
 
 
536
    /* Unregister msg logging if it's previously registered */
 
537
    if (pjsua_msg_logger.id >= 0) {
 
538
        pjsip_endpt_unregister_module(pjsua_var.endpt, &pjsua_msg_logger);
 
539
        pjsua_msg_logger.id = -1;
 
540
    }
 
541
 
 
542
    /* Enable SIP message logging */
 
543
    if (pjsua_var.log_cfg.msg_logging)
 
544
        pjsip_endpt_register_module(pjsua_var.endpt, &pjsua_msg_logger);
 
545
 
 
546
    return PJ_SUCCESS;
 
547
}
 
548
 
 
549
 
 
550
/*****************************************************************************
 
551
 * PJSUA Base API.
 
552
 */
 
553
 
 
554
/* Worker thread function. */
 
555
static int worker_thread(void *arg)
 
556
{
 
557
    enum { TIMEOUT = 10 };
 
558
 
 
559
    PJ_UNUSED_ARG(arg);
 
560
 
 
561
    while (!pjsua_var.thread_quit_flag) {
 
562
        int count;
 
563
 
 
564
        count = pjsua_handle_events(TIMEOUT);
 
565
        if (count < 0)
 
566
            pj_thread_sleep(TIMEOUT);
 
567
    }
 
568
 
 
569
    return 0;
 
570
}
 
571
 
 
572
 
 
573
/* Init random seed */
 
574
static void init_random_seed(void)
 
575
{
 
576
    pj_sockaddr addr;
 
577
    const pj_str_t *hostname;
 
578
    pj_uint32_t pid;
 
579
    pj_time_val t;
 
580
    unsigned seed=0;
 
581
 
 
582
    /* Add hostname */
 
583
    hostname = pj_gethostname();
 
584
    seed = pj_hash_calc(seed, hostname->ptr, (int)hostname->slen);
 
585
 
 
586
    /* Add primary IP address */
 
587
    if (pj_gethostip(pj_AF_INET(), &addr)==PJ_SUCCESS)
 
588
        seed = pj_hash_calc(seed, &addr.ipv4.sin_addr, 4);
 
589
 
 
590
    /* Get timeofday */
 
591
    pj_gettimeofday(&t);
 
592
    seed = pj_hash_calc(seed, &t, sizeof(t));
 
593
 
 
594
    /* Add PID */
 
595
    pid = pj_getpid();
 
596
    seed = pj_hash_calc(seed, &pid, sizeof(pid));
 
597
 
 
598
    /* Init random seed */
 
599
    pj_srand(seed);
 
600
}
 
601
 
 
602
/*
 
603
 * Instantiate pjsua application.
 
604
 */
 
605
PJ_DEF(pj_status_t) pjsua_create(void)
 
606
{
 
607
    pj_status_t status;
 
608
 
 
609
    /* Init pjsua data */
 
610
    init_data();
 
611
 
 
612
    /* Set default logging settings */
 
613
    pjsua_logging_config_default(&pjsua_var.log_cfg);
 
614
 
 
615
    /* Init PJLIB: */
 
616
    status = pj_init();
 
617
    PJ_ASSERT_RETURN(status == PJ_SUCCESS, status);
 
618
 
 
619
    /* Init random seed */
 
620
    init_random_seed();
 
621
 
 
622
    /* Init PJLIB-UTIL: */
 
623
    status = pjlib_util_init();
 
624
    PJ_ASSERT_RETURN(status == PJ_SUCCESS, status);
 
625
 
 
626
    /* Init PJNATH */
 
627
    status = pjnath_init();
 
628
    PJ_ASSERT_RETURN(status == PJ_SUCCESS, status);
 
629
 
 
630
    /* Set default sound device ID */
 
631
    pjsua_var.cap_dev = PJMEDIA_AUD_DEFAULT_CAPTURE_DEV;
 
632
    pjsua_var.play_dev = PJMEDIA_AUD_DEFAULT_PLAYBACK_DEV;
 
633
 
 
634
    /* Init caching pool. */
 
635
    pj_caching_pool_init(&pjsua_var.cp, NULL, 0);
 
636
 
 
637
    /* Create memory pool for application. */
 
638
    pjsua_var.pool = pjsua_pool_create("pjsua", 1000, 1000);
 
639
    
 
640
    PJ_ASSERT_RETURN(pjsua_var.pool, PJ_ENOMEM);
 
641
 
 
642
    /* Create mutex */
 
643
    status = pj_mutex_create_recursive(pjsua_var.pool, "pjsua", 
 
644
                                       &pjsua_var.mutex);
 
645
    if (status != PJ_SUCCESS) {
 
646
        pjsua_perror(THIS_FILE, "Unable to create mutex", status);
 
647
        return status;
 
648
    }
 
649
 
 
650
    /* Must create SIP endpoint to initialize SIP parser. The parser
 
651
     * is needed for example when application needs to call pjsua_verify_url().
 
652
     */
 
653
    status = pjsip_endpt_create(&pjsua_var.cp.factory, 
 
654
                                pj_gethostname()->ptr, 
 
655
                                &pjsua_var.endpt);
 
656
    PJ_ASSERT_RETURN(status == PJ_SUCCESS, status);
 
657
 
 
658
 
 
659
    return PJ_SUCCESS;
 
660
}
 
661
 
 
662
 
 
663
/*
 
664
 * Initialize pjsua with the specified settings. All the settings are 
 
665
 * optional, and the default values will be used when the config is not
 
666
 * specified.
 
667
 */
 
668
PJ_DEF(pj_status_t) pjsua_init( const pjsua_config *ua_cfg,
 
669
                                const pjsua_logging_config *log_cfg,
 
670
                                const pjsua_media_config *media_cfg)
 
671
{
 
672
    pjsua_config         default_cfg;
 
673
    pjsua_media_config   default_media_cfg;
 
674
    const pj_str_t       STR_OPTIONS = { "OPTIONS", 7 };
 
675
    pjsip_ua_init_param  ua_init_param;
 
676
    pj_status_t status;
 
677
 
 
678
 
 
679
    /* Create default configurations when the config is not supplied */
 
680
 
 
681
    if (ua_cfg == NULL) {
 
682
        pjsua_config_default(&default_cfg);
 
683
        ua_cfg = &default_cfg;
 
684
    }
 
685
 
 
686
    if (media_cfg == NULL) {
 
687
        pjsua_media_config_default(&default_media_cfg);
 
688
        media_cfg = &default_media_cfg;
 
689
    }
 
690
 
 
691
    /* Initialize logging first so that info/errors can be captured */
 
692
    if (log_cfg) {
 
693
        status = pjsua_reconfigure_logging(log_cfg);
 
694
        if (status != PJ_SUCCESS)
 
695
            return status;
 
696
    }
 
697
 
 
698
    /* If nameserver is configured, create DNS resolver instance and
 
699
     * set it to be used by SIP resolver.
 
700
     */
 
701
    if (ua_cfg->nameserver_count) {
 
702
#if PJSIP_HAS_RESOLVER
 
703
        unsigned i;
 
704
 
 
705
        /* Create DNS resolver */
 
706
        status = pjsip_endpt_create_resolver(pjsua_var.endpt, 
 
707
                                             &pjsua_var.resolver);
 
708
        if (status != PJ_SUCCESS) {
 
709
            pjsua_perror(THIS_FILE, "Error creating resolver", status);
 
710
            return status;
 
711
        }
 
712
 
 
713
        /* Configure nameserver for the DNS resolver */
 
714
        status = pj_dns_resolver_set_ns(pjsua_var.resolver, 
 
715
                                        ua_cfg->nameserver_count,
 
716
                                        ua_cfg->nameserver, NULL);
 
717
        if (status != PJ_SUCCESS) {
 
718
            pjsua_perror(THIS_FILE, "Error setting nameserver", status);
 
719
            return status;
 
720
        }
 
721
 
 
722
        /* Set this DNS resolver to be used by the SIP resolver */
 
723
        status = pjsip_endpt_set_resolver(pjsua_var.endpt, pjsua_var.resolver);
 
724
        if (status != PJ_SUCCESS) {
 
725
            pjsua_perror(THIS_FILE, "Error setting DNS resolver", status);
 
726
            return status;
 
727
        }
 
728
 
 
729
        /* Print nameservers */
 
730
        for (i=0; i<ua_cfg->nameserver_count; ++i) {
 
731
            PJ_LOG(4,(THIS_FILE, "Nameserver %.*s added",
 
732
                      (int)ua_cfg->nameserver[i].slen,
 
733
                      ua_cfg->nameserver[i].ptr));
 
734
        }
 
735
#else
 
736
        PJ_LOG(2,(THIS_FILE, 
 
737
                  "DNS resolver is disabled (PJSIP_HAS_RESOLVER==0)"));
 
738
#endif
 
739
    }
 
740
 
 
741
    /* Init SIP UA: */
 
742
 
 
743
    /* Initialize transaction layer: */
 
744
    status = pjsip_tsx_layer_init_module(pjsua_var.endpt);
 
745
    PJ_ASSERT_RETURN(status == PJ_SUCCESS, status);
 
746
 
 
747
 
 
748
    /* Initialize UA layer module: */
 
749
    pj_bzero(&ua_init_param, sizeof(ua_init_param));
 
750
    if (ua_cfg->hangup_forked_call) {
 
751
        ua_init_param.on_dlg_forked = &on_dlg_forked;
 
752
    }
 
753
    status = pjsip_ua_init_module( pjsua_var.endpt, &ua_init_param);
 
754
    PJ_ASSERT_RETURN(status == PJ_SUCCESS, status);
 
755
 
 
756
 
 
757
    /* Initialize Replaces support. */
 
758
    status = pjsip_replaces_init_module( pjsua_var.endpt );
 
759
    PJ_ASSERT_RETURN(status == PJ_SUCCESS, status);
 
760
 
 
761
    /* Initialize 100rel support */
 
762
    status = pjsip_100rel_init_module(pjsua_var.endpt);
 
763
    PJ_ASSERT_RETURN(status == PJ_SUCCESS, status);
 
764
 
 
765
    /* Initialize session timer support */
 
766
    status = pjsip_timer_init_module(pjsua_var.endpt);
 
767
    PJ_ASSERT_RETURN(status == PJ_SUCCESS, status);
 
768
 
 
769
    /* Initialize and register PJSUA application module. */
 
770
    {
 
771
        const pjsip_module mod_initializer = 
 
772
        {
 
773
        NULL, NULL,                 /* prev, next.                      */
 
774
        { "mod-pjsua", 9 },         /* Name.                            */
 
775
        -1,                         /* Id                               */
 
776
        PJSIP_MOD_PRIORITY_APPLICATION, /* Priority                     */
 
777
        NULL,                       /* load()                           */
 
778
        NULL,                       /* start()                          */
 
779
        NULL,                       /* stop()                           */
 
780
        NULL,                       /* unload()                         */
 
781
        &mod_pjsua_on_rx_request,   /* on_rx_request()                  */
 
782
        &mod_pjsua_on_rx_response,  /* on_rx_response()                 */
 
783
        NULL,                       /* on_tx_request.                   */
 
784
        NULL,                       /* on_tx_response()                 */
 
785
        NULL,                       /* on_tsx_state()                   */
 
786
        };
 
787
 
 
788
        pjsua_var.mod = mod_initializer;
 
789
 
 
790
        status = pjsip_endpt_register_module(pjsua_var.endpt, &pjsua_var.mod);
 
791
        PJ_ASSERT_RETURN(status == PJ_SUCCESS, status);
 
792
    }
 
793
 
 
794
    
 
795
 
 
796
    /* Initialize PJSUA call subsystem: */
 
797
    status = pjsua_call_subsys_init(ua_cfg);
 
798
    if (status != PJ_SUCCESS)
 
799
        goto on_error;
 
800
 
 
801
    /* Convert deprecated STUN settings */
 
802
    if (pjsua_var.ua_cfg.stun_srv_cnt==0) {
 
803
        if (pjsua_var.ua_cfg.stun_domain.slen) {
 
804
            pjsua_var.ua_cfg.stun_srv[pjsua_var.ua_cfg.stun_srv_cnt++] = 
 
805
                pjsua_var.ua_cfg.stun_domain;
 
806
        }
 
807
        if (pjsua_var.ua_cfg.stun_host.slen) {
 
808
            pjsua_var.ua_cfg.stun_srv[pjsua_var.ua_cfg.stun_srv_cnt++] = 
 
809
                pjsua_var.ua_cfg.stun_host;
 
810
        }
 
811
    }
 
812
 
 
813
    /* Start resolving STUN server */
 
814
    status = resolve_stun_server(PJ_FALSE);
 
815
    if (status != PJ_SUCCESS && status != PJ_EPENDING) {
 
816
        pjsua_perror(THIS_FILE, "Error resolving STUN server", status);
 
817
        return status;
 
818
    }
 
819
 
 
820
    /* Initialize PJSUA media subsystem */
 
821
    status = pjsua_media_subsys_init(media_cfg);
 
822
    if (status != PJ_SUCCESS)
 
823
        goto on_error;
 
824
 
 
825
 
 
826
    /* Init core SIMPLE module : */
 
827
    status = pjsip_evsub_init_module(pjsua_var.endpt);
 
828
    PJ_ASSERT_RETURN(status == PJ_SUCCESS, status);
 
829
 
 
830
 
 
831
    /* Init presence module: */
 
832
    status = pjsip_pres_init_module( pjsua_var.endpt, pjsip_evsub_instance());
 
833
    PJ_ASSERT_RETURN(status == PJ_SUCCESS, status);
 
834
 
 
835
    /* Initialize MWI support */
 
836
    status = pjsip_mwi_init_module(pjsua_var.endpt, pjsip_evsub_instance());
 
837
 
 
838
    /* Init PUBLISH module */
 
839
    pjsip_publishc_init_module(pjsua_var.endpt);
 
840
 
 
841
    /* Init xfer/REFER module */
 
842
    status = pjsip_xfer_init_module( pjsua_var.endpt );
 
843
    PJ_ASSERT_RETURN(status == PJ_SUCCESS, status);
 
844
 
 
845
    /* Init pjsua presence handler: */
 
846
    status = pjsua_pres_init();
 
847
    if (status != PJ_SUCCESS)
 
848
        goto on_error;
 
849
 
 
850
    /* Init out-of-dialog MESSAGE request handler. */
 
851
    status = pjsua_im_init();
 
852
    if (status != PJ_SUCCESS)
 
853
        goto on_error;
 
854
 
 
855
    /* Register OPTIONS handler */
 
856
    pjsip_endpt_register_module(pjsua_var.endpt, &pjsua_options_handler);
 
857
 
 
858
    /* Add OPTIONS in Allow header */
 
859
    pjsip_endpt_add_capability(pjsua_var.endpt, NULL, PJSIP_H_ALLOW,
 
860
                               NULL, 1, &STR_OPTIONS);
 
861
 
 
862
    /* Start worker thread if needed. */
 
863
    if (pjsua_var.ua_cfg.thread_cnt) {
 
864
        unsigned i;
 
865
 
 
866
        if (pjsua_var.ua_cfg.thread_cnt > PJ_ARRAY_SIZE(pjsua_var.thread))
 
867
            pjsua_var.ua_cfg.thread_cnt = PJ_ARRAY_SIZE(pjsua_var.thread);
 
868
 
 
869
        for (i=0; i<pjsua_var.ua_cfg.thread_cnt; ++i) {
 
870
            status = pj_thread_create(pjsua_var.pool, "pjsua", &worker_thread,
 
871
                                      NULL, 0, 0, &pjsua_var.thread[i]);
 
872
            if (status != PJ_SUCCESS)
 
873
                goto on_error;
 
874
        }
 
875
        PJ_LOG(4,(THIS_FILE, "%d SIP worker threads created", 
 
876
                  pjsua_var.ua_cfg.thread_cnt));
 
877
    } else {
 
878
        PJ_LOG(4,(THIS_FILE, "No SIP worker threads created"));
 
879
    }
 
880
 
 
881
    /* Done! */
 
882
 
 
883
    PJ_LOG(3,(THIS_FILE, "pjsua version %s for %s initialized", 
 
884
                         pj_get_version(), PJ_OS_NAME));
 
885
 
 
886
    return PJ_SUCCESS;
 
887
 
 
888
on_error:
 
889
    pjsua_destroy();
 
890
    return status;
 
891
}
 
892
 
 
893
 
 
894
/* Sleep with polling */
 
895
static void busy_sleep(unsigned msec)
 
896
{
 
897
    pj_time_val timeout, now;
 
898
 
 
899
    pj_gettimeofday(&timeout);
 
900
    timeout.msec += msec;
 
901
    pj_time_val_normalize(&timeout);
 
902
 
 
903
    do {
 
904
        int i;
 
905
        i = msec / 10;
 
906
        while (pjsua_handle_events(10) > 0 && i > 0)
 
907
            --i;
 
908
        pj_gettimeofday(&now);
 
909
    } while (PJ_TIME_VAL_LT(now, timeout));
 
910
}
 
911
 
 
912
/* Internal function to destroy STUN resolution session
 
913
 * (pj_stun_resolve).
 
914
 */
 
915
static void destroy_stun_resolve(pjsua_stun_resolve *sess)
 
916
{
 
917
    PJSUA_LOCK();
 
918
    pj_list_erase(sess);
 
919
    PJSUA_UNLOCK();
 
920
 
 
921
    pj_assert(sess->stun_sock==NULL);
 
922
    pj_pool_release(sess->pool);
 
923
}
 
924
 
 
925
/* This is the internal function to be called when STUN resolution
 
926
 * session (pj_stun_resolve) has completed.
 
927
 */
 
928
static void stun_resolve_complete(pjsua_stun_resolve *sess)
 
929
{
 
930
    pj_stun_resolve_result result;
 
931
 
 
932
    pj_bzero(&result, sizeof(result));
 
933
    result.token = sess->token;
 
934
    result.status = sess->status;
 
935
    result.name = sess->srv[sess->idx];
 
936
    pj_memcpy(&result.addr, &sess->addr, sizeof(result.addr));
 
937
 
 
938
    if (result.status == PJ_SUCCESS) {
 
939
        char addr[PJ_INET6_ADDRSTRLEN+10];
 
940
        pj_sockaddr_print(&result.addr, addr, sizeof(addr), 3);
 
941
        PJ_LOG(4,(THIS_FILE, 
 
942
                  "STUN resolution success, using %.*s, address is %s",
 
943
                  (int)sess->srv[sess->idx].slen,
 
944
                  sess->srv[sess->idx].ptr,
 
945
                  addr));
 
946
    } else {
 
947
        char errmsg[PJ_ERR_MSG_SIZE];
 
948
        pj_strerror(result.status, errmsg, sizeof(errmsg));
 
949
        PJ_LOG(1,(THIS_FILE, "STUN resolution failed: %s", errmsg));
 
950
    }
 
951
 
 
952
    sess->cb(&result);
 
953
 
 
954
    if (!sess->blocking) {
 
955
        destroy_stun_resolve(sess);
 
956
    }
 
957
}
 
958
 
 
959
/* This is the callback called by the STUN socket (pj_stun_sock)
 
960
 * to report it's state. We use this as part of testing the
 
961
 * STUN server.
 
962
 */
 
963
static pj_bool_t test_stun_on_status(pj_stun_sock *stun_sock, 
 
964
                                     pj_stun_sock_op op,
 
965
                                     pj_status_t status)
 
966
{
 
967
    pjsua_stun_resolve *sess;
 
968
 
 
969
    sess = (pjsua_stun_resolve*) pj_stun_sock_get_user_data(stun_sock);
 
970
    pj_assert(stun_sock == sess->stun_sock);
 
971
 
 
972
    if (status != PJ_SUCCESS) {
 
973
        char errmsg[PJ_ERR_MSG_SIZE];
 
974
        pj_strerror(status, errmsg, sizeof(errmsg));
 
975
 
 
976
        PJ_LOG(4,(THIS_FILE, "STUN resolution for %.*s failed: %s",
 
977
                  (int)sess->srv[sess->idx].slen,
 
978
                  sess->srv[sess->idx].ptr, errmsg));
 
979
 
 
980
        sess->status = status;
 
981
 
 
982
        pj_stun_sock_destroy(stun_sock);
 
983
        sess->stun_sock = NULL;
 
984
 
 
985
        ++sess->idx;
 
986
        resolve_stun_entry(sess);
 
987
 
 
988
        return PJ_FALSE;
 
989
 
 
990
    } else if (op == PJ_STUN_SOCK_BINDING_OP) {
 
991
        pj_stun_sock_info ssi;
 
992
 
 
993
        pj_stun_sock_get_info(stun_sock, &ssi);
 
994
        pj_memcpy(&sess->addr, &ssi.srv_addr, sizeof(sess->addr));
 
995
 
 
996
        sess->status = PJ_SUCCESS;
 
997
        pj_stun_sock_destroy(stun_sock);
 
998
        sess->stun_sock = NULL;
 
999
 
 
1000
        stun_resolve_complete(sess);
 
1001
 
 
1002
        return PJ_FALSE;
 
1003
 
 
1004
    } else
 
1005
        return PJ_TRUE;
 
1006
    
 
1007
}
 
1008
 
 
1009
/* This is an internal function to resolve and test current
 
1010
 * server entry in pj_stun_resolve session. It is called by
 
1011
 * pjsua_resolve_stun_servers() and test_stun_on_status() above
 
1012
 */
 
1013
static void resolve_stun_entry(pjsua_stun_resolve *sess)
 
1014
{
 
1015
    /* Loop while we have entry to try */
 
1016
    for (; sess->idx < sess->count; ++sess->idx) {
 
1017
        const int af = pj_AF_INET();
 
1018
        pj_str_t hostpart;
 
1019
        pj_uint16_t port;
 
1020
        pj_stun_sock_cb stun_sock_cb;
 
1021
        
 
1022
        pj_assert(sess->idx < sess->count);
 
1023
 
 
1024
        /* Parse the server entry into host:port */
 
1025
        sess->status = pj_sockaddr_parse2(af, 0, &sess->srv[sess->idx],
 
1026
                                          &hostpart, &port, NULL);
 
1027
        if (sess->status != PJ_SUCCESS) {
 
1028
            PJ_LOG(2,(THIS_FILE, "Invalid STUN server entry %.*s", 
 
1029
                      (int)sess->srv[sess->idx].slen, 
 
1030
                      sess->srv[sess->idx].ptr));
 
1031
            continue;
 
1032
        }
 
1033
        
 
1034
        /* Use default port if not specified */
 
1035
        if (port == 0)
 
1036
            port = PJ_STUN_PORT;
 
1037
 
 
1038
        pj_assert(sess->stun_sock == NULL);
 
1039
 
 
1040
        PJ_LOG(4,(THIS_FILE, "Trying STUN server %.*s (%d of %d)..",
 
1041
                  (int)sess->srv[sess->idx].slen,
 
1042
                  sess->srv[sess->idx].ptr,
 
1043
                  sess->idx+1, sess->count));
 
1044
 
 
1045
        /* Use STUN_sock to test this entry */
 
1046
        pj_bzero(&stun_sock_cb, sizeof(stun_sock_cb));
 
1047
        stun_sock_cb.on_status = &test_stun_on_status;
 
1048
        sess->status = pj_stun_sock_create(&pjsua_var.stun_cfg, "stunresolve",
 
1049
                                           pj_AF_INET(), &stun_sock_cb,
 
1050
                                           NULL, sess, &sess->stun_sock);
 
1051
        if (sess->status != PJ_SUCCESS) {
 
1052
            char errmsg[PJ_ERR_MSG_SIZE];
 
1053
            pj_strerror(sess->status, errmsg, sizeof(errmsg));
 
1054
            PJ_LOG(4,(THIS_FILE, 
 
1055
                     "Error creating STUN socket for %.*s: %s",
 
1056
                      (int)sess->srv[sess->idx].slen,
 
1057
                      sess->srv[sess->idx].ptr, errmsg));
 
1058
 
 
1059
            continue;
 
1060
        }
 
1061
 
 
1062
        sess->status = pj_stun_sock_start(sess->stun_sock, &hostpart,
 
1063
                                          port, pjsua_var.resolver);
 
1064
        if (sess->status != PJ_SUCCESS) {
 
1065
            char errmsg[PJ_ERR_MSG_SIZE];
 
1066
            pj_strerror(sess->status, errmsg, sizeof(errmsg));
 
1067
            PJ_LOG(4,(THIS_FILE, 
 
1068
                     "Error starting STUN socket for %.*s: %s",
 
1069
                      (int)sess->srv[sess->idx].slen,
 
1070
                      sess->srv[sess->idx].ptr, errmsg));
 
1071
 
 
1072
            pj_stun_sock_destroy(sess->stun_sock);
 
1073
            sess->stun_sock = NULL;
 
1074
            continue;
 
1075
        }
 
1076
 
 
1077
        /* Done for now, testing will resume/complete asynchronously in
 
1078
         * stun_sock_cb()
 
1079
         */
 
1080
        return;
 
1081
    }
 
1082
 
 
1083
    if (sess->idx >= sess->count) {
 
1084
        /* No more entries to try */
 
1085
        PJ_ASSERT_ON_FAIL(sess->status != PJ_SUCCESS, 
 
1086
                          sess->status = PJ_EUNKNOWN);
 
1087
        stun_resolve_complete(sess);
 
1088
    }
 
1089
}
 
1090
 
 
1091
 
 
1092
/*
 
1093
 * Resolve STUN server.
 
1094
 */
 
1095
PJ_DEF(pj_status_t) pjsua_resolve_stun_servers( unsigned count,
 
1096
                                                pj_str_t srv[],
 
1097
                                                pj_bool_t wait,
 
1098
                                                void *token,
 
1099
                                                pj_stun_resolve_cb cb)
 
1100
{
 
1101
    pj_pool_t *pool;
 
1102
    pjsua_stun_resolve *sess;
 
1103
    pj_status_t status;
 
1104
    unsigned i;
 
1105
 
 
1106
    PJ_ASSERT_RETURN(count && srv && cb, PJ_EINVAL);
 
1107
 
 
1108
    pool = pjsua_pool_create("stunres", 256, 256);
 
1109
    if (!pool)
 
1110
        return PJ_ENOMEM;
 
1111
 
 
1112
    sess = PJ_POOL_ZALLOC_T(pool, pjsua_stun_resolve);
 
1113
    sess->pool = pool;
 
1114
    sess->token = token;
 
1115
    sess->cb = cb;
 
1116
    sess->count = count;
 
1117
    sess->blocking = wait;
 
1118
    sess->status = PJ_EPENDING;
 
1119
    sess->srv = (pj_str_t*) pj_pool_calloc(pool, count, sizeof(pj_str_t));
 
1120
    for (i=0; i<count; ++i) {
 
1121
        pj_strdup(pool, &sess->srv[i], &srv[i]);
 
1122
    }
 
1123
 
 
1124
    PJSUA_LOCK();
 
1125
    pj_list_push_back(&pjsua_var.stun_res, sess);
 
1126
    PJSUA_UNLOCK();
 
1127
 
 
1128
    resolve_stun_entry(sess);
 
1129
 
 
1130
    if (!wait)
 
1131
        return PJ_SUCCESS;
 
1132
 
 
1133
    while (sess->status == PJ_EPENDING) {
 
1134
        pjsua_handle_events(50);
 
1135
    }
 
1136
 
 
1137
    status = sess->status;
 
1138
    destroy_stun_resolve(sess);
 
1139
 
 
1140
    return status;
 
1141
}
 
1142
 
 
1143
/*
 
1144
 * Cancel pending STUN resolution.
 
1145
 */
 
1146
PJ_DEF(pj_status_t) pjsua_cancel_stun_resolution( void *token,
 
1147
                                                  pj_bool_t notify_cb)
 
1148
{
 
1149
    pjsua_stun_resolve *sess;
 
1150
    unsigned cancelled_count = 0;
 
1151
 
 
1152
    PJSUA_LOCK();
 
1153
    sess = pjsua_var.stun_res.next;
 
1154
    while (sess != &pjsua_var.stun_res) {
 
1155
        pjsua_stun_resolve *next = sess->next;
 
1156
 
 
1157
        if (sess->token == token) {
 
1158
            if (notify_cb) {
 
1159
                pj_stun_resolve_result result;
 
1160
 
 
1161
                pj_bzero(&result, sizeof(result));
 
1162
                result.token = token;
 
1163
                result.status = PJ_ECANCELLED;
 
1164
 
 
1165
                sess->cb(&result);
 
1166
            }
 
1167
 
 
1168
            destroy_stun_resolve(sess);
 
1169
            ++cancelled_count;
 
1170
        }
 
1171
 
 
1172
        sess = next;
 
1173
    }
 
1174
    PJSUA_UNLOCK();
 
1175
 
 
1176
    return cancelled_count ? PJ_SUCCESS : PJ_ENOTFOUND;
 
1177
}
 
1178
 
 
1179
static void internal_stun_resolve_cb(const pj_stun_resolve_result *result)
 
1180
{
 
1181
    pjsua_var.stun_status = result->status;
 
1182
    if (result->status == PJ_SUCCESS) {
 
1183
        pj_memcpy(&pjsua_var.stun_srv, &result->addr, sizeof(result->addr));
 
1184
    }
 
1185
}
 
1186
 
 
1187
/*
 
1188
 * Resolve STUN server.
 
1189
 */
 
1190
pj_status_t resolve_stun_server(pj_bool_t wait)
 
1191
{
 
1192
    if (pjsua_var.stun_status == PJ_EUNKNOWN) {
 
1193
        pj_status_t status;
 
1194
 
 
1195
        /* Initialize STUN configuration */
 
1196
        pj_stun_config_init(&pjsua_var.stun_cfg, &pjsua_var.cp.factory, 0,
 
1197
                            pjsip_endpt_get_ioqueue(pjsua_var.endpt),
 
1198
                            pjsip_endpt_get_timer_heap(pjsua_var.endpt));
 
1199
 
 
1200
        /* Start STUN server resolution */
 
1201
        if (pjsua_var.ua_cfg.stun_srv_cnt) {
 
1202
            pjsua_var.stun_status = PJ_EPENDING;
 
1203
            status = pjsua_resolve_stun_servers(pjsua_var.ua_cfg.stun_srv_cnt,
 
1204
                                                pjsua_var.ua_cfg.stun_srv,
 
1205
                                                wait, NULL,
 
1206
                                                &internal_stun_resolve_cb);
 
1207
            if (wait || status != PJ_SUCCESS) {
 
1208
                pjsua_var.stun_status = status;
 
1209
            }
 
1210
        } else {
 
1211
            pjsua_var.stun_status = PJ_SUCCESS;
 
1212
        }
 
1213
 
 
1214
    } else if (pjsua_var.stun_status == PJ_EPENDING) {
 
1215
        /* STUN server resolution has been started, wait for the
 
1216
         * result.
 
1217
         */
 
1218
        if (wait) {
 
1219
            while (pjsua_var.stun_status == PJ_EPENDING)
 
1220
                pjsua_handle_events(10);
 
1221
        }
 
1222
    }
 
1223
 
 
1224
    if (pjsua_var.stun_status != PJ_EPENDING &&
 
1225
        pjsua_var.stun_status != PJ_SUCCESS &&
 
1226
        pjsua_var.ua_cfg.stun_ignore_failure)
 
1227
    {
 
1228
        PJ_LOG(2,(THIS_FILE, 
 
1229
                  "Ignoring STUN resolution failure (by setting)"));
 
1230
        pjsua_var.stun_status = PJ_SUCCESS;
 
1231
    }
 
1232
 
 
1233
    return pjsua_var.stun_status;
 
1234
}
 
1235
 
 
1236
/*
 
1237
 * Destroy pjsua.
 
1238
 */
 
1239
PJ_DEF(pj_status_t) pjsua_destroy(void)
 
1240
{
 
1241
    int i;  /* Must be signed */
 
1242
 
 
1243
    /* Signal threads to quit: */
 
1244
    pjsua_var.thread_quit_flag = 1;
 
1245
 
 
1246
    /* Wait worker threads to quit: */
 
1247
    for (i=0; i<(int)pjsua_var.ua_cfg.thread_cnt; ++i) {
 
1248
        if (pjsua_var.thread[i]) {
 
1249
            pj_thread_join(pjsua_var.thread[i]);
 
1250
            pj_thread_destroy(pjsua_var.thread[i]);
 
1251
            pjsua_var.thread[i] = NULL;
 
1252
        }
 
1253
    }
 
1254
    
 
1255
    if (pjsua_var.endpt) {
 
1256
        unsigned max_wait;
 
1257
 
 
1258
        PJ_LOG(4,(THIS_FILE, "Shutting down..."));
 
1259
 
 
1260
        /* Terminate all calls. */
 
1261
        pjsua_call_hangup_all();
 
1262
 
 
1263
        /* Set all accounts to offline */
 
1264
        for (i=0; i<(int)PJ_ARRAY_SIZE(pjsua_var.acc); ++i) {
 
1265
            if (!pjsua_var.acc[i].valid)
 
1266
                continue;
 
1267
            pjsua_var.acc[i].online_status = PJ_FALSE;
 
1268
            pj_bzero(&pjsua_var.acc[i].rpid, sizeof(pjrpid_element));
 
1269
        }
 
1270
 
 
1271
        /* Terminate all presence subscriptions. */
 
1272
        pjsua_pres_shutdown();
 
1273
 
 
1274
        /* Destroy media (to shutdown media transports etc) */
 
1275
        pjsua_media_subsys_destroy();
 
1276
 
 
1277
        /* Wait for sometime until all publish client sessions are done
 
1278
         * (ticket #364)
 
1279
         */
 
1280
        /* First stage, get the maximum wait time */
 
1281
        max_wait = 100;
 
1282
        for (i=0; i<PJ_ARRAY_SIZE(pjsua_var.acc); ++i) {
 
1283
            if (!pjsua_var.acc[i].valid)
 
1284
                continue;
 
1285
            if (pjsua_var.acc[i].cfg.unpublish_max_wait_time_msec > max_wait)
 
1286
                max_wait = pjsua_var.acc[i].cfg.unpublish_max_wait_time_msec;
 
1287
        }
 
1288
        
 
1289
        /* Second stage, wait for unpublications to complete */
 
1290
        for (i=0; i<(int)(max_wait/50); ++i) {
 
1291
            unsigned j;
 
1292
            for (j=0; j<PJ_ARRAY_SIZE(pjsua_var.acc); ++j) {
 
1293
                if (!pjsua_var.acc[j].valid)
 
1294
                    continue;
 
1295
 
 
1296
                if (pjsua_var.acc[j].publish_sess)
 
1297
                    break;
 
1298
            }
 
1299
            if (j != PJ_ARRAY_SIZE(pjsua_var.acc))
 
1300
                busy_sleep(50);
 
1301
            else
 
1302
                break;
 
1303
        }
 
1304
 
 
1305
        /* Third stage, forcefully destroy unfinished unpublications */
 
1306
        for (i=0; i<PJ_ARRAY_SIZE(pjsua_var.acc); ++i) {
 
1307
            if (pjsua_var.acc[i].publish_sess) {
 
1308
                pjsip_publishc_destroy(pjsua_var.acc[i].publish_sess);
 
1309
                pjsua_var.acc[i].publish_sess = NULL;
 
1310
            }
 
1311
        }
 
1312
 
 
1313
        /* Unregister all accounts */
 
1314
        for (i=0; i<(int)PJ_ARRAY_SIZE(pjsua_var.acc); ++i) {
 
1315
            if (!pjsua_var.acc[i].valid)
 
1316
                continue;
 
1317
 
 
1318
            if (pjsua_var.acc[i].regc) {
 
1319
                pjsua_acc_set_registration(i, PJ_FALSE);
 
1320
            }
 
1321
        }
 
1322
 
 
1323
        /* Terminate any pending STUN resolution */
 
1324
        if (!pj_list_empty(&pjsua_var.stun_res)) {
 
1325
            pjsua_stun_resolve *sess = pjsua_var.stun_res.next;
 
1326
            while (sess != &pjsua_var.stun_res) {
 
1327
                pjsua_stun_resolve *next = sess->next;
 
1328
                destroy_stun_resolve(sess);
 
1329
                sess = next;
 
1330
            }
 
1331
        }
 
1332
 
 
1333
        /* Wait until all unregistrations are done (ticket #364) */
 
1334
        /* First stage, get the maximum wait time */
 
1335
        max_wait = 100;
 
1336
        for (i=0; i<PJ_ARRAY_SIZE(pjsua_var.acc); ++i) {
 
1337
            if (!pjsua_var.acc[i].valid)
 
1338
                continue;
 
1339
            if (pjsua_var.acc[i].cfg.unreg_timeout > max_wait)
 
1340
                max_wait = pjsua_var.acc[i].cfg.unreg_timeout;
 
1341
        }
 
1342
        
 
1343
        /* Second stage, wait for unregistrations to complete */
 
1344
        for (i=0; i<(int)(max_wait/50); ++i) {
 
1345
            unsigned j;
 
1346
            for (j=0; j<PJ_ARRAY_SIZE(pjsua_var.acc); ++j) {
 
1347
                if (!pjsua_var.acc[j].valid)
 
1348
                    continue;
 
1349
 
 
1350
                if (pjsua_var.acc[j].regc)
 
1351
                    break;
 
1352
            }
 
1353
            if (j != PJ_ARRAY_SIZE(pjsua_var.acc))
 
1354
                busy_sleep(50);
 
1355
            else
 
1356
                break;
 
1357
        }
 
1358
        /* Note variable 'i' is used below */
 
1359
 
 
1360
        /* Wait for some time to allow unregistration and ICE/TURN
 
1361
         * transports shutdown to complete: 
 
1362
         */
 
1363
        if (i < 20)
 
1364
            busy_sleep(1000 - i*50);
 
1365
 
 
1366
        PJ_LOG(4,(THIS_FILE, "Destroying..."));
 
1367
 
 
1368
        /* Must destroy endpoint first before destroying pools in
 
1369
         * buddies or accounts, since shutting down transaction layer
 
1370
         * may emit events which trigger some buddy or account callbacks
 
1371
         * to be called.
 
1372
         */
 
1373
        pjsip_endpt_destroy(pjsua_var.endpt);
 
1374
        pjsua_var.endpt = NULL;
 
1375
 
 
1376
        /* Destroy pool in the buddy object */
 
1377
        for (i=0; i<(int)PJ_ARRAY_SIZE(pjsua_var.buddy); ++i) {
 
1378
            if (pjsua_var.buddy[i].pool) {
 
1379
                pj_pool_release(pjsua_var.buddy[i].pool);
 
1380
                pjsua_var.buddy[i].pool = NULL;
 
1381
            }
 
1382
        }
 
1383
 
 
1384
        /* Destroy accounts */
 
1385
        for (i=0; i<(int)PJ_ARRAY_SIZE(pjsua_var.acc); ++i) {
 
1386
            if (pjsua_var.acc[i].pool) {
 
1387
                pj_pool_release(pjsua_var.acc[i].pool);
 
1388
                pjsua_var.acc[i].pool = NULL;
 
1389
            }
 
1390
        }
 
1391
    }
 
1392
 
 
1393
    /* Destroy mutex */
 
1394
    if (pjsua_var.mutex) {
 
1395
        pj_mutex_destroy(pjsua_var.mutex);
 
1396
        pjsua_var.mutex = NULL;
 
1397
    }
 
1398
 
 
1399
    /* Destroy pool and pool factory. */
 
1400
    if (pjsua_var.pool) {
 
1401
        pj_pool_release(pjsua_var.pool);
 
1402
        pjsua_var.pool = NULL;
 
1403
        pj_caching_pool_destroy(&pjsua_var.cp);
 
1404
 
 
1405
        PJ_LOG(4,(THIS_FILE, "PJSUA destroyed..."));
 
1406
 
 
1407
        /* End logging */
 
1408
        if (pjsua_var.log_file) {
 
1409
            pj_file_close(pjsua_var.log_file);
 
1410
            pjsua_var.log_file = NULL;
 
1411
        }
 
1412
 
 
1413
        /* Shutdown PJLIB */
 
1414
        pj_shutdown();
 
1415
    }
 
1416
 
 
1417
    /* Clear pjsua_var */
 
1418
    pj_bzero(&pjsua_var, sizeof(pjsua_var));
 
1419
 
 
1420
    /* Done. */
 
1421
    return PJ_SUCCESS;
 
1422
}
 
1423
 
 
1424
 
 
1425
/**
 
1426
 * Application is recommended to call this function after all initialization
 
1427
 * is done, so that the library can do additional checking set up
 
1428
 * additional 
 
1429
 *
 
1430
 * @return              PJ_SUCCESS on success, or the appropriate error code.
 
1431
 */
 
1432
PJ_DEF(pj_status_t) pjsua_start(void)
 
1433
{
 
1434
    pj_status_t status;
 
1435
 
 
1436
    status = pjsua_call_subsys_start();
 
1437
    if (status != PJ_SUCCESS)
 
1438
        return status;
 
1439
 
 
1440
    status = pjsua_media_subsys_start();
 
1441
    if (status != PJ_SUCCESS)
 
1442
        return status;
 
1443
 
 
1444
    status = pjsua_pres_start();
 
1445
    if (status != PJ_SUCCESS)
 
1446
        return status;
 
1447
 
 
1448
    return PJ_SUCCESS;
 
1449
}
 
1450
 
 
1451
 
 
1452
/**
 
1453
 * Poll pjsua for events, and if necessary block the caller thread for
 
1454
 * the specified maximum interval (in miliseconds).
 
1455
 */
 
1456
PJ_DEF(int) pjsua_handle_events(unsigned msec_timeout)
 
1457
{
 
1458
#if defined(PJ_SYMBIAN) && PJ_SYMBIAN != 0
 
1459
 
 
1460
    return pj_symbianos_poll(-1, msec_timeout);
 
1461
 
 
1462
#else
 
1463
 
 
1464
    unsigned count = 0;
 
1465
    pj_time_val tv;
 
1466
    pj_status_t status;
 
1467
 
 
1468
    tv.sec = 0;
 
1469
    tv.msec = msec_timeout;
 
1470
    pj_time_val_normalize(&tv);
 
1471
 
 
1472
    status = pjsip_endpt_handle_events2(pjsua_var.endpt, &tv, &count);
 
1473
 
 
1474
    if (status != PJ_SUCCESS)
 
1475
        return -status;
 
1476
 
 
1477
    return count;
 
1478
    
 
1479
#endif
 
1480
}
 
1481
 
 
1482
 
 
1483
/*
 
1484
 * Create memory pool.
 
1485
 */
 
1486
PJ_DEF(pj_pool_t*) pjsua_pool_create( const char *name, pj_size_t init_size,
 
1487
                                      pj_size_t increment)
 
1488
{
 
1489
    /* Pool factory is thread safe, no need to lock */
 
1490
    return pj_pool_create(&pjsua_var.cp.factory, name, init_size, increment, 
 
1491
                          NULL);
 
1492
}
 
1493
 
 
1494
 
 
1495
/*
 
1496
 * Internal function to get SIP endpoint instance of pjsua, which is
 
1497
 * needed for example to register module, create transports, etc.
 
1498
 * Probably is only valid after #pjsua_init() is called.
 
1499
 */
 
1500
PJ_DEF(pjsip_endpoint*) pjsua_get_pjsip_endpt(void)
 
1501
{
 
1502
    return pjsua_var.endpt;
 
1503
}
 
1504
 
 
1505
/*
 
1506
 * Internal function to get media endpoint instance.
 
1507
 * Only valid after #pjsua_init() is called.
 
1508
 */
 
1509
PJ_DEF(pjmedia_endpt*) pjsua_get_pjmedia_endpt(void)
 
1510
{
 
1511
    return pjsua_var.med_endpt;
 
1512
}
 
1513
 
 
1514
/*
 
1515
 * Internal function to get PJSUA pool factory.
 
1516
 */
 
1517
PJ_DEF(pj_pool_factory*) pjsua_get_pool_factory(void)
 
1518
{
 
1519
    return &pjsua_var.cp.factory;
 
1520
}
 
1521
 
 
1522
/*****************************************************************************
 
1523
 * PJSUA SIP Transport API.
 
1524
 */
 
1525
 
 
1526
/*
 
1527
 * Tools to get address string.
 
1528
 */
 
1529
static const char *addr_string(const pj_sockaddr_t *addr)
 
1530
{
 
1531
    static char str[128];
 
1532
    str[0] = '\0';
 
1533
    pj_inet_ntop(((const pj_sockaddr*)addr)->addr.sa_family, 
 
1534
                 pj_sockaddr_get_addr(addr),
 
1535
                 str, sizeof(str));
 
1536
    return str;
 
1537
}
 
1538
 
 
1539
/*
 
1540
 * Create and initialize SIP socket (and possibly resolve public
 
1541
 * address via STUN, depending on config).
 
1542
 */
 
1543
static pj_status_t create_sip_udp_sock(int af,
 
1544
                                       const pjsua_transport_config *cfg,
 
1545
                                       pj_sock_t *p_sock,
 
1546
                                       pj_sockaddr *p_pub_addr)
 
1547
{
 
1548
    char stun_ip_addr[PJ_INET6_ADDRSTRLEN];
 
1549
    unsigned port = cfg->port;
 
1550
    pj_str_t stun_srv;
 
1551
    pj_sock_t sock;
 
1552
    pj_sockaddr bind_addr;
 
1553
    pj_status_t status;
 
1554
 
 
1555
    /* Make sure STUN server resolution has completed */
 
1556
    status = resolve_stun_server(PJ_TRUE);
 
1557
    if (status != PJ_SUCCESS) {
 
1558
        pjsua_perror(THIS_FILE, "Error resolving STUN server", status);
 
1559
        return status;
 
1560
    }
 
1561
 
 
1562
    /* Initialize bound address */
 
1563
    if (cfg->bound_addr.slen) {
 
1564
        status = pj_sockaddr_init(af, &bind_addr, &cfg->bound_addr, 
 
1565
                                  (pj_uint16_t)port);
 
1566
        if (status != PJ_SUCCESS) {
 
1567
            pjsua_perror(THIS_FILE, 
 
1568
                         "Unable to resolve transport bound address", 
 
1569
                         status);
 
1570
            return status;
 
1571
        }
 
1572
    } else {
 
1573
        pj_sockaddr_init(af, &bind_addr, NULL, (pj_uint16_t)port);
 
1574
    }
 
1575
 
 
1576
    /* Create socket */
 
1577
    status = pj_sock_socket(af, pj_SOCK_DGRAM(), 0, &sock);
 
1578
    if (status != PJ_SUCCESS) {
 
1579
        pjsua_perror(THIS_FILE, "socket() error", status);
 
1580
        return status;
 
1581
    }
 
1582
 
 
1583
    /* Apply QoS, if specified */
 
1584
    status = pj_sock_apply_qos2(sock, cfg->qos_type, 
 
1585
                                &cfg->qos_params, 
 
1586
                                2, THIS_FILE, "SIP UDP socket");
 
1587
 
 
1588
    /* Bind socket */
 
1589
    status = pj_sock_bind(sock, &bind_addr, pj_sockaddr_get_len(&bind_addr));
 
1590
    if (status != PJ_SUCCESS) {
 
1591
        pjsua_perror(THIS_FILE, "bind() error", status);
 
1592
        pj_sock_close(sock);
 
1593
        return status;
 
1594
    }
 
1595
 
 
1596
    /* If port is zero, get the bound port */
 
1597
    if (port == 0) {
 
1598
        pj_sockaddr bound_addr;
 
1599
        int namelen = sizeof(bound_addr);
 
1600
        status = pj_sock_getsockname(sock, &bound_addr, &namelen);
 
1601
        if (status != PJ_SUCCESS) {
 
1602
            pjsua_perror(THIS_FILE, "getsockname() error", status);
 
1603
            pj_sock_close(sock);
 
1604
            return status;
 
1605
        }
 
1606
 
 
1607
        port = pj_sockaddr_get_port(&bound_addr);
 
1608
    }
 
1609
 
 
1610
    if (pjsua_var.stun_srv.addr.sa_family != 0) {
 
1611
        pj_ansi_strcpy(stun_ip_addr,pj_inet_ntoa(pjsua_var.stun_srv.ipv4.sin_addr));
 
1612
        stun_srv = pj_str(stun_ip_addr);
 
1613
    } else {
 
1614
        stun_srv.slen = 0;
 
1615
    }
 
1616
 
 
1617
    /* Get the published address, either by STUN or by resolving
 
1618
     * the name of local host.
 
1619
     */
 
1620
    if (pj_sockaddr_has_addr(p_pub_addr)) {
 
1621
        /*
 
1622
         * Public address is already specified, no need to resolve the 
 
1623
         * address, only set the port.
 
1624
         */
 
1625
        if (pj_sockaddr_get_port(p_pub_addr) == 0)
 
1626
            pj_sockaddr_set_port(p_pub_addr, (pj_uint16_t)port);
 
1627
 
 
1628
    } else if (stun_srv.slen) {
 
1629
        /*
 
1630
         * STUN is specified, resolve the address with STUN.
 
1631
         */
 
1632
        if (af != pj_AF_INET()) {
 
1633
            pjsua_perror(THIS_FILE, "Cannot use STUN", PJ_EAFNOTSUP);
 
1634
            pj_sock_close(sock);
 
1635
            return PJ_EAFNOTSUP;
 
1636
        }
 
1637
 
 
1638
        status = pjstun_get_mapped_addr(&pjsua_var.cp.factory, 1, &sock,
 
1639
                                         &stun_srv, pj_ntohs(pjsua_var.stun_srv.ipv4.sin_port),
 
1640
                                         &stun_srv, pj_ntohs(pjsua_var.stun_srv.ipv4.sin_port),
 
1641
                                         &p_pub_addr->ipv4);
 
1642
        if (status != PJ_SUCCESS) {
 
1643
            pjsua_perror(THIS_FILE, "Error contacting STUN server", status);
 
1644
            pj_sock_close(sock);
 
1645
            return status;
 
1646
        }
 
1647
 
 
1648
    } else {
 
1649
        pj_bzero(p_pub_addr, sizeof(pj_sockaddr));
 
1650
 
 
1651
        if (pj_sockaddr_has_addr(&bind_addr)) {
 
1652
            pj_sockaddr_copy_addr(p_pub_addr, &bind_addr);
 
1653
        } else {
 
1654
            status = pj_gethostip(af, p_pub_addr);
 
1655
            if (status != PJ_SUCCESS) {
 
1656
                pjsua_perror(THIS_FILE, "Unable to get local host IP", status);
 
1657
                pj_sock_close(sock);
 
1658
                return status;
 
1659
            }
 
1660
        }
 
1661
 
 
1662
        p_pub_addr->addr.sa_family = (pj_uint16_t)af;
 
1663
        pj_sockaddr_set_port(p_pub_addr, (pj_uint16_t)port);
 
1664
    }
 
1665
 
 
1666
    *p_sock = sock;
 
1667
 
 
1668
    PJ_LOG(4,(THIS_FILE, "SIP UDP socket reachable at %s:%d",
 
1669
              addr_string(p_pub_addr),
 
1670
              (int)pj_sockaddr_get_port(p_pub_addr)));
 
1671
 
 
1672
    return PJ_SUCCESS;
 
1673
}
 
1674
 
 
1675
 
 
1676
/*
 
1677
 * Create SIP transport.
 
1678
 */
 
1679
PJ_DEF(pj_status_t) pjsua_transport_create( pjsip_transport_type_e type,
 
1680
                                            const pjsua_transport_config *cfg,
 
1681
                                            pjsua_transport_id *p_id)
 
1682
{
 
1683
    pjsip_transport *tp;
 
1684
    unsigned id;
 
1685
    pj_status_t status;
 
1686
 
 
1687
    PJSUA_LOCK();
 
1688
 
 
1689
    /* Find empty transport slot */
 
1690
    for (id=0; id < PJ_ARRAY_SIZE(pjsua_var.tpdata); ++id) {
 
1691
        if (pjsua_var.tpdata[id].data.ptr == NULL)
 
1692
            break;
 
1693
    }
 
1694
 
 
1695
    if (id == PJ_ARRAY_SIZE(pjsua_var.tpdata)) {
 
1696
        status = PJ_ETOOMANY;
 
1697
        pjsua_perror(THIS_FILE, "Error creating transport", status);
 
1698
        goto on_return;
 
1699
    }
 
1700
 
 
1701
    /* Create the transport */
 
1702
    if (type==PJSIP_TRANSPORT_UDP || type==PJSIP_TRANSPORT_UDP6) {
 
1703
        /*
 
1704
         * Create UDP transport (IPv4 or IPv6).
 
1705
         */
 
1706
        pjsua_transport_config config;
 
1707
        char hostbuf[PJ_INET6_ADDRSTRLEN];
 
1708
        pj_sock_t sock = PJ_INVALID_SOCKET;
 
1709
        pj_sockaddr pub_addr;
 
1710
        pjsip_host_port addr_name;
 
1711
 
 
1712
        /* Supply default config if it's not specified */
 
1713
        if (cfg == NULL) {
 
1714
            pjsua_transport_config_default(&config);
 
1715
            cfg = &config;
 
1716
        }
 
1717
 
 
1718
        /* Initialize the public address from the config, if any */
 
1719
        pj_sockaddr_init(pjsip_transport_type_get_af(type), &pub_addr, 
 
1720
                         NULL, (pj_uint16_t)cfg->port);
 
1721
        if (cfg->public_addr.slen) {
 
1722
            status = pj_sockaddr_set_str_addr(pjsip_transport_type_get_af(type),
 
1723
                                              &pub_addr, &cfg->public_addr);
 
1724
            if (status != PJ_SUCCESS) {
 
1725
                pjsua_perror(THIS_FILE, 
 
1726
                             "Unable to resolve transport public address", 
 
1727
                             status);
 
1728
                goto on_return;
 
1729
            }
 
1730
        }
 
1731
 
 
1732
        /* Create the socket and possibly resolve the address with STUN 
 
1733
         * (only when public address is not specified).
 
1734
         */
 
1735
        status = create_sip_udp_sock(pjsip_transport_type_get_af(type),
 
1736
                                     cfg, &sock, &pub_addr);
 
1737
        if (status != PJ_SUCCESS)
 
1738
            goto on_return;
 
1739
 
 
1740
        pj_ansi_strcpy(hostbuf, addr_string(&pub_addr));
 
1741
        addr_name.host = pj_str(hostbuf);
 
1742
        addr_name.port = pj_sockaddr_get_port(&pub_addr);
 
1743
 
 
1744
        /* Create UDP transport */
 
1745
        status = pjsip_udp_transport_attach2(pjsua_var.endpt, type, sock,
 
1746
                                             &addr_name, 1, &tp);
 
1747
        if (status != PJ_SUCCESS) {
 
1748
            pjsua_perror(THIS_FILE, "Error creating SIP UDP transport", 
 
1749
                         status);
 
1750
            pj_sock_close(sock);
 
1751
            goto on_return;
 
1752
        }
 
1753
 
 
1754
 
 
1755
        /* Save the transport */
 
1756
        pjsua_var.tpdata[id].type = type;
 
1757
        pjsua_var.tpdata[id].local_name = tp->local_name;
 
1758
        pjsua_var.tpdata[id].data.tp = tp;
 
1759
 
 
1760
#if defined(PJ_HAS_TCP) && PJ_HAS_TCP!=0
 
1761
 
 
1762
    } else if (type == PJSIP_TRANSPORT_TCP || type == PJSIP_TRANSPORT_TCP6) {
 
1763
        /*
 
1764
         * Create TCP transport.
 
1765
         */
 
1766
        pjsua_transport_config config;
 
1767
        pjsip_tpfactory *tcp;
 
1768
        pjsip_tcp_transport_cfg tcp_cfg;
 
1769
 
 
1770
        pjsip_tcp_transport_cfg_default(&tcp_cfg, pj_AF_INET());
 
1771
 
 
1772
        /* Supply default config if it's not specified */
 
1773
        if (cfg == NULL) {
 
1774
            pjsua_transport_config_default(&config);
 
1775
            cfg = &config;
 
1776
        }
 
1777
 
 
1778
        /* Configure bind address */
 
1779
        if (cfg->port)
 
1780
            pj_sockaddr_set_port(&tcp_cfg.bind_addr, (pj_uint16_t)cfg->port);
 
1781
 
 
1782
        if (cfg->bound_addr.slen) {
 
1783
            status = pj_sockaddr_set_str_addr(tcp_cfg.af, 
 
1784
                                              &tcp_cfg.bind_addr,
 
1785
                                              &cfg->bound_addr);
 
1786
            if (status != PJ_SUCCESS) {
 
1787
                pjsua_perror(THIS_FILE, 
 
1788
                             "Unable to resolve transport bound address", 
 
1789
                             status);
 
1790
                goto on_return;
 
1791
            }
 
1792
        }
 
1793
 
 
1794
        /* Set published name */
 
1795
        if (cfg->public_addr.slen)
 
1796
            tcp_cfg.addr_name.host = cfg->public_addr;
 
1797
 
 
1798
        /* Copy the QoS settings */
 
1799
        tcp_cfg.qos_type = cfg->qos_type;
 
1800
        pj_memcpy(&tcp_cfg.qos_params, &cfg->qos_params, 
 
1801
                  sizeof(cfg->qos_params));
 
1802
 
 
1803
        /* Create the TCP transport */
 
1804
        status = pjsip_tcp_transport_start3(pjsua_var.endpt, &tcp_cfg, &tcp);
 
1805
 
 
1806
        if (status != PJ_SUCCESS) {
 
1807
            pjsua_perror(THIS_FILE, "Error creating SIP TCP listener", 
 
1808
                         status);
 
1809
            goto on_return;
 
1810
        }
 
1811
 
 
1812
        /* Save the transport */
 
1813
        pjsua_var.tpdata[id].type = type;
 
1814
        pjsua_var.tpdata[id].local_name = tcp->addr_name;
 
1815
        pjsua_var.tpdata[id].data.factory = tcp;
 
1816
 
 
1817
#endif  /* PJ_HAS_TCP */
 
1818
 
 
1819
#if defined(PJSIP_HAS_TLS_TRANSPORT) && PJSIP_HAS_TLS_TRANSPORT!=0
 
1820
    } else if (type == PJSIP_TRANSPORT_TLS) {
 
1821
        /*
 
1822
         * Create TLS transport.
 
1823
         */
 
1824
        /*
 
1825
         * Create TCP transport.
 
1826
         */
 
1827
        pjsua_transport_config config;
 
1828
        pjsip_host_port a_name;
 
1829
        pjsip_tpfactory *tls;
 
1830
        pj_sockaddr_in local_addr;
 
1831
 
 
1832
        /* Supply default config if it's not specified */
 
1833
        if (cfg == NULL) {
 
1834
            pjsua_transport_config_default(&config);
 
1835
            config.port = 5061;
 
1836
            cfg = &config;
 
1837
        }
 
1838
 
 
1839
        /* Init local address */
 
1840
        pj_sockaddr_in_init(&local_addr, 0, 0);
 
1841
 
 
1842
        if (cfg->port)
 
1843
            local_addr.sin_port = pj_htons((pj_uint16_t)cfg->port);
 
1844
 
 
1845
        if (cfg->bound_addr.slen) {
 
1846
            status = pj_sockaddr_in_set_str_addr(&local_addr,&cfg->bound_addr);
 
1847
            if (status != PJ_SUCCESS) {
 
1848
                pjsua_perror(THIS_FILE, 
 
1849
                             "Unable to resolve transport bound address", 
 
1850
                             status);
 
1851
                goto on_return;
 
1852
            }
 
1853
        }
 
1854
 
 
1855
        /* Init published name */
 
1856
        pj_bzero(&a_name, sizeof(pjsip_host_port));
 
1857
        if (cfg->public_addr.slen)
 
1858
            a_name.host = cfg->public_addr;
 
1859
 
 
1860
        status = pjsip_tls_transport_start(pjsua_var.endpt, 
 
1861
                                           &cfg->tls_setting, 
 
1862
                                           &local_addr, &a_name, 1, &tls);
 
1863
        if (status != PJ_SUCCESS) {
 
1864
            pjsua_perror(THIS_FILE, "Error creating SIP TLS listener", 
 
1865
                         status);
 
1866
            goto on_return;
 
1867
        }
 
1868
 
 
1869
        /* Save the transport */
 
1870
        pjsua_var.tpdata[id].type = type;
 
1871
        pjsua_var.tpdata[id].local_name = tls->addr_name;
 
1872
        pjsua_var.tpdata[id].data.factory = tls;
 
1873
#endif
 
1874
 
 
1875
    } else {
 
1876
        status = PJSIP_EUNSUPTRANSPORT;
 
1877
        pjsua_perror(THIS_FILE, "Error creating transport", status);
 
1878
        goto on_return;
 
1879
    }
 
1880
 
 
1881
 
 
1882
    /* Return the ID */
 
1883
    if (p_id) *p_id = id;
 
1884
 
 
1885
    status = PJ_SUCCESS;
 
1886
 
 
1887
on_return:
 
1888
 
 
1889
    PJSUA_UNLOCK();
 
1890
 
 
1891
    return status;
 
1892
}
 
1893
 
 
1894
 
 
1895
/*
 
1896
 * Register transport that has been created by application.
 
1897
 */
 
1898
PJ_DEF(pj_status_t) pjsua_transport_register( pjsip_transport *tp,
 
1899
                                              pjsua_transport_id *p_id)
 
1900
{
 
1901
    unsigned id;
 
1902
 
 
1903
    PJSUA_LOCK();
 
1904
 
 
1905
    /* Find empty transport slot */
 
1906
    for (id=0; id < PJ_ARRAY_SIZE(pjsua_var.tpdata); ++id) {
 
1907
        if (pjsua_var.tpdata[id].data.ptr == NULL)
 
1908
            break;
 
1909
    }
 
1910
 
 
1911
    if (id == PJ_ARRAY_SIZE(pjsua_var.tpdata)) {
 
1912
        pjsua_perror(THIS_FILE, "Error creating transport", PJ_ETOOMANY);
 
1913
        PJSUA_UNLOCK();
 
1914
        return PJ_ETOOMANY;
 
1915
    }
 
1916
 
 
1917
    /* Save the transport */
 
1918
    pjsua_var.tpdata[id].type = (pjsip_transport_type_e) tp->key.type;
 
1919
    pjsua_var.tpdata[id].local_name = tp->local_name;
 
1920
    pjsua_var.tpdata[id].data.tp = tp;
 
1921
 
 
1922
    /* Return the ID */
 
1923
    if (p_id) *p_id = id;
 
1924
 
 
1925
    PJSUA_UNLOCK();
 
1926
 
 
1927
    return PJ_SUCCESS;
 
1928
}
 
1929
 
 
1930
 
 
1931
/*
 
1932
 * Enumerate all transports currently created in the system.
 
1933
 */
 
1934
PJ_DEF(pj_status_t) pjsua_enum_transports( pjsua_transport_id id[],
 
1935
                                           unsigned *p_count )
 
1936
{
 
1937
    unsigned i, count;
 
1938
 
 
1939
    PJSUA_LOCK();
 
1940
 
 
1941
    for (i=0, count=0; i<PJ_ARRAY_SIZE(pjsua_var.tpdata) && count<*p_count; 
 
1942
         ++i) 
 
1943
    {
 
1944
        if (!pjsua_var.tpdata[i].data.ptr)
 
1945
            continue;
 
1946
 
 
1947
        id[count++] = i;
 
1948
    }
 
1949
 
 
1950
    *p_count = count;
 
1951
 
 
1952
    PJSUA_UNLOCK();
 
1953
 
 
1954
    return PJ_SUCCESS;
 
1955
}
 
1956
 
 
1957
 
 
1958
/*
 
1959
 * Get information about transports.
 
1960
 */
 
1961
PJ_DEF(pj_status_t) pjsua_transport_get_info( pjsua_transport_id id,
 
1962
                                              pjsua_transport_info *info)
 
1963
{
 
1964
    pjsua_transport_data *t = &pjsua_var.tpdata[id];
 
1965
    pj_status_t status;
 
1966
 
 
1967
    pj_bzero(info, sizeof(*info));
 
1968
 
 
1969
    /* Make sure id is in range. */
 
1970
    PJ_ASSERT_RETURN(id>=0 && id<(int)PJ_ARRAY_SIZE(pjsua_var.tpdata), 
 
1971
                     PJ_EINVAL);
 
1972
 
 
1973
    /* Make sure that transport exists */
 
1974
    PJ_ASSERT_RETURN(pjsua_var.tpdata[id].data.ptr != NULL, PJ_EINVAL);
 
1975
 
 
1976
    PJSUA_LOCK();
 
1977
 
 
1978
    if (pjsua_var.tpdata[id].type == PJSIP_TRANSPORT_UDP) {
 
1979
 
 
1980
        pjsip_transport *tp = t->data.tp;
 
1981
 
 
1982
        if (tp == NULL) {
 
1983
            PJSUA_UNLOCK();
 
1984
            return PJ_EINVALIDOP;
 
1985
        }
 
1986
    
 
1987
        info->id = id;
 
1988
        info->type = (pjsip_transport_type_e) tp->key.type;
 
1989
        info->type_name = pj_str(tp->type_name);
 
1990
        info->info = pj_str(tp->info);
 
1991
        info->flag = tp->flag;
 
1992
        info->addr_len = tp->addr_len;
 
1993
        info->local_addr = tp->local_addr;
 
1994
        info->local_name = tp->local_name;
 
1995
        info->usage_count = pj_atomic_get(tp->ref_cnt);
 
1996
 
 
1997
        status = PJ_SUCCESS;
 
1998
 
 
1999
    } else if (pjsua_var.tpdata[id].type == PJSIP_TRANSPORT_TCP) {
 
2000
 
 
2001
        pjsip_tpfactory *factory = t->data.factory;
 
2002
 
 
2003
        if (factory == NULL) {
 
2004
            PJSUA_UNLOCK();
 
2005
            return PJ_EINVALIDOP;
 
2006
        }
 
2007
    
 
2008
        info->id = id;
 
2009
        info->type = t->type;
 
2010
        info->type_name = pj_str("TCP");
 
2011
        info->info = pj_str("TCP transport");
 
2012
        info->flag = factory->flag;
 
2013
        info->addr_len = sizeof(factory->local_addr);
 
2014
        info->local_addr = factory->local_addr;
 
2015
        info->local_name = factory->addr_name;
 
2016
        info->usage_count = 0;
 
2017
 
 
2018
        status = PJ_SUCCESS;
 
2019
 
 
2020
    } else {
 
2021
        pj_assert(!"Unsupported transport");
 
2022
        status = PJ_EINVALIDOP;
 
2023
    }
 
2024
 
 
2025
 
 
2026
    PJSUA_UNLOCK();
 
2027
 
 
2028
    return status;
 
2029
}
 
2030
 
 
2031
 
 
2032
/*
 
2033
 * Disable a transport or re-enable it.
 
2034
 */
 
2035
PJ_DEF(pj_status_t) pjsua_transport_set_enable( pjsua_transport_id id,
 
2036
                                                pj_bool_t enabled)
 
2037
{
 
2038
    /* Make sure id is in range. */
 
2039
    PJ_ASSERT_RETURN(id>=0 && id<(int)PJ_ARRAY_SIZE(pjsua_var.tpdata), 
 
2040
                     PJ_EINVAL);
 
2041
 
 
2042
    /* Make sure that transport exists */
 
2043
    PJ_ASSERT_RETURN(pjsua_var.tpdata[id].data.ptr != NULL, PJ_EINVAL);
 
2044
 
 
2045
 
 
2046
    /* To be done!! */
 
2047
    PJ_TODO(pjsua_transport_set_enable);
 
2048
    PJ_UNUSED_ARG(enabled);
 
2049
 
 
2050
    return PJ_EINVALIDOP;
 
2051
}
 
2052
 
 
2053
 
 
2054
/*
 
2055
 * Close the transport.
 
2056
 */
 
2057
PJ_DEF(pj_status_t) pjsua_transport_close( pjsua_transport_id id,
 
2058
                                           pj_bool_t force )
 
2059
{
 
2060
    pj_status_t status;
 
2061
 
 
2062
    /* Make sure id is in range. */
 
2063
    PJ_ASSERT_RETURN(id>=0 && id<(int)PJ_ARRAY_SIZE(pjsua_var.tpdata), 
 
2064
                     PJ_EINVAL);
 
2065
 
 
2066
    /* Make sure that transport exists */
 
2067
    PJ_ASSERT_RETURN(pjsua_var.tpdata[id].data.ptr != NULL, PJ_EINVAL);
 
2068
 
 
2069
    /* Note: destroy() may not work if there are objects still referencing
 
2070
     *       the transport.
 
2071
     */
 
2072
    if (force) {
 
2073
        switch (pjsua_var.tpdata[id].type) {
 
2074
        case PJSIP_TRANSPORT_UDP:
 
2075
            status = pjsip_transport_shutdown(pjsua_var.tpdata[id].data.tp);
 
2076
            if (status  != PJ_SUCCESS)
 
2077
                return status;
 
2078
            status = pjsip_transport_destroy(pjsua_var.tpdata[id].data.tp);
 
2079
            if (status != PJ_SUCCESS)
 
2080
                return status;
 
2081
            break;
 
2082
 
 
2083
        case PJSIP_TRANSPORT_TLS:
 
2084
        case PJSIP_TRANSPORT_TCP:
 
2085
            /* This will close the TCP listener, but existing TCP/TLS
 
2086
             * connections (if any) will still linger 
 
2087
             */
 
2088
            status = (*pjsua_var.tpdata[id].data.factory->destroy)
 
2089
                        (pjsua_var.tpdata[id].data.factory);
 
2090
            if (status != PJ_SUCCESS)
 
2091
                return status;
 
2092
 
 
2093
            break;
 
2094
 
 
2095
        default:
 
2096
            return PJ_EINVAL;
 
2097
        }
 
2098
        
 
2099
    } else {
 
2100
        /* If force is not specified, transports will be closed at their
 
2101
         * convenient time. However this will leak PJSUA-API transport
 
2102
         * descriptors as PJSUA-API wouldn't know when exactly the
 
2103
         * transport is closed thus it can't cleanup PJSUA transport
 
2104
         * descriptor.
 
2105
         */
 
2106
        switch (pjsua_var.tpdata[id].type) {
 
2107
        case PJSIP_TRANSPORT_UDP:
 
2108
            return pjsip_transport_shutdown(pjsua_var.tpdata[id].data.tp);
 
2109
        case PJSIP_TRANSPORT_TLS:
 
2110
        case PJSIP_TRANSPORT_TCP:
 
2111
            return (*pjsua_var.tpdata[id].data.factory->destroy)
 
2112
                        (pjsua_var.tpdata[id].data.factory);
 
2113
        default:
 
2114
            return PJ_EINVAL;
 
2115
        }
 
2116
    }
 
2117
 
 
2118
    /* Cleanup pjsua data when force is applied */
 
2119
    if (force) {
 
2120
        pjsua_var.tpdata[id].type = PJSIP_TRANSPORT_UNSPECIFIED;
 
2121
        pjsua_var.tpdata[id].data.ptr = NULL;
 
2122
    }
 
2123
 
 
2124
    return PJ_SUCCESS;
 
2125
}
 
2126
 
 
2127
 
 
2128
/*
 
2129
 * Add additional headers etc in msg_data specified by application
 
2130
 * when sending requests.
 
2131
 */
 
2132
void pjsua_process_msg_data(pjsip_tx_data *tdata,
 
2133
                            const pjsua_msg_data *msg_data)
 
2134
{
 
2135
    pj_bool_t allow_body;
 
2136
    const pjsip_hdr *hdr;
 
2137
 
 
2138
    /* Always add User-Agent */
 
2139
    if (pjsua_var.ua_cfg.user_agent.slen && 
 
2140
        tdata->msg->type == PJSIP_REQUEST_MSG) 
 
2141
    {
 
2142
        const pj_str_t STR_USER_AGENT = { "User-Agent", 10 };
 
2143
        pjsip_hdr *h;
 
2144
        h = (pjsip_hdr*)pjsip_generic_string_hdr_create(tdata->pool, 
 
2145
                                                        &STR_USER_AGENT, 
 
2146
                                                        &pjsua_var.ua_cfg.user_agent);
 
2147
        pjsip_msg_add_hdr(tdata->msg, h);
 
2148
    }
 
2149
 
 
2150
    if (!msg_data)
 
2151
        return;
 
2152
 
 
2153
    hdr = msg_data->hdr_list.next;
 
2154
    while (hdr && hdr != &msg_data->hdr_list) {
 
2155
        pjsip_hdr *new_hdr;
 
2156
 
 
2157
        new_hdr = (pjsip_hdr*) pjsip_hdr_clone(tdata->pool, hdr);
 
2158
        pjsip_msg_add_hdr(tdata->msg, new_hdr);
 
2159
 
 
2160
        hdr = hdr->next;
 
2161
    }
 
2162
 
 
2163
    allow_body = (tdata->msg->body == NULL);
 
2164
 
 
2165
    if (allow_body && msg_data->content_type.slen && msg_data->msg_body.slen) {
 
2166
        pjsip_media_type ctype;
 
2167
        pjsip_msg_body *body;   
 
2168
 
 
2169
        pjsua_parse_media_type(tdata->pool, &msg_data->content_type, &ctype);
 
2170
        body = pjsip_msg_body_create(tdata->pool, &ctype.type, &ctype.subtype,
 
2171
                                     &msg_data->msg_body);
 
2172
        tdata->msg->body = body;
 
2173
    }
 
2174
}
 
2175
 
 
2176
 
 
2177
/*
 
2178
 * Add route_set to outgoing requests
 
2179
 */
 
2180
void pjsua_set_msg_route_set( pjsip_tx_data *tdata,
 
2181
                              const pjsip_route_hdr *route_set )
 
2182
{
 
2183
    const pjsip_route_hdr *r;
 
2184
 
 
2185
    r = route_set->next;
 
2186
    while (r != route_set) {
 
2187
        pjsip_route_hdr *new_r;
 
2188
 
 
2189
        new_r = (pjsip_route_hdr*) pjsip_hdr_clone(tdata->pool, r);
 
2190
        pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)new_r);
 
2191
 
 
2192
        r = r->next;
 
2193
    }
 
2194
}
 
2195
 
 
2196
 
 
2197
/*
 
2198
 * Simple version of MIME type parsing (it doesn't support parameters)
 
2199
 */
 
2200
void pjsua_parse_media_type( pj_pool_t *pool,
 
2201
                             const pj_str_t *mime,
 
2202
                             pjsip_media_type *media_type)
 
2203
{
 
2204
    pj_str_t tmp;
 
2205
    char *pos;
 
2206
 
 
2207
    pj_bzero(media_type, sizeof(*media_type));
 
2208
 
 
2209
    pj_strdup_with_null(pool, &tmp, mime);
 
2210
 
 
2211
    pos = pj_strchr(&tmp, '/');
 
2212
    if (pos) {
 
2213
        media_type->type.ptr = tmp.ptr; 
 
2214
        media_type->type.slen = (pos-tmp.ptr);
 
2215
        media_type->subtype.ptr = pos+1; 
 
2216
        media_type->subtype.slen = tmp.ptr+tmp.slen-pos-1;
 
2217
    } else {
 
2218
        media_type->type = tmp;
 
2219
    }
 
2220
}
 
2221
 
 
2222
 
 
2223
/*
 
2224
 * Internal function to init transport selector from transport id.
 
2225
 */
 
2226
void pjsua_init_tpselector(pjsua_transport_id tp_id,
 
2227
                           pjsip_tpselector *sel)
 
2228
{
 
2229
    pjsua_transport_data *tpdata;
 
2230
    unsigned flag;
 
2231
 
 
2232
    pj_bzero(sel, sizeof(*sel));
 
2233
    if (tp_id == PJSUA_INVALID_ID)
 
2234
        return;
 
2235
 
 
2236
    pj_assert(tp_id >= 0 && tp_id < (int)PJ_ARRAY_SIZE(pjsua_var.tpdata));
 
2237
    tpdata = &pjsua_var.tpdata[tp_id];
 
2238
 
 
2239
    flag = pjsip_transport_get_flag_from_type(tpdata->type);
 
2240
 
 
2241
    if (flag & PJSIP_TRANSPORT_DATAGRAM) {
 
2242
        sel->type = PJSIP_TPSELECTOR_TRANSPORT;
 
2243
        sel->u.transport = tpdata->data.tp;
 
2244
    } else {
 
2245
        sel->type = PJSIP_TPSELECTOR_LISTENER;
 
2246
        sel->u.listener = tpdata->data.factory;
 
2247
    }
 
2248
}
 
2249
 
 
2250
 
 
2251
/* Callback upon NAT detection completion */
 
2252
static void nat_detect_cb(void *user_data, 
 
2253
                          const pj_stun_nat_detect_result *res)
 
2254
{
 
2255
    PJ_UNUSED_ARG(user_data);
 
2256
 
 
2257
    pjsua_var.nat_in_progress = PJ_FALSE;
 
2258
    pjsua_var.nat_status = res->status;
 
2259
    pjsua_var.nat_type = res->nat_type;
 
2260
 
 
2261
    if (pjsua_var.ua_cfg.cb.on_nat_detect) {
 
2262
        (*pjsua_var.ua_cfg.cb.on_nat_detect)(res);
 
2263
    }
 
2264
}
 
2265
 
 
2266
 
 
2267
/*
 
2268
 * Detect NAT type.
 
2269
 */
 
2270
PJ_DEF(pj_status_t) pjsua_detect_nat_type()
 
2271
{
 
2272
    pj_status_t status;
 
2273
 
 
2274
    if (pjsua_var.nat_in_progress)
 
2275
        return PJ_SUCCESS;
 
2276
 
 
2277
    /* Make sure STUN server resolution has completed */
 
2278
    status = resolve_stun_server(PJ_TRUE);
 
2279
    if (status != PJ_SUCCESS) {
 
2280
        pjsua_var.nat_status = status;
 
2281
        pjsua_var.nat_type = PJ_STUN_NAT_TYPE_ERR_UNKNOWN;
 
2282
        return status;
 
2283
    }
 
2284
 
 
2285
    /* Make sure we have STUN */
 
2286
    if (pjsua_var.stun_srv.ipv4.sin_family == 0) {
 
2287
        pjsua_var.nat_status = PJNATH_ESTUNINSERVER;
 
2288
        return PJNATH_ESTUNINSERVER;
 
2289
    }
 
2290
 
 
2291
    status = pj_stun_detect_nat_type(&pjsua_var.stun_srv.ipv4, 
 
2292
                                     &pjsua_var.stun_cfg, 
 
2293
                                     NULL, &nat_detect_cb);
 
2294
 
 
2295
    if (status != PJ_SUCCESS) {
 
2296
        pjsua_var.nat_status = status;
 
2297
        pjsua_var.nat_type = PJ_STUN_NAT_TYPE_ERR_UNKNOWN;
 
2298
        return status;
 
2299
    }
 
2300
 
 
2301
    pjsua_var.nat_in_progress = PJ_TRUE;
 
2302
 
 
2303
    return PJ_SUCCESS;
 
2304
}
 
2305
 
 
2306
 
 
2307
/*
 
2308
 * Get NAT type.
 
2309
 */
 
2310
PJ_DEF(pj_status_t) pjsua_get_nat_type(pj_stun_nat_type *type)
 
2311
{
 
2312
    *type = pjsua_var.nat_type;
 
2313
    return pjsua_var.nat_status;
 
2314
}
 
2315
 
 
2316
 
 
2317
/*
 
2318
 * Verify that valid SIP url is given.
 
2319
 */
 
2320
PJ_DEF(pj_status_t) pjsua_verify_sip_url(const char *c_url)
 
2321
{
 
2322
    pjsip_uri *p;
 
2323
    pj_pool_t *pool;
 
2324
    char *url;
 
2325
    int len = (c_url ? pj_ansi_strlen(c_url) : 0);
 
2326
 
 
2327
    if (!len) return -1;
 
2328
 
 
2329
    pool = pj_pool_create(&pjsua_var.cp.factory, "check%p", 1024, 0, NULL);
 
2330
    if (!pool) return -1;
 
2331
 
 
2332
    url = (char*) pj_pool_alloc(pool, len+1);
 
2333
    pj_ansi_strcpy(url, c_url);
 
2334
 
 
2335
    p = pjsip_parse_uri(pool, url, len, 0);
 
2336
    if (!p || (pj_stricmp2(pjsip_uri_get_scheme(p), "sip") != 0 &&
 
2337
               pj_stricmp2(pjsip_uri_get_scheme(p), "sips") != 0))
 
2338
    {
 
2339
        p = NULL;
 
2340
    }
 
2341
 
 
2342
    pj_pool_release(pool);
 
2343
    return p ? 0 : -1;
 
2344
}
 
2345
 
 
2346
/*
 
2347
 * Schedule a timer entry. 
 
2348
 */
 
2349
PJ_DEF(pj_status_t) pjsua_schedule_timer( pj_timer_entry *entry,
 
2350
                                          const pj_time_val *delay)
 
2351
{
 
2352
    return pjsip_endpt_schedule_timer(pjsua_var.endpt, entry, delay);
 
2353
}
 
2354
 
 
2355
/*
 
2356
 * Cancel the previously scheduled timer.
 
2357
 *
 
2358
 */
 
2359
PJ_DEF(void) pjsua_cancel_timer(pj_timer_entry *entry)
 
2360
{
 
2361
    pjsip_endpt_cancel_timer(pjsua_var.endpt, entry);
 
2362
}
 
2363
 
 
2364
/** 
 
2365
 * Normalize route URI (check for ";lr" and append one if it doesn't
 
2366
 * exist and pjsua_config.force_lr is set.
 
2367
 */
 
2368
pj_status_t normalize_route_uri(pj_pool_t *pool, pj_str_t *uri)
 
2369
{
 
2370
    pj_str_t tmp_uri;
 
2371
    pj_pool_t *tmp_pool;
 
2372
    pjsip_uri *uri_obj;
 
2373
    pjsip_sip_uri *sip_uri;
 
2374
 
 
2375
    tmp_pool = pjsua_pool_create("tmplr%p", 512, 512);
 
2376
    if (!tmp_pool)
 
2377
        return PJ_ENOMEM;
 
2378
 
 
2379
    pj_strdup_with_null(tmp_pool, &tmp_uri, uri);
 
2380
 
 
2381
    uri_obj = pjsip_parse_uri(tmp_pool, tmp_uri.ptr, tmp_uri.slen, 0);
 
2382
    if (!uri_obj) {
 
2383
        PJ_LOG(1,(THIS_FILE, "Invalid route URI: %.*s", 
 
2384
                  (int)uri->slen, uri->ptr));
 
2385
        pj_pool_release(tmp_pool);
 
2386
        return PJSIP_EINVALIDURI;
 
2387
    }
 
2388
 
 
2389
    if (!PJSIP_URI_SCHEME_IS_SIP(uri_obj) && 
 
2390
        !PJSIP_URI_SCHEME_IS_SIP(uri_obj))
 
2391
    {
 
2392
        PJ_LOG(1,(THIS_FILE, "Route URI must be SIP URI: %.*s", 
 
2393
                  (int)uri->slen, uri->ptr));
 
2394
        pj_pool_release(tmp_pool);
 
2395
        return PJSIP_EINVALIDSCHEME;
 
2396
    }
 
2397
 
 
2398
    sip_uri = (pjsip_sip_uri*) pjsip_uri_get_uri(uri_obj);
 
2399
 
 
2400
    /* Done if force_lr is disabled or if lr parameter is present */
 
2401
    if (!pjsua_var.ua_cfg.force_lr || sip_uri->lr_param) {
 
2402
        pj_pool_release(tmp_pool);
 
2403
        return PJ_SUCCESS;
 
2404
    }
 
2405
 
 
2406
    /* Set lr param */
 
2407
    sip_uri->lr_param = 1;
 
2408
 
 
2409
    /* Print the URI */
 
2410
    tmp_uri.ptr = (char*) pj_pool_alloc(tmp_pool, PJSIP_MAX_URL_SIZE);
 
2411
    tmp_uri.slen = pjsip_uri_print(PJSIP_URI_IN_ROUTING_HDR, uri_obj, 
 
2412
                                   tmp_uri.ptr, PJSIP_MAX_URL_SIZE);
 
2413
    if (tmp_uri.slen < 1) {
 
2414
        PJ_LOG(1,(THIS_FILE, "Route URI is too long: %.*s", 
 
2415
                  (int)uri->slen, uri->ptr));
 
2416
        pj_pool_release(tmp_pool);
 
2417
        return PJSIP_EURITOOLONG;
 
2418
    }
 
2419
 
 
2420
    /* Clone the URI */
 
2421
    pj_strdup_with_null(pool, uri, &tmp_uri);
 
2422
 
 
2423
    pj_pool_release(tmp_pool);
 
2424
    return PJ_SUCCESS;
 
2425
}
 
2426
 
 
2427
/*
 
2428
 * This is a utility function to dump the stack states to log, using
 
2429
 * verbosity level 3.
 
2430
 */
 
2431
PJ_DEF(void) pjsua_dump(pj_bool_t detail)
 
2432
{
 
2433
    unsigned old_decor;
 
2434
    unsigned i;
 
2435
 
 
2436
    PJ_LOG(3,(THIS_FILE, "Start dumping application states:"));
 
2437
 
 
2438
    old_decor = pj_log_get_decor();
 
2439
    pj_log_set_decor(old_decor & (PJ_LOG_HAS_NEWLINE | PJ_LOG_HAS_CR));
 
2440
 
 
2441
    if (detail)
 
2442
        pj_dump_config();
 
2443
 
 
2444
    pjsip_endpt_dump(pjsua_get_pjsip_endpt(), detail);
 
2445
 
 
2446
    pjmedia_endpt_dump(pjsua_get_pjmedia_endpt());
 
2447
 
 
2448
    PJ_LOG(3,(THIS_FILE, "Dumping media transports:"));
 
2449
    for (i=0; i<pjsua_var.ua_cfg.max_calls; ++i) {
 
2450
        pjsua_call *call = &pjsua_var.calls[i];
 
2451
        pjmedia_transport_info tpinfo;
 
2452
        char addr_buf[80];
 
2453
 
 
2454
        /* MSVC complains about tpinfo not being initialized */
 
2455
        //pj_bzero(&tpinfo, sizeof(tpinfo));
 
2456
 
 
2457
        pjmedia_transport_info_init(&tpinfo);
 
2458
        pjmedia_transport_get_info(call->med_tp, &tpinfo);
 
2459
 
 
2460
        PJ_LOG(3,(THIS_FILE, " %s: %s",
 
2461
                  (pjsua_var.media_cfg.enable_ice ? "ICE" : "UDP"),
 
2462
                  pj_sockaddr_print(&tpinfo.sock_info.rtp_addr_name, addr_buf,
 
2463
                                    sizeof(addr_buf), 3)));
 
2464
    }
 
2465
 
 
2466
    pjsip_tsx_layer_dump(detail);
 
2467
    pjsip_ua_dump(detail);
 
2468
 
 
2469
// Dumping complete call states may require a 'large' buffer 
 
2470
// (about 3KB per call session, including RTCP XR).
 
2471
#if 0
 
2472
    /* Dump all invite sessions: */
 
2473
    PJ_LOG(3,(THIS_FILE, "Dumping invite sessions:"));
 
2474
 
 
2475
    if (pjsua_call_get_count() == 0) {
 
2476
 
 
2477
        PJ_LOG(3,(THIS_FILE, "  - no sessions -"));
 
2478
 
 
2479
    } else {
 
2480
        unsigned i;
 
2481
 
 
2482
        for (i=0; i<pjsua_var.ua_cfg.max_calls; ++i) {
 
2483
            if (pjsua_call_is_active(i)) {
 
2484
                /* Tricky logging, since call states log string tends to be 
 
2485
                 * longer than PJ_LOG_MAX_SIZE.
 
2486
                 */
 
2487
                char buf[1024 * 3];
 
2488
                unsigned call_dump_len;
 
2489
                unsigned part_len;
 
2490
                unsigned part_idx;
 
2491
                unsigned log_decor;
 
2492
 
 
2493
                pjsua_call_dump(i, detail, buf, sizeof(buf), "  ");
 
2494
                call_dump_len = strlen(buf);
 
2495
 
 
2496
                log_decor = pj_log_get_decor();
 
2497
                pj_log_set_decor(log_decor & ~(PJ_LOG_HAS_NEWLINE | 
 
2498
                                               PJ_LOG_HAS_CR));
 
2499
                PJ_LOG(3,(THIS_FILE, "\n"));
 
2500
                pj_log_set_decor(0);
 
2501
 
 
2502
                part_idx = 0;
 
2503
                part_len = PJ_LOG_MAX_SIZE-80;
 
2504
                while (part_idx < call_dump_len) {
 
2505
                    char p_orig, *p;
 
2506
 
 
2507
                    p = &buf[part_idx];
 
2508
                    if (part_idx + part_len > call_dump_len)
 
2509
                        part_len = call_dump_len - part_idx;
 
2510
                    p_orig = p[part_len];
 
2511
                    p[part_len] = '\0';
 
2512
                    PJ_LOG(3,(THIS_FILE, "%s", p));
 
2513
                    p[part_len] = p_orig;
 
2514
                    part_idx += part_len;
 
2515
                }
 
2516
                pj_log_set_decor(log_decor);
 
2517
            }
 
2518
        }
 
2519
    }
 
2520
#endif
 
2521
 
 
2522
    /* Dump presence status */
 
2523
    pjsua_pres_dump(detail);
 
2524
 
 
2525
    pj_log_set_decor(old_decor);
 
2526
    PJ_LOG(3,(THIS_FILE, "Dump complete"));
 
2527
}
 
2528