Statistics
| Branch: | Revision:

janus-gateway / plugins / janus_sip.c @ fee224b8

History | View | Annotate | Download (126 KB)

1
/*! \file   janus_sip.c
2
 * \author Lorenzo Miniero <lorenzo@meetecho.com>
3
 * \copyright GNU General Public License v3
4
 * \brief  Janus SIP plugin
5
 * \details  This is a simple SIP plugin for Janus, allowing WebRTC peers
6
 * to register at a SIP server (e.g., Asterisk) and call SIP user agents
7
 * through the gateway. Specifically, when attaching to the plugin peers
8
 * are requested to provide their SIP server credentials, i.e., the address
9
 * of the SIP server and their username/secret. This results in the plugin
10
 * registering at the SIP server and acting as a SIP client on behalf of
11
 * the web peer. Most of the SIP states and lifetime are masked by the plugin,
12
 * and only the relevant events (e.g., INVITEs and BYEs) and functionality
13
 * (call, hangup) are made available to the web peer: peers can call
14
 * extensions at the SIP server or wait for incoming INVITEs, and during
15
 * a call they can send DTMF tones. Calls can do plain RTP or SDES-SRTP.
16
 *
17
 * The concept behind this plugin is to allow different web pages associated
18
 * to the same peer, and hence the same SIP user, to attach to the plugin
19
 * at the same time and yet just do a SIP REGISTER once. The same should
20
 * apply for calls: while an incoming call would be notified to all the
21
 * web UIs associated to the peer, only one would be able to pick up and
22
 * answer, in pretty much the same way as SIP forking works but without the
23
 * need to fork in the same place. This specific functionality, though, has
24
 * not been implemented as of yet.
25
 *
26
 * \todo Only Asterisk and Kamailio have been tested as a SIP server, and
27
 * specifically only with basic audio calls: this plugin needs some work
28
 * to make it more stable and reliable.
29
 *
30
 * \section sipapi SIP Plugin API
31
 *
32
 * All requests you can send in the SIP Plugin API are asynchronous,
33
 * which means all responses (successes and errors) will be delivered
34
 * as events with the same transaction.
35
 *
36
 * The supported requests are \c register , \c call , \c accept and
37
 * \c hangup . \c register can be used, as the name suggests, to register
38
 * a username at a SIP registrar to call and be called; \c call is used
39
 * to send an INVITE to a different SIP URI through the plugin, while
40
 * \c accept is used to accept the call in case one is invited instead
41
 * of inviting; finally, \c hangup can be used to terminate the
42
 * communication at any time, either to hangup (BYE) an ongoing call or
43
 * to cancel/decline (CANCEL/BYE) a call that hasn't started yet.
44
 *
45
 * Actual API docs: TBD.
46
 *
47
 * \ingroup plugins
48
 * \ref plugins
49
 */
50

    
51
#include "plugin.h"
52

    
53
#include <arpa/inet.h>
54
#include <net/if.h>
55

    
56
#include <jansson.h>
57

    
58
#include <sofia-sip/msg_header.h>
59
#include <sofia-sip/nua.h>
60
#include <sofia-sip/sdp.h>
61
#include <sofia-sip/sip_status.h>
62
#include <sofia-sip/url.h>
63
#include <sofia-sip/tport_tag.h>
64

    
65
#include <srtp/srtp.h>
66
#include <srtp/crypto_kernel.h>
67

    
68
#include "../debug.h"
69
#include "../apierror.h"
70
#include "../config.h"
71
#include "../mutex.h"
72
#include "../record.h"
73
#include "../rtp.h"
74
#include "../rtcp.h"
75
#include "../utils.h"
76

    
77

    
78
/* Plugin information */
79
#define JANUS_SIP_VERSION                        6
80
#define JANUS_SIP_VERSION_STRING        "0.0.6"
81
#define JANUS_SIP_DESCRIPTION                "This is a simple SIP plugin for Janus, allowing WebRTC peers to register at a SIP server and call SIP user agents through the gateway."
82
#define JANUS_SIP_NAME                                "JANUS SIP plugin"
83
#define JANUS_SIP_AUTHOR                        "Meetecho s.r.l."
84
#define JANUS_SIP_PACKAGE                        "janus.plugin.sip"
85

    
86
/* Plugin methods */
87
janus_plugin *create(void);
88
int janus_sip_init(janus_callbacks *callback, const char *config_path);
89
void janus_sip_destroy(void);
90
int janus_sip_get_api_compatibility(void);
91
int janus_sip_get_version(void);
92
const char *janus_sip_get_version_string(void);
93
const char *janus_sip_get_description(void);
94
const char *janus_sip_get_name(void);
95
const char *janus_sip_get_author(void);
96
const char *janus_sip_get_package(void);
97
void janus_sip_create_session(janus_plugin_session *handle, int *error);
98
struct janus_plugin_result *janus_sip_handle_message(janus_plugin_session *handle, char *transaction, json_t *message, json_t *jsep);
99
void janus_sip_setup_media(janus_plugin_session *handle);
100
void janus_sip_incoming_rtp(janus_plugin_session *handle, int video, char *buf, int len);
101
void janus_sip_incoming_rtcp(janus_plugin_session *handle, int video, char *buf, int len);
102
void janus_sip_hangup_media(janus_plugin_session *handle);
103
void janus_sip_destroy_session(janus_plugin_session *handle, int *error);
104
json_t *janus_sip_query_session(janus_plugin_session *handle);
105

    
106
/* Plugin setup */
107
static janus_plugin janus_sip_plugin =
108
        JANUS_PLUGIN_INIT (
109
                .init = janus_sip_init,
110
                .destroy = janus_sip_destroy,
111

    
112
                .get_api_compatibility = janus_sip_get_api_compatibility,
113
                .get_version = janus_sip_get_version,
114
                .get_version_string = janus_sip_get_version_string,
115
                .get_description = janus_sip_get_description,
116
                .get_name = janus_sip_get_name,
117
                .get_author = janus_sip_get_author,
118
                .get_package = janus_sip_get_package,
119

    
120
                .create_session = janus_sip_create_session,
121
                .handle_message = janus_sip_handle_message,
122
                .setup_media = janus_sip_setup_media,
123
                .incoming_rtp = janus_sip_incoming_rtp,
124
                .incoming_rtcp = janus_sip_incoming_rtcp,
125
                .hangup_media = janus_sip_hangup_media,
126
                .destroy_session = janus_sip_destroy_session,
127
                .query_session = janus_sip_query_session,
128
        );
129

    
130
/* Plugin creator */
131
janus_plugin *create(void) {
132
        JANUS_LOG(LOG_VERB, "%s created!\n", JANUS_SIP_NAME);
133
        return &janus_sip_plugin;
134
}
135

    
136
/* Parameter validation */
137
static struct janus_json_parameter request_parameters[] = {
138
        {"request", JSON_STRING, JANUS_JSON_PARAM_REQUIRED}
139
};
140
static struct janus_json_parameter register_parameters[] = {
141
        {"type", JSON_STRING, 0},
142
        {"send_register", JANUS_JSON_BOOL, 0},
143
        {"sips", JANUS_JSON_BOOL, 0},
144
        {"username", JSON_STRING, 0},
145
        {"secret", JSON_STRING, 0},
146
        {"ha1_secret", JSON_STRING, 0},
147
        {"authuser", JSON_STRING, 0}
148
};
149
static struct janus_json_parameter proxy_parameters[] = {
150
        {"proxy", JSON_STRING, 0}
151
};
152
static struct janus_json_parameter call_parameters[] = {
153
        {"uri", JSON_STRING, JANUS_JSON_PARAM_REQUIRED},
154
        {"autoack", JANUS_JSON_BOOL, 0},
155
        {"headers", JSON_OBJECT, 0},
156
        {"srtp", JSON_STRING, 0}
157
};
158
static struct janus_json_parameter accept_parameters[] = {
159
        {"srtp", JSON_STRING, 0}
160
};
161
static struct janus_json_parameter recording_parameters[] = {
162
        {"action", JSON_STRING, JANUS_JSON_PARAM_REQUIRED},
163
        {"audio", JANUS_JSON_BOOL, 0},
164
        {"video", JANUS_JSON_BOOL, 0},
165
        {"peer_audio", JANUS_JSON_BOOL, 0},
166
        {"peer_video", JANUS_JSON_BOOL, 0},
167
        {"filename", JSON_STRING, 0}
168
};
169
static struct janus_json_parameter dtmf_info_parameters[] = {
170
        {"digit", JSON_STRING, JANUS_JSON_PARAM_REQUIRED},
171
        {"duration", JSON_INTEGER, JANUS_JSON_PARAM_POSITIVE}
172
};
173

    
174
/* Useful stuff */
175
static volatile gint initialized = 0, stopping = 0;
176
static janus_callbacks *gateway = NULL;
177

    
178
static char local_ip[INET6_ADDRSTRLEN];
179
static int keepalive_interval = 120;
180
static gboolean behind_nat = FALSE;
181
static char *user_agent;
182
#define JANUS_DEFAULT_REGISTER_TTL        3600
183
static int register_ttl = JANUS_DEFAULT_REGISTER_TTL;
184

    
185
static GThread *handler_thread;
186
static GThread *watchdog;
187
static void *janus_sip_handler(void *data);
188

    
189
typedef struct janus_sip_message {
190
        janus_plugin_session *handle;
191
        char *transaction;
192
        json_t *message;
193
        json_t *jsep;
194
} janus_sip_message;
195
static GAsyncQueue *messages = NULL;
196
static janus_sip_message exit_message;
197

    
198
static void janus_sip_message_free(janus_sip_message *msg) {
199
        if(!msg || msg == &exit_message)
200
                return;
201

    
202
        msg->handle = NULL;
203

    
204
        g_free(msg->transaction);
205
        msg->transaction = NULL;
206
        if(msg->message)
207
                json_decref(msg->message);
208
        msg->message = NULL;
209
        if(msg->jsep)
210
                json_decref(msg->jsep);
211
        msg->jsep = NULL;
212

    
213
        g_free(msg);
214
}
215

    
216

    
217
typedef enum {
218
        janus_sip_registration_status_disabled = -2,
219
        janus_sip_registration_status_failed = -1,
220
        janus_sip_registration_status_unregistered = 0,
221
        janus_sip_registration_status_registering,
222
        janus_sip_registration_status_registered,
223
        janus_sip_registration_status_unregistering,
224
} janus_sip_registration_status;
225

    
226
static const char *janus_sip_registration_status_string(janus_sip_registration_status status) {
227
        switch(status) {
228
                case janus_sip_registration_status_disabled:
229
                        return "disabled";
230
                case janus_sip_registration_status_failed:
231
                        return "failed";
232
                case janus_sip_registration_status_unregistered:
233
                        return "unregistered";
234
                case janus_sip_registration_status_registering:
235
                        return "registering";
236
                case janus_sip_registration_status_registered:
237
                        return "registered";
238
                case janus_sip_registration_status_unregistering:
239
                        return "unregistering";
240
                default:
241
                        return "unknown";
242
        }
243
}
244

    
245

    
246
typedef enum {
247
        janus_sip_call_status_idle = 0,
248
        janus_sip_call_status_inviting,
249
        janus_sip_call_status_invited,
250
        janus_sip_call_status_incall,
251
        janus_sip_call_status_closing,
252
} janus_sip_call_status;
253

    
254
static const char *janus_sip_call_status_string(janus_sip_call_status status) {
255
        switch(status) {
256
                case janus_sip_call_status_idle:
257
                        return "idle";
258
                case janus_sip_call_status_inviting:
259
                        return "inviting";
260
                case janus_sip_call_status_invited:
261
                        return "invited";
262
                case janus_sip_call_status_incall:
263
                        return "incall";
264
                case janus_sip_call_status_closing:
265
                        return "closing";
266
                default:
267
                        return "unknown";
268
        }
269
}
270

    
271

    
272
/* Sofia stuff */
273
typedef struct ssip_s ssip_t;
274
typedef struct ssip_oper_s ssip_oper_t;
275

    
276
typedef enum {
277
        janus_sip_secret_type_plaintext = 1,
278
        janus_sip_secret_type_hashed = 2,
279
        janus_sip_secret_type_unknown
280
} janus_sip_secret_type;
281

    
282
typedef struct janus_sip_account {
283
        char *identity;
284
        char *user_agent;                /* Used to override the general UA string */
285
        gboolean sips;
286
        char *username;
287
        char *display_name;                /* Used for outgoing calls in the From header */
288
        char *authuser;                        /**< username to use for authentication */
289
        char *secret;
290
        janus_sip_secret_type secret_type;
291
        int sip_port;
292
        char *proxy;
293
        janus_sip_registration_status registration_status;
294
} janus_sip_account;
295

    
296
typedef struct janus_sip_media {
297
        char *remote_ip;
298
        int ready:1;
299
        gboolean autoack;
300
        gboolean require_srtp, has_srtp_local, has_srtp_remote;
301
        int has_audio:1;
302
        int audio_rtp_fd, audio_rtcp_fd;
303
        int local_audio_rtp_port, remote_audio_rtp_port;
304
        int local_audio_rtcp_port, remote_audio_rtcp_port;
305
        guint32 audio_ssrc, audio_ssrc_peer;
306
        int audio_pt;
307
        const char *audio_pt_name;
308
        srtp_t audio_srtp_in, audio_srtp_out;
309
        srtp_policy_t audio_remote_policy, audio_local_policy;
310
        int audio_srtp_suite_in, audio_srtp_suite_out;
311
        int has_video:1;
312
        int video_rtp_fd, video_rtcp_fd;
313
        int local_video_rtp_port, remote_video_rtp_port;
314
        int local_video_rtcp_port, remote_video_rtcp_port;
315
        guint32 video_ssrc, video_ssrc_peer;
316
        int video_pt;
317
        const char *video_pt_name;
318
        srtp_t video_srtp_in, video_srtp_out;
319
        srtp_policy_t video_remote_policy, video_local_policy;
320
        int video_srtp_suite_in, video_srtp_suite_out;
321
} janus_sip_media;
322

    
323
typedef struct janus_sip_session {
324
        janus_plugin_session *handle;
325
        ssip_t *stack;
326
        janus_sip_account account;
327
        janus_sip_call_status status;
328
        janus_sip_media media;
329
        sdp_parser_t *raw_media;
330
        char *transaction;
331
        char *callee;
332
        janus_recorder *arc;                /* The Janus recorder instance for this user's audio, if enabled */
333
        janus_recorder *arc_peer;        /* The Janus recorder instance for the peer's audio, if enabled */
334
        janus_recorder *vrc;                /* The Janus recorder instance for this user's video, if enabled */
335
        janus_recorder *vrc_peer;        /* The Janus recorder instance for the peer's video, if enabled */
336
        janus_mutex rec_mutex;                /* Mutex to protect the recorders from race conditions */
337
        volatile gint hangingup;
338
        gint64 destroyed;        /* Time at which this session was marked as destroyed */
339
        janus_mutex mutex;
340
} janus_sip_session;
341
static GHashTable *sessions;
342
static GList *old_sessions;
343
static janus_mutex sessions_mutex;
344

    
345

    
346
#undef SU_ROOT_MAGIC_T
347
#define SU_ROOT_MAGIC_T        ssip_t
348
#undef NUA_MAGIC_T
349
#define NUA_MAGIC_T                ssip_t
350
#undef NUA_HMAGIC_T
351
#define NUA_HMAGIC_T        ssip_oper_t
352

    
353
struct ssip_s {
354
        su_home_t s_home[1];
355
        su_root_t *s_root;
356
        nua_t *s_nua;
357
        nua_handle_t *s_nh_r, *s_nh_i;
358
        janus_sip_session *session;
359
};
360

    
361

    
362
/* SRTP stuff (in case we need SDES) */
363
#define SRTP_MASTER_KEY_LENGTH        16
364
#define SRTP_MASTER_SALT_LENGTH        14
365
#define SRTP_MASTER_LENGTH (SRTP_MASTER_KEY_LENGTH + SRTP_MASTER_SALT_LENGTH)
366
static const char *janus_sip_srtp_error[] =
367
{
368
        "err_status_ok",
369
        "err_status_fail",
370
        "err_status_bad_param",
371
        "err_status_alloc_fail",
372
        "err_status_dealloc_fail",
373
        "err_status_init_fail",
374
        "err_status_terminus",
375
        "err_status_auth_fail",
376
        "err_status_cipher_fail",
377
        "err_status_replay_fail",
378
        "err_status_replay_old",
379
        "err_status_algo_fail",
380
        "err_status_no_such_op",
381
        "err_status_no_ctx",
382
        "err_status_cant_check",
383
        "err_status_key_expired",
384
        "err_status_socket_err",
385
        "err_status_signal_err",
386
        "err_status_nonce_bad",
387
        "err_status_read_fail",
388
        "err_status_write_fail",
389
        "err_status_parse_err",
390
        "err_status_encode_err",
391
        "err_status_semaphore_err",
392
        "err_status_pfkey_err",
393
};
394
static const gchar *janus_sip_get_srtp_error(int error) {
395
        if(error < 0 || error > 24)
396
                return NULL;
397
        return janus_sip_srtp_error[error];
398
}
399
static int janus_sip_srtp_set_local(janus_sip_session *session, gboolean video, char **crypto) {
400
        if(session == NULL)
401
                return -1;
402
        /* Generate key/salt */
403
        uint8_t *key = g_malloc0(SRTP_MASTER_LENGTH);
404
        crypto_get_random(key, SRTP_MASTER_LENGTH);
405
        /* Set SRTP policies */
406
        srtp_policy_t *policy = video ? &session->media.video_local_policy : &session->media.audio_local_policy;
407
        crypto_policy_set_rtp_default(&(policy->rtp));
408
        crypto_policy_set_rtcp_default(&(policy->rtcp));
409
        policy->ssrc.type = ssrc_any_inbound;
410
        policy->key = key;
411
        policy->next = NULL;
412
        /* Create SRTP context */
413
        err_status_t res = srtp_create(video ? &session->media.video_srtp_out : &session->media.audio_srtp_out, policy);
414
        if(res != err_status_ok) {
415
                /* Something went wrong... */
416
                JANUS_LOG(LOG_ERR, "Oops, error creating outbound SRTP session: %d (%s)\n", res, janus_sip_get_srtp_error(res));
417
                g_free(key);
418
                policy->key = NULL;
419
                return -2;
420
        }
421
        /* Base64 encode the salt */
422
        *crypto = g_base64_encode(key, SRTP_MASTER_LENGTH);
423
        if((video && session->media.video_srtp_out) || (!video && session->media.audio_srtp_out)) {
424
                JANUS_LOG(LOG_VERB, "%s outbound SRTP session created\n", video ? "Video" : "Audio");
425
        }
426
        return 0;
427
}
428
static int janus_sip_srtp_set_remote(janus_sip_session *session, gboolean video, const char *crypto, int suite) {
429
        if(session == NULL || crypto == NULL)
430
                return -1;
431
        /* Base64 decode the crypto string and set it as the remote SRTP context */
432
        gsize len = 0;
433
        guchar *decoded = g_base64_decode(crypto, &len);
434
        if(len < SRTP_MASTER_LENGTH) {
435
                /* FIXME Can this happen? */
436
                g_free(decoded);
437
                return -2;
438
        }
439
        /* Set SRTP policies */
440
        srtp_policy_t *policy = video ? &session->media.video_remote_policy : &session->media.audio_remote_policy;
441
        crypto_policy_set_rtp_default(&(policy->rtp));
442
        crypto_policy_set_rtcp_default(&(policy->rtcp));
443
        if(suite == 32) {
444
                crypto_policy_set_aes_cm_128_hmac_sha1_32(&(policy->rtp));
445
                crypto_policy_set_aes_cm_128_hmac_sha1_32(&(policy->rtcp));
446
        } else if(suite == 80) {
447
                crypto_policy_set_aes_cm_128_hmac_sha1_80(&(policy->rtp));
448
                crypto_policy_set_aes_cm_128_hmac_sha1_80(&(policy->rtcp));
449
        }
450
        policy->ssrc.type = ssrc_any_inbound;
451
        policy->key = decoded;
452
        policy->next = NULL;
453
        /* Create SRTP context */
454
        err_status_t res = srtp_create(video ? &session->media.video_srtp_in : &session->media.audio_srtp_in, policy);
455
        if(res != err_status_ok) {
456
                /* Something went wrong... */
457
                JANUS_LOG(LOG_ERR, "Oops, error creating inbound SRTP session: %d (%s)\n", res, janus_sip_get_srtp_error(res));
458
                g_free(decoded);
459
                policy->key = NULL;
460
                return -2;
461
        }
462
        if((video && session->media.video_srtp_in) || (!video && session->media.audio_srtp_in)) {
463
                JANUS_LOG(LOG_VERB, "%s inbound SRTP session created\n", video ? "Video" : "Audio");
464
        }
465
        return 0;
466
}
467
static void janus_sip_srtp_cleanup(janus_sip_session *session) {
468
        if(session == NULL)
469
                return;
470
        session->media.autoack = TRUE;
471
        session->media.require_srtp = FALSE;
472
        session->media.has_srtp_local = FALSE;
473
        session->media.has_srtp_remote = FALSE;
474
        /* Audio */
475
        if(session->media.audio_srtp_out)
476
                srtp_dealloc(session->media.audio_srtp_out);
477
        session->media.audio_srtp_out = NULL;
478
        g_free(session->media.audio_local_policy.key);
479
        session->media.audio_local_policy.key = NULL;
480
        session->media.audio_srtp_suite_out = 0;
481
        if(session->media.audio_srtp_in)
482
                srtp_dealloc(session->media.audio_srtp_in);
483
        session->media.audio_srtp_in = NULL;
484
        g_free(session->media.audio_remote_policy.key);
485
        session->media.audio_remote_policy.key = NULL;
486
        session->media.audio_srtp_suite_in = 0;
487
        /* Video */
488
        if(session->media.video_srtp_out)
489
                srtp_dealloc(session->media.video_srtp_out);
490
        session->media.video_srtp_out = NULL;
491
        g_free(session->media.video_local_policy.key);
492
        session->media.video_local_policy.key = NULL;
493
        session->media.video_srtp_suite_out = 0;
494
        if(session->media.video_srtp_in)
495
                srtp_dealloc(session->media.video_srtp_in);
496
        session->media.video_srtp_in = NULL;
497
        g_free(session->media.video_remote_policy.key);
498
        session->media.video_remote_policy.key = NULL;
499
        session->media.video_srtp_suite_in = 0;
500
}
501

    
502

    
503
/* Sofia Event thread */
504
gpointer janus_sip_sofia_thread(gpointer user_data);
505
/* Sofia callbacks */
506
void janus_sip_sofia_callback(nua_event_t event, int status, char const *phrase, nua_t *nua, nua_magic_t *magic, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tags[]);
507
/* SDP parsing and manipulation */
508
void janus_sip_sdp_process(janus_sip_session *session, sdp_session_t *sdp, gboolean answer);
509
char *janus_sip_sdp_manipulate(janus_sip_session *session, sdp_session_t *sdp, gboolean answer);
510
/* Media */
511
static int janus_sip_allocate_local_ports(janus_sip_session *session);
512
static void *janus_sip_relay_thread(void *data);
513

    
514

    
515
/* URI parsing utilies */
516

    
517
#define JANUS_SIP_URI_MAXLEN        1024
518
typedef struct {
519
        char data[JANUS_SIP_URI_MAXLEN];
520
        url_t url[1];
521
} janus_sip_uri_t;
522

    
523
/* Parses a SIP URI (SIPS is not supported), returns 0 on success, -1 otherwise */
524
static int janus_sip_parse_uri(janus_sip_uri_t *sip_uri, const char *data) {
525
        g_strlcpy(sip_uri->data, data, JANUS_SIP_URI_MAXLEN);
526
        if (url_d(sip_uri->url, sip_uri->data) < 0 || sip_uri->url->url_type != url_sip)
527
                return -1;
528
        return 0;
529
}
530

    
531
/* Similar to the above function, but it also accepts SIPS URIs */
532
static int janus_sip_parse_proxy_uri(janus_sip_uri_t *sip_uri, const char *data) {
533
        g_strlcpy(sip_uri->data, data, JANUS_SIP_URI_MAXLEN);
534
        if (url_d(sip_uri->url, sip_uri->data) < 0 || (sip_uri->url->url_type != url_sip && sip_uri->url->url_type != url_sips))
535
                return -1;
536
        return 0;
537
}
538

    
539
/* Error codes */
540
#define JANUS_SIP_ERROR_UNKNOWN_ERROR                499
541
#define JANUS_SIP_ERROR_NO_MESSAGE                        440
542
#define JANUS_SIP_ERROR_INVALID_JSON                441
543
#define JANUS_SIP_ERROR_INVALID_REQUEST                442
544
#define JANUS_SIP_ERROR_MISSING_ELEMENT                443
545
#define JANUS_SIP_ERROR_INVALID_ELEMENT                444
546
#define JANUS_SIP_ERROR_ALREADY_REGISTERED        445
547
#define JANUS_SIP_ERROR_INVALID_ADDRESS                446
548
#define JANUS_SIP_ERROR_WRONG_STATE                        447
549
#define JANUS_SIP_ERROR_MISSING_SDP                        448
550
#define JANUS_SIP_ERROR_LIBSOFIA_ERROR                449
551
#define JANUS_SIP_ERROR_IO_ERROR                        450
552
#define JANUS_SIP_ERROR_RECORDING_ERROR                451
553
#define JANUS_SIP_ERROR_TOO_STRICT                        452
554

    
555

    
556
/* SIP watchdog/garbage collector (sort of) */
557
void *janus_sip_watchdog(void *data);
558
void *janus_sip_watchdog(void *data) {
559
        JANUS_LOG(LOG_INFO, "SIP watchdog started\n");
560
        gint64 now = 0;
561
        while(g_atomic_int_get(&initialized) && !g_atomic_int_get(&stopping)) {
562
                janus_mutex_lock(&sessions_mutex);
563
                /* Iterate on all the sessions */
564
                now = janus_get_monotonic_time();
565
                if(old_sessions != NULL) {
566
                        GList *sl = old_sessions;
567
                        JANUS_LOG(LOG_HUGE, "Checking %d old SIP sessions...\n", g_list_length(old_sessions));
568
                        while(sl) {
569
                                janus_sip_session *session = (janus_sip_session *)sl->data;
570
                                if(!session) {
571
                                        sl = sl->next;
572
                                        continue;
573
                                }
574
                                if (now-session->destroyed >= 5*G_USEC_PER_SEC) {
575
                                        /* We're lazy and actually get rid of the stuff only after a few seconds */
576
                                        JANUS_LOG(LOG_VERB, "Freeing old SIP session\n");
577
                                        GList *rm = sl->next;
578
                                        old_sessions = g_list_delete_link(old_sessions, sl);
579
                                        sl = rm;
580
                                        if (session->account.identity) {
581
                                            g_free(session->account.identity);
582
                                            session->account.identity = NULL;
583
                                        }
584
                                        session->account.sips = TRUE;
585
                                        if (session->account.proxy) {
586
                                            g_free(session->account.proxy);
587
                                            session->account.proxy = NULL;
588
                                        }
589
                                        if (session->account.secret) {
590
                                            g_free(session->account.secret);
591
                                            session->account.secret = NULL;
592
                                        }
593
                                        if (session->account.username) {
594
                                            g_free(session->account.username);
595
                                            session->account.username = NULL;
596
                                        }
597
                                        if (session->account.display_name) {
598
                                            g_free(session->account.display_name);
599
                                            session->account.display_name = NULL;
600
                                        }
601
                                        if (session->account.user_agent) {
602
                                            g_free(session->account.user_agent);
603
                                            session->account.user_agent = NULL;
604
                                        }
605
                                        if (session->account.authuser) {
606
                                            g_free(session->account.authuser);
607
                                            session->account.authuser = NULL;
608
                                        }
609
                                        if (session->callee) {
610
                                            g_free(session->callee);
611
                                            session->callee = NULL;
612
                                        }
613
                                        if (session->transaction) {
614
                                            g_free(session->transaction);
615
                                            session->transaction = NULL;
616
                                        }
617
                                        if (session->media.remote_ip) {
618
                                            g_free(session->media.remote_ip);
619
                                            session->media.remote_ip = NULL;
620
                                        }
621
                                        janus_sip_srtp_cleanup(session);
622
                                        session->handle = NULL;
623
                                        g_free(session);
624
                                        session = NULL;
625
                                        continue;
626
                                }
627
                                sl = sl->next;
628
                        }
629
                }
630
                janus_mutex_unlock(&sessions_mutex);
631
                g_usleep(500000);
632
        }
633
        JANUS_LOG(LOG_INFO, "SIP watchdog stopped\n");
634
        return NULL;
635
}
636

    
637

    
638
static void janus_sip_detect_local_ip(char *buf, size_t buflen) {
639
        JANUS_LOG(LOG_VERB, "Autodetecting local IP...\n");
640

    
641
        struct sockaddr_in addr;
642
        socklen_t len;
643
        int fd = socket(AF_INET, SOCK_DGRAM, 0);
644
        if (fd == -1)
645
                goto error;
646
        addr.sin_family = AF_INET;
647
        addr.sin_port = htons(1);
648
        inet_pton(AF_INET, "1.2.3.4", &addr.sin_addr.s_addr);
649
        if (connect(fd, (const struct sockaddr*) &addr, sizeof(addr)) < 0)
650
                goto error;
651
        len = sizeof(addr);
652
        if (getsockname(fd, (struct sockaddr*) &addr, &len) < 0)
653
                goto error;
654
        if (getnameinfo((const struct sockaddr*) &addr, sizeof(addr),
655
                        buf, buflen,
656
                        NULL, 0, NI_NUMERICHOST) != 0)
657
                goto error;
658
        close(fd);
659
        return;
660

    
661
error:
662
        if (fd != -1)
663
                close(fd);
664
        JANUS_LOG(LOG_VERB, "Couldn't find any address! using 127.0.0.1 as the local IP... (which is NOT going to work out of your machine)\n");
665
        g_strlcpy(buf, "127.0.0.1", buflen);
666
}
667

    
668

    
669
/* Plugin implementation */
670
int janus_sip_init(janus_callbacks *callback, const char *config_path) {
671
        if(g_atomic_int_get(&stopping)) {
672
                /* Still stopping from before */
673
                return -1;
674
        }
675
        if(callback == NULL || config_path == NULL) {
676
                /* Invalid arguments */
677
                return -1;
678
        }
679

    
680
        /* Read configuration */
681
        char filename[255];
682
        g_snprintf(filename, 255, "%s/%s.cfg", config_path, JANUS_SIP_PACKAGE);
683
        JANUS_LOG(LOG_VERB, "Configuration file: %s\n", filename);
684
        janus_config *config = janus_config_parse(filename);
685
        if(config != NULL)
686
                janus_config_print(config);
687

    
688
        gboolean local_ip_set = FALSE;
689
        janus_config_item *item = janus_config_get_item_drilldown(config, "general", "local_ip");
690
        if(item && item->value) {
691
                int family;
692
                if (!janus_is_ip_valid(item->value, &family)) {
693
                        JANUS_LOG(LOG_WARN, "Invalid local IP specified: %s, guessing the default...\n", item->value);
694
                } else {
695
                        /* Verify that we can actually bind to that address */
696
                        int fd = socket(family, SOCK_DGRAM, 0);
697
                        if (fd == -1) {
698
                                JANUS_LOG(LOG_WARN, "Error creating test socket, falling back to detecting IP address...\n");
699
                        } else {
700
                                int r;
701
                                struct sockaddr_storage ss;
702
                                socklen_t addrlen;
703
                                memset(&ss, 0, sizeof(ss));
704
                                if (family == AF_INET) {
705
                                        struct sockaddr_in *addr4 = (struct sockaddr_in*)&ss;
706
                                        addr4->sin_family = AF_INET;
707
                                        addr4->sin_port = 0;
708
                                        inet_pton(AF_INET, item->value, &(addr4->sin_addr.s_addr));
709
                                        addrlen = sizeof(struct sockaddr_in);
710
                                } else {
711
                                        struct sockaddr_in6 *addr6 = (struct sockaddr_in6*)&ss;
712
                                        addr6->sin6_family = AF_INET6;
713
                                        addr6->sin6_port = 0;
714
                                        inet_pton(AF_INET6, item->value, &(addr6->sin6_addr.s6_addr));
715
                                        addrlen = sizeof(struct sockaddr_in6);
716
                                }
717
                                r = bind(fd, (const struct sockaddr*)&ss, addrlen);
718
                                close(fd);
719
                                if (r < 0) {
720
                                        JANUS_LOG(LOG_WARN, "Error setting local IP address to %s, falling back to detecting IP address...\n", item->value);
721
                                } else {
722
                                        g_strlcpy(local_ip, item->value, sizeof(local_ip));
723
                                        local_ip_set = TRUE;
724
                                }
725
                        }
726
                }
727
        }
728
        if (!local_ip_set)
729
                janus_sip_detect_local_ip(local_ip, sizeof(local_ip));
730
        JANUS_LOG(LOG_VERB, "Local IP set to %s\n", local_ip);
731

    
732
        item = janus_config_get_item_drilldown(config, "general", "keepalive_interval");
733
        if(item && item->value)
734
                keepalive_interval = atoi(item->value);
735
        JANUS_LOG(LOG_VERB, "SIP keep-alive interval set to %d seconds\n", keepalive_interval);
736

    
737
        item = janus_config_get_item_drilldown(config, "general", "register_ttl");
738
        if(item && item->value)
739
                register_ttl = atoi(item->value);
740
        JANUS_LOG(LOG_VERB, "SIP registration TTL set to %d seconds\n", register_ttl);
741

    
742
        item = janus_config_get_item_drilldown(config, "general", "behind_nat");
743
        if(item && item->value)
744
                behind_nat = janus_is_true(item->value);
745

    
746
        item = janus_config_get_item_drilldown(config, "general", "user_agent");
747
        if(item && item->value)
748
                user_agent = g_strdup(item->value);
749
        else
750
                user_agent = g_strdup("Janus WebRTC Gateway SIP Plugin "JANUS_SIP_VERSION_STRING);
751
        JANUS_LOG(LOG_VERB, "SIP User-Agent set to %s\n", user_agent);
752

    
753
        /* This plugin actually has nothing to configure... */
754
        janus_config_destroy(config);
755
        config = NULL;
756

    
757
        /* Setup sofia */
758
        su_init();
759

    
760
        sessions = g_hash_table_new(NULL, NULL);
761
        janus_mutex_init(&sessions_mutex);
762
        messages = g_async_queue_new_full((GDestroyNotify) janus_sip_message_free);
763
        /* This is the callback we'll need to invoke to contact the gateway */
764
        gateway = callback;
765

    
766
        g_atomic_int_set(&initialized, 1);
767

    
768
        GError *error = NULL;
769
        /* Start the sessions watchdog */
770
        watchdog = g_thread_try_new("sip watchdog", &janus_sip_watchdog, NULL, &error);
771
        if(error != NULL) {
772
                g_atomic_int_set(&initialized, 0);
773
                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the SIP watchdog thread...\n", error->code, error->message ? error->message : "??");
774
                return -1;
775
        }
776
        /* Launch the thread that will handle incoming messages */
777
        handler_thread = g_thread_try_new("sip handler", janus_sip_handler, NULL, &error);
778
        if(error != NULL) {
779
                g_atomic_int_set(&initialized, 0);
780
                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the SIP handler thread...\n", error->code, error->message ? error->message : "??");
781
                return -1;
782
        }
783
        JANUS_LOG(LOG_INFO, "%s initialized!\n", JANUS_SIP_NAME);
784
        return 0;
785
}
786

    
787
void janus_sip_destroy(void) {
788
        if(!g_atomic_int_get(&initialized))
789
                return;
790
        g_atomic_int_set(&stopping, 1);
791

    
792
        g_async_queue_push(messages, &exit_message);
793
        if(handler_thread != NULL) {
794
                g_thread_join(handler_thread);
795
                handler_thread = NULL;
796
        }
797
        if(watchdog != NULL) {
798
                g_thread_join(watchdog);
799
                watchdog = NULL;
800
        }
801
        /* FIXME We should destroy the sessions cleanly */
802
        janus_mutex_lock(&sessions_mutex);
803
        g_hash_table_destroy(sessions);
804
        janus_mutex_unlock(&sessions_mutex);
805
        g_async_queue_unref(messages);
806
        messages = NULL;
807
        sessions = NULL;
808
        g_atomic_int_set(&initialized, 0);
809
        g_atomic_int_set(&stopping, 0);
810
        JANUS_LOG(LOG_INFO, "%s destroyed!\n", JANUS_SIP_NAME);
811
}
812

    
813
int janus_sip_get_api_compatibility(void) {
814
        /* Important! This is what your plugin MUST always return: don't lie here or bad things will happen */
815
        return JANUS_PLUGIN_API_VERSION;
816
}
817

    
818
int janus_sip_get_version(void) {
819
        return JANUS_SIP_VERSION;
820
}
821

    
822
const char *janus_sip_get_version_string(void) {
823
        return JANUS_SIP_VERSION_STRING;
824
}
825

    
826
const char *janus_sip_get_description(void) {
827
        return JANUS_SIP_DESCRIPTION;
828
}
829

    
830
const char *janus_sip_get_name(void) {
831
        return JANUS_SIP_NAME;
832
}
833

    
834
const char *janus_sip_get_author(void) {
835
        return JANUS_SIP_AUTHOR;
836
}
837

    
838
const char *janus_sip_get_package(void) {
839
        return JANUS_SIP_PACKAGE;
840
}
841

    
842
void janus_sip_create_session(janus_plugin_session *handle, int *error) {
843
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
844
                *error = -1;
845
                return;
846
        }
847
        janus_sip_session *session = g_malloc0(sizeof(janus_sip_session));
848
        session->handle = handle;
849
        session->account.identity = NULL;
850
        session->account.sips = TRUE;
851
        session->account.username = NULL;
852
        session->account.display_name = NULL;
853
        session->account.user_agent = NULL;
854
        session->account.authuser = NULL;
855
        session->account.secret = NULL;
856
        session->account.secret_type = janus_sip_secret_type_unknown;
857
        session->account.sip_port = 0;
858
        session->account.proxy = NULL;
859
        session->account.registration_status = janus_sip_registration_status_unregistered;
860
        session->status = janus_sip_call_status_idle;
861
        session->stack = NULL;
862
        session->transaction = NULL;
863
        session->callee = NULL;
864
        session->media.remote_ip = NULL;
865
        session->media.ready = 0;
866
        session->media.autoack = TRUE;
867
        session->media.require_srtp = FALSE;
868
        session->media.has_srtp_local = FALSE;
869
        session->media.has_srtp_remote = FALSE;
870
        session->media.has_audio = 0;
871
        session->media.audio_rtp_fd = -1;
872
        session->media.audio_rtcp_fd= -1;
873
        session->media.local_audio_rtp_port = 0;
874
        session->media.remote_audio_rtp_port = 0;
875
        session->media.local_audio_rtcp_port = 0;
876
        session->media.remote_audio_rtcp_port = 0;
877
        session->media.audio_ssrc = 0;
878
        session->media.audio_ssrc_peer = 0;
879
        session->media.audio_pt = -1;
880
        session->media.audio_pt_name = NULL;
881
        session->media.audio_srtp_suite_in = 0;
882
        session->media.audio_srtp_suite_out = 0;
883
        session->media.has_video = 0;
884
        session->media.video_rtp_fd = -1;
885
        session->media.video_rtcp_fd= -1;
886
        session->media.local_video_rtp_port = 0;
887
        session->media.remote_video_rtp_port = 0;
888
        session->media.local_video_rtcp_port = 0;
889
        session->media.remote_video_rtcp_port = 0;
890
        session->media.video_ssrc = 0;
891
        session->media.video_ssrc_peer = 0;
892
        session->media.video_pt = -1;
893
        session->media.video_pt_name = NULL;
894
        session->media.video_srtp_suite_in = 0;
895
        session->media.video_srtp_suite_out = 0;
896
        session->raw_media = NULL;
897
        janus_mutex_init(&session->rec_mutex);
898
        session->destroyed = 0;
899
        g_atomic_int_set(&session->hangingup, 0);
900
        janus_mutex_init(&session->mutex);
901
        handle->plugin_handle = session;
902

    
903
        janus_mutex_lock(&sessions_mutex);
904
        g_hash_table_insert(sessions, handle, session);
905
        janus_mutex_unlock(&sessions_mutex);
906

    
907
        return;
908
}
909

    
910
void janus_sip_destroy_session(janus_plugin_session *handle, int *error) {
911
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
912
                *error = -1;
913
                return;
914
        }
915
        janus_sip_session *session = (janus_sip_session *)handle->plugin_handle;
916
        if(!session) {
917
                JANUS_LOG(LOG_ERR, "No SIP session associated with this handle...\n");
918
                *error = -2;
919
                return;
920
        }
921
        janus_mutex_lock(&sessions_mutex);
922
        if(!session->destroyed) {
923
                g_hash_table_remove(sessions, handle);
924
                janus_sip_hangup_media(handle);
925
                session->destroyed = janus_get_monotonic_time();
926
                JANUS_LOG(LOG_VERB, "Destroying SIP session (%s)...\n", session->account.username ? session->account.username : "unregistered user");
927
                if(session->stack != NULL) {
928
                        /* Shutdown the NUA: this will remove the session later on */
929
                        nua_shutdown(session->stack->s_nua);
930
                } else {
931
                        /* No stack, maybe never registered: cleaning up and removing the session is done in a lazy way */
932
                        old_sessions = g_list_append(old_sessions, session);
933
                }
934
        }
935
        janus_mutex_unlock(&sessions_mutex);
936
        return;
937
}
938

    
939
json_t *janus_sip_query_session(janus_plugin_session *handle) {
940
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
941
                return NULL;
942
        }
943
        janus_sip_session *session = (janus_sip_session *)handle->plugin_handle;
944
        if(!session) {
945
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
946
                return NULL;
947
        }
948
        /* Provide some generic info, e.g., if we're in a call and with whom */
949
        json_t *info = json_object();
950
        json_object_set_new(info, "username", session->account.username ? json_string(session->account.username) : NULL);
951
        json_object_set_new(info, "display_name", session->account.display_name ? json_string(session->account.display_name) : NULL);
952
        json_object_set_new(info, "user_agent", session->account.user_agent ? json_string(session->account.user_agent) : NULL);
953
        json_object_set_new(info, "identity", session->account.identity ? json_string(session->account.identity) : NULL);
954
        json_object_set_new(info, "registration_status", json_string(janus_sip_registration_status_string(session->account.registration_status)));
955
        json_object_set_new(info, "call_status", json_string(janus_sip_call_status_string(session->status)));
956
        if(session->callee) {
957
                json_object_set_new(info, "callee", json_string(session->callee ? session->callee : "??"));
958
                json_object_set_new(info, "auto-ack", json_string(session->media.autoack ? "yes" : "no"));
959
                json_object_set_new(info, "srtp-required", json_string(session->media.require_srtp ? "yes" : "no"));
960
                json_object_set_new(info, "sdes-local", json_string(session->media.has_srtp_local ? "yes" : "no"));
961
                json_object_set_new(info, "sdes-remote", json_string(session->media.has_srtp_remote ? "yes" : "no"));
962
        }
963
        if(session->arc || session->vrc || session->arc_peer || session->vrc_peer) {
964
                json_t *recording = json_object();
965
                if(session->arc && session->arc->filename)
966
                        json_object_set_new(recording, "audio", json_string(session->arc->filename));
967
                if(session->vrc && session->vrc->filename)
968
                        json_object_set_new(recording, "video", json_string(session->vrc->filename));
969
                if(session->arc_peer && session->arc_peer->filename)
970
                        json_object_set_new(recording, "audio-peer", json_string(session->arc_peer->filename));
971
                if(session->vrc_peer && session->vrc_peer->filename)
972
                        json_object_set_new(recording, "video-peer", json_string(session->vrc_peer->filename));
973
                json_object_set_new(info, "recording", recording);
974
        }
975
        json_object_set_new(info, "destroyed", json_integer(session->destroyed));
976
        return info;
977
}
978

    
979
struct janus_plugin_result *janus_sip_handle_message(janus_plugin_session *handle, char *transaction, json_t *message, json_t *jsep) {
980
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
981
                return janus_plugin_result_new(JANUS_PLUGIN_ERROR, g_atomic_int_get(&stopping) ? "Shutting down" : "Plugin not initialized", NULL);
982
        janus_sip_message *msg = g_malloc0(sizeof(janus_sip_message));
983
        msg->handle = handle;
984
        msg->transaction = transaction;
985
        msg->message = message;
986
        msg->jsep = jsep;
987
        g_async_queue_push(messages, msg);
988

    
989
        /* All the requests to this plugin are handled asynchronously */
990
        return janus_plugin_result_new(JANUS_PLUGIN_OK_WAIT, NULL, NULL);
991
}
992

    
993
void janus_sip_setup_media(janus_plugin_session *handle) {
994
        JANUS_LOG(LOG_INFO, "WebRTC media is now available\n");
995
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
996
                return;
997
        janus_sip_session *session = (janus_sip_session *)handle->plugin_handle;
998
        if(!session) {
999
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1000
                return;
1001
        }
1002
        if(session->destroyed)
1003
                return;
1004
        g_atomic_int_set(&session->hangingup, 0);
1005
        /* TODO Only relay RTP/RTCP when we get this event */
1006
}
1007

    
1008
void janus_sip_incoming_rtp(janus_plugin_session *handle, int video, char *buf, int len) {
1009
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
1010
                return;
1011
        if(gateway) {
1012
                /* Honour the audio/video active flags */
1013
                janus_sip_session *session = (janus_sip_session *)handle->plugin_handle;
1014
                if(!session || session->destroyed) {
1015
                        JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1016
                        return;
1017
                }
1018
                if(session->status != janus_sip_call_status_incall)
1019
                        return;
1020
                /* Forward to our SIP peer */
1021
                if(video) {
1022
                        if(session->media.video_ssrc == 0) {
1023
                                rtp_header *header = (rtp_header *)buf;
1024
                                session->media.video_ssrc = ntohl(header->ssrc);
1025
                                JANUS_LOG(LOG_VERB, "Got SIP video SSRC: %"SCNu32"\n", session->media.video_ssrc);
1026
                        }
1027
                        if(session->media.has_video && session->media.video_rtp_fd) {
1028
                                /* Save the frame if we're recording */
1029
                                janus_recorder_save_frame(session->vrc, buf, len);
1030
                                /* Is SRTP involved? */
1031
                                if(session->media.has_srtp_local) {
1032
                                        char sbuf[2048];
1033
                                        memcpy(&sbuf, buf, len);
1034
                                        int protected = len;
1035
                                        int res = srtp_protect(session->media.video_srtp_out, &sbuf, &protected);
1036
                                        if(res != err_status_ok) {
1037
                                                rtp_header *header = (rtp_header *)&sbuf;
1038
                                                guint32 timestamp = ntohl(header->timestamp);
1039
                                                guint16 seq = ntohs(header->seq_number);
1040
                                                JANUS_LOG(LOG_ERR, "[SIP-%s] Video SRTP protect error... %s (len=%d-->%d, ts=%"SCNu32", seq=%"SCNu16")...\n",
1041
                                                        session->account.username, janus_sip_get_srtp_error(res), len, protected, timestamp, seq);
1042
                                        } else {
1043
                                                /* Forward the frame to the peer */
1044
                                                send(session->media.video_rtp_fd, sbuf, protected, 0);
1045
                                        }
1046
                                } else {
1047
                                        /* Forward the frame to the peer */
1048
                                        send(session->media.video_rtp_fd, buf, len, 0);
1049
                                }
1050
                        }
1051
                } else {
1052
                        if(session->media.audio_ssrc == 0) {
1053
                                rtp_header *header = (rtp_header *)buf;
1054
                                session->media.audio_ssrc = ntohl(header->ssrc);
1055
                                JANUS_LOG(LOG_VERB, "Got SIP audio SSRC: %"SCNu32"\n", session->media.audio_ssrc);
1056
                        }
1057
                        if(session->media.has_audio && session->media.audio_rtp_fd) {
1058
                                /* Save the frame if we're recording */
1059
                                janus_recorder_save_frame(session->arc, buf, len);
1060
                                /* Is SRTP involved? */
1061
                                if(session->media.has_srtp_local) {
1062
                                        char sbuf[2048];
1063
                                        memcpy(&sbuf, buf, len);
1064
                                        int protected = len;
1065
                                        int res = srtp_protect(session->media.audio_srtp_out, &sbuf, &protected);
1066
                                        if(res != err_status_ok) {
1067
                                                rtp_header *header = (rtp_header *)&sbuf;
1068
                                                guint32 timestamp = ntohl(header->timestamp);
1069
                                                guint16 seq = ntohs(header->seq_number);
1070
                                                JANUS_LOG(LOG_ERR, "[SIP-%s] Audio SRTP protect error... %s (len=%d-->%d, ts=%"SCNu32", seq=%"SCNu16")...\n",
1071
                                                        session->account.username, janus_sip_get_srtp_error(res), len, protected, timestamp, seq);
1072
                                        } else {
1073
                                                /* Forward the frame to the peer */
1074
                                                send(session->media.audio_rtp_fd, sbuf, protected, 0);
1075
                                        }
1076
                                } else {
1077
                                        /* Forward the frame to the peer */
1078
                                        send(session->media.audio_rtp_fd, buf, len, 0);
1079
                                }
1080
                        }
1081
                }
1082
        }
1083
}
1084

    
1085
void janus_sip_incoming_rtcp(janus_plugin_session *handle, int video, char *buf, int len) {
1086
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
1087
                return;
1088
        if(gateway) {
1089
                janus_sip_session *session = (janus_sip_session *)handle->plugin_handle;
1090
                if(!session || session->destroyed) {
1091
                        JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1092
                        return;
1093
                }
1094
                if(session->status != janus_sip_call_status_incall)
1095
                        return;
1096
                /* Forward to our SIP peer */
1097
                if(video) {
1098
                        if(session->media.has_video && session->media.video_rtcp_fd) {
1099
                                /* Is SRTP involved? */
1100
                                if(session->media.has_srtp_local) {
1101
                                        char sbuf[2048];
1102
                                        memcpy(&sbuf, buf, len);
1103
                                        int protected = len;
1104
                                        int res = srtp_protect_rtcp(session->media.video_srtp_out, &sbuf, &protected);
1105
                                        if(res != err_status_ok) {
1106
                                                JANUS_LOG(LOG_ERR, "[SIP-%s] Video SRTCP protect error... %s (len=%d-->%d)...\n",
1107
                                                        session->account.username, janus_sip_get_srtp_error(res), len, protected);
1108
                                        } else {
1109
                                                /* Fix SSRCs as the gateway does */
1110
                                                JANUS_LOG(LOG_HUGE, "[SIP] Fixing SSRCs (local %u, peer %u)\n",
1111
                                                        session->media.video_ssrc, session->media.video_ssrc_peer);
1112
                                                janus_rtcp_fix_ssrc(NULL, (char *)buf, len, 1, session->media.video_ssrc, session->media.video_ssrc_peer);
1113
                                                /* Forward the message to the peer */
1114
                                                send(session->media.video_rtcp_fd, sbuf, protected, 0);
1115
                                        }
1116
                                } else {
1117
                                        /* Fix SSRCs as the gateway does */
1118
                                        JANUS_LOG(LOG_HUGE, "[SIP] Fixing SSRCs (local %u, peer %u)\n",
1119
                                                session->media.video_ssrc, session->media.video_ssrc_peer);
1120
                                        janus_rtcp_fix_ssrc(NULL, (char *)buf, len, 1, session->media.video_ssrc, session->media.video_ssrc_peer);
1121
                                        /* Forward the message to the peer */
1122
                                        send(session->media.video_rtcp_fd, buf, len, 0);
1123
                                }
1124
                        }
1125
                } else {
1126
                        if(session->media.has_audio && session->media.audio_rtcp_fd) {
1127
                                /* Is SRTP involved? */
1128
                                if(session->media.has_srtp_local) {
1129
                                        char sbuf[2048];
1130
                                        memcpy(&sbuf, buf, len);
1131
                                        int protected = len;
1132
                                        int res = srtp_protect_rtcp(session->media.audio_srtp_out, &sbuf, &protected);
1133
                                        if(res != err_status_ok) {
1134
                                                JANUS_LOG(LOG_ERR, "[SIP-%s] Audio SRTCP protect error... %s (len=%d-->%d)...\n",
1135
                                                        session->account.username, janus_sip_get_srtp_error(res), len, protected);
1136
                                        } else {
1137
                                                /* Fix SSRCs as the gateway does */
1138
                                                JANUS_LOG(LOG_HUGE, "[SIP] Fixing SSRCs (local %u, peer %u)\n",
1139
                                                        session->media.audio_ssrc, session->media.audio_ssrc_peer);
1140
                                                janus_rtcp_fix_ssrc(NULL, (char *)buf, len, 1, session->media.audio_ssrc, session->media.audio_ssrc_peer);
1141
                                                /* Forward the message to the peer */
1142
                                                send(session->media.audio_rtcp_fd, sbuf, protected, 0);
1143
                                        }
1144
                                } else {
1145
                                        /* Fix SSRCs as the gateway does */
1146
                                        JANUS_LOG(LOG_HUGE, "[SIP] Fixing SSRCs (local %u, peer %u)\n",
1147
                                                session->media.audio_ssrc, session->media.audio_ssrc_peer);
1148
                                        janus_rtcp_fix_ssrc(NULL, (char *)buf, len, 1, session->media.audio_ssrc, session->media.audio_ssrc_peer);
1149
                                        /* Forward the message to the peer */
1150
                                        send(session->media.audio_rtcp_fd, buf, len, 0);
1151
                                }
1152
                        }
1153
                }
1154
        }
1155
}
1156

    
1157
void janus_sip_hangup_media(janus_plugin_session *handle) {
1158
        JANUS_LOG(LOG_INFO, "No WebRTC media anymore\n");
1159
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
1160
                return;
1161
        janus_sip_session *session = (janus_sip_session *)handle->plugin_handle;
1162
        if(!session) {
1163
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1164
                return;
1165
        }
1166
        if(session->destroyed)
1167
                return;
1168
        if(g_atomic_int_add(&session->hangingup, 1))
1169
                return;
1170
        if(!(session->status == janus_sip_call_status_inviting ||
1171
                 session->status == janus_sip_call_status_invited ||
1172
                 session->status == janus_sip_call_status_incall))
1173
                return;
1174
        /* Get rid of the recorders, if available */
1175
        janus_mutex_lock(&session->rec_mutex);
1176
        if(session->arc) {
1177
                janus_recorder_close(session->arc);
1178
                JANUS_LOG(LOG_INFO, "Closed user's audio recording %s\n", session->arc->filename ? session->arc->filename : "??");
1179
                janus_recorder_free(session->arc);
1180
        }
1181
        session->arc = NULL;
1182
        if(session->arc_peer) {
1183
                janus_recorder_close(session->arc_peer);
1184
                JANUS_LOG(LOG_INFO, "Closed peer's audio recording %s\n", session->arc_peer->filename ? session->arc_peer->filename : "??");
1185
                janus_recorder_free(session->arc_peer);
1186
        }
1187
        session->arc_peer = NULL;
1188
        if(session->vrc) {
1189
                janus_recorder_close(session->vrc);
1190
                JANUS_LOG(LOG_INFO, "Closed user's video recording %s\n", session->vrc->filename ? session->vrc->filename : "??");
1191
                janus_recorder_free(session->vrc);
1192
        }
1193
        session->vrc = NULL;
1194
        if(session->vrc_peer) {
1195
                janus_recorder_close(session->vrc_peer);
1196
                JANUS_LOG(LOG_INFO, "Closed peer's video recording %s\n", session->vrc_peer->filename ? session->vrc_peer->filename : "??");
1197
                janus_recorder_free(session->vrc_peer);
1198
        }
1199
        session->vrc_peer = NULL;
1200
        janus_mutex_unlock(&session->rec_mutex);
1201
        if (session->raw_media != NULL) {
1202
                sdp_parser_free(session->raw_media);
1203
                session->raw_media = NULL;
1204
        }
1205
        /* FIXME Simulate a "hangup" coming from the browser */
1206
        janus_sip_message *msg = g_malloc0(sizeof(janus_sip_message));
1207
        msg->handle = handle;
1208
        msg->message = json_pack("{ss}", "request", "hangup");
1209
        msg->transaction = NULL;
1210
        msg->jsep = NULL;
1211
        g_async_queue_push(messages, msg);
1212
}
1213

    
1214
/* Thread to handle incoming messages */
1215
static void *janus_sip_handler(void *data) {
1216
        JANUS_LOG(LOG_VERB, "Joining SIP handler thread\n");
1217
        janus_sip_message *msg = NULL;
1218
        int error_code = 0;
1219
        char error_cause[512];
1220
        json_t *root = NULL;
1221
        while(g_atomic_int_get(&initialized) && !g_atomic_int_get(&stopping)) {
1222
                msg = g_async_queue_pop(messages);
1223
                if(msg == NULL)
1224
                        continue;
1225
                if(msg == &exit_message)
1226
                        break;
1227
                if(msg->handle == NULL) {
1228
                        janus_sip_message_free(msg);
1229
                        continue;
1230
                }
1231
                janus_sip_session *session = NULL;
1232
                janus_mutex_lock(&sessions_mutex);
1233
                if(g_hash_table_lookup(sessions, msg->handle) != NULL ) {
1234
                        session = (janus_sip_session *)msg->handle->plugin_handle;
1235
                }
1236
                janus_mutex_unlock(&sessions_mutex);
1237
                if(!session) {
1238
                        JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1239
                        janus_sip_message_free(msg);
1240
                        continue;
1241
                }
1242
                if(session->destroyed) {
1243
                        janus_sip_message_free(msg);
1244
                        continue;
1245
                }
1246
                /* Handle request */
1247
                error_code = 0;
1248
                root = msg->message;
1249
                if(msg->message == NULL) {
1250
                        JANUS_LOG(LOG_ERR, "No message??\n");
1251
                        error_code = JANUS_SIP_ERROR_NO_MESSAGE;
1252
                        g_snprintf(error_cause, 512, "%s", "No message??");
1253
                        goto error;
1254
                }
1255
                if(!json_is_object(root)) {
1256
                        JANUS_LOG(LOG_ERR, "JSON error: not an object\n");
1257
                        error_code = JANUS_SIP_ERROR_INVALID_JSON;
1258
                        g_snprintf(error_cause, 512, "JSON error: not an object");
1259
                        goto error;
1260
                }
1261
                JANUS_VALIDATE_JSON_OBJECT(root, request_parameters,
1262
                        error_code, error_cause, TRUE,
1263
                        JANUS_SIP_ERROR_MISSING_ELEMENT, JANUS_SIP_ERROR_INVALID_ELEMENT);
1264
                if(error_code != 0)
1265
                        goto error;
1266
                json_t *request = json_object_get(root, "request");
1267
                const char *request_text = json_string_value(request);
1268
                json_t *result = NULL;
1269

    
1270
                if(!strcasecmp(request_text, "register")) {
1271
                        /* Send a REGISTER */
1272
                        if(session->account.registration_status > janus_sip_registration_status_unregistered) {
1273
                                JANUS_LOG(LOG_ERR, "Already registered (%s)\n", session->account.username);
1274
                                error_code = JANUS_SIP_ERROR_ALREADY_REGISTERED;
1275
                                g_snprintf(error_cause, 512, "Already registered (%s)", session->account.username);
1276
                                goto error;
1277
                        }
1278

    
1279
                        /* Cleanup old values */
1280
                        if(session->account.identity != NULL)
1281
                                g_free(session->account.identity);
1282
                        session->account.identity = NULL;
1283
                        session->account.sips = TRUE;
1284
                        if(session->account.username != NULL)
1285
                                g_free(session->account.username);
1286
                        session->account.username = NULL;
1287
                        if(session->account.display_name != NULL)
1288
                                g_free(session->account.display_name);
1289
                        session->account.display_name = NULL;
1290
                        if(session->account.authuser != NULL)
1291
                                g_free(session->account.authuser);
1292
                        session->account.authuser = NULL;
1293
                        if(session->account.secret != NULL)
1294
                                g_free(session->account.secret);
1295
                        session->account.secret = NULL;
1296
                        session->account.secret_type = janus_sip_secret_type_unknown;
1297
                        if(session->account.proxy != NULL)
1298
                                g_free(session->account.proxy);
1299
                        session->account.proxy = NULL;
1300
                        if(session->account.user_agent != NULL)
1301
                                g_free(session->account.user_agent);
1302
                        session->account.user_agent = NULL;
1303
                        session->account.registration_status = janus_sip_registration_status_unregistered;
1304

    
1305
                        gboolean guest = FALSE;
1306
                        JANUS_VALIDATE_JSON_OBJECT(root, register_parameters,
1307
                                error_code, error_cause, TRUE,
1308
                                JANUS_SIP_ERROR_MISSING_ELEMENT, JANUS_SIP_ERROR_INVALID_ELEMENT);
1309
                        if(error_code != 0)
1310
                                goto error;
1311
                        json_t *type = json_object_get(root, "type");
1312
                        if(type != NULL) {
1313
                                const char *type_text = json_string_value(type);
1314
                                if(!strcmp(type_text, "guest")) {
1315
                                        JANUS_LOG(LOG_INFO, "Registering as a guest\n");
1316
                                        guest = TRUE;
1317
                                } else {
1318
                                        JANUS_LOG(LOG_WARN, "Unknown type '%s', ignoring...\n", type_text);
1319
                                }
1320
                        }
1321

    
1322
                        gboolean send_register = TRUE;
1323
                        json_t *do_register = json_object_get(root, "send_register");
1324
                        if(do_register != NULL) {
1325
                                if(guest) {
1326
                                        JANUS_LOG(LOG_ERR, "Conflicting elements: send_register cannot be true if guest is true\n");
1327
                                        error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
1328
                                        g_snprintf(error_cause, 512, "Conflicting elements: send_register cannot be true if guest is true");
1329
                                        goto error;
1330
                                }
1331
                                send_register = json_is_true(do_register);
1332
                        }
1333

    
1334
                        gboolean sips = TRUE;
1335
                        json_t *do_sips = json_object_get(root, "sips");
1336
                        if(do_sips != NULL) {
1337
                                sips = json_is_true(do_sips);
1338
                        }
1339

    
1340
                        /* Parse address */
1341
                        json_t *proxy = json_object_get(root, "proxy");
1342
                        const char *proxy_text = NULL;
1343

    
1344
                        if (proxy && !json_is_null(proxy)) {
1345
                                /* Has to be validated separately because it could be null */
1346
                                JANUS_VALIDATE_JSON_OBJECT(root, proxy_parameters,
1347
                                        error_code, error_cause, TRUE,
1348
                                        JANUS_SIP_ERROR_MISSING_ELEMENT, JANUS_SIP_ERROR_INVALID_ELEMENT);
1349
                                if(error_code != 0)
1350
                                        goto error;
1351
                                proxy_text = json_string_value(proxy);
1352
                                janus_sip_uri_t proxy_uri;
1353
                                if (janus_sip_parse_proxy_uri(&proxy_uri, proxy_text) < 0) {
1354
                                        JANUS_LOG(LOG_ERR, "Invalid proxy address %s\n", proxy_text);
1355
                                        error_code = JANUS_SIP_ERROR_INVALID_ADDRESS;
1356
                                        g_snprintf(error_cause, 512, "Invalid proxy address %s\n", proxy_text);
1357
                                        goto error;
1358
                                }
1359
                        }
1360

    
1361
                        /* Parse register TTL */
1362
                        int ttl = register_ttl;
1363
                        json_t *reg_ttl = json_object_get(root, "register_ttl");
1364
                        if (reg_ttl && json_is_integer(reg_ttl))
1365
                                ttl = json_integer_value(reg_ttl);
1366
                        if (ttl <= 0)
1367
                                ttl = JANUS_DEFAULT_REGISTER_TTL;
1368

    
1369
                        /* Parse display name */
1370
                        const char* display_name_text = NULL;
1371
                        json_t *display_name = json_object_get(root, "display_name");
1372
                        if (display_name && json_is_string(display_name))
1373
                                display_name_text = json_string_value(display_name);
1374

    
1375
                        /* Parse user agent */
1376
                        const char* user_agent_text = NULL;
1377
                        json_t *user_agent = json_object_get(root, "user_agent");
1378
                        if (user_agent && json_is_string(user_agent))
1379
                                user_agent_text = json_string_value(user_agent);
1380

    
1381
                        /* Now the user part, if needed */
1382
                        json_t *username = json_object_get(root, "username");
1383
                        if(!guest && !username) {
1384
                                /* The username is mandatory if we're not registering as guests */
1385
                                JANUS_LOG(LOG_ERR, "Missing element (username)\n");
1386
                                error_code = JANUS_SIP_ERROR_MISSING_ELEMENT;
1387
                                g_snprintf(error_cause, 512, "Missing element (username)");
1388
                                goto error;
1389
                        }
1390
                        const char *username_text = NULL;
1391
                        janus_sip_uri_t username_uri;
1392
                        char user_id[256];
1393
                        if(username) {
1394
                                /* Parse address */
1395
                                username_text = json_string_value(username);
1396
                                if (janus_sip_parse_uri(&username_uri, username_text) < 0) {
1397
                                        JANUS_LOG(LOG_ERR, "Invalid user address %s\n", username_text);
1398
                                        error_code = JANUS_SIP_ERROR_INVALID_ADDRESS;
1399
                                        g_snprintf(error_cause, 512, "Invalid user address %s\n", username_text);
1400
                                        goto error;
1401
                                }
1402
                                g_strlcpy(user_id, username_uri.url->url_user, sizeof(user_id));
1403
                        }
1404
                        if(guest) {
1405
                                /* Not needed, we can stop here: just pick a random username if it wasn't provided and say we're registered */
1406
                                if(!username)
1407
                                        g_snprintf(user_id, 255, "janus-sip-%"SCNu32"", janus_random_uint32());
1408
                                JANUS_LOG(LOG_INFO, "Guest will have username %s\n", user_id);
1409
                                send_register = FALSE;
1410
                        } else {
1411
                                json_t *secret = json_object_get(root, "secret");
1412
                                json_t *ha1_secret = json_object_get(root, "ha1_secret");
1413
                                json_t *authuser = json_object_get(root, "authuser");
1414
                                if(!secret && !ha1_secret) {
1415
                                        JANUS_LOG(LOG_ERR, "Missing element (secret or ha1_secret)\n");
1416
                                        error_code = JANUS_SIP_ERROR_MISSING_ELEMENT;
1417
                                        g_snprintf(error_cause, 512, "Missing element (secret or ha1_secret)");
1418
                                        goto error;
1419
                                }
1420
                                if(secret && ha1_secret) {
1421
                                        JANUS_LOG(LOG_ERR, "Conflicting elements specified (secret and ha1_secret)\n");
1422
                                        error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
1423
                                        g_snprintf(error_cause, 512, "Conflicting elements specified (secret and ha1_secret)");
1424
                                        goto error;
1425
                                }
1426
                                const char *secret_text;
1427
                                if(secret) {
1428
                                        secret_text = json_string_value(secret);
1429
                                        session->account.secret = g_strdup(secret_text);
1430
                                        session->account.secret_type = janus_sip_secret_type_plaintext;
1431
                                } else {
1432
                                        secret_text = json_string_value(ha1_secret);
1433
                                        session->account.secret = g_strdup(secret_text);
1434
                                        session->account.secret_type = janus_sip_secret_type_hashed;
1435
                                }
1436
                                if (authuser) {
1437
                                        const char *authuser_text;
1438
                                        authuser_text = json_string_value(authuser);
1439
                                        session->account.authuser = g_strdup(authuser_text);
1440
                                } else {
1441
                                        session->account.authuser = g_strdup(user_id);
1442
                                }
1443
                                /* Got the values, try registering now */
1444
                                JANUS_LOG(LOG_VERB, "Registering user %s (secret %s) @ %s through %s\n",
1445
                                        username_text, secret_text, username_uri.url->url_host, proxy_text != NULL ? proxy_text : "(null)");
1446
                        }
1447

    
1448
                        session->account.identity = g_strdup(username_text);
1449
                        session->account.sips = sips;
1450
                        session->account.username = g_strdup(user_id);
1451
                        if (display_name_text) {
1452
                                session->account.display_name = g_strdup(display_name_text);
1453
                        }
1454
                        if (user_agent_text) {
1455
                                session->account.user_agent = g_strdup(user_agent_text);
1456
                        }
1457
                        if (proxy_text) {
1458
                                session->account.proxy = g_strdup(proxy_text);
1459
                        }
1460

    
1461
                        session->account.registration_status = janus_sip_registration_status_registering;
1462
                        if(session->stack == NULL) {
1463
                                /* Start the thread first */
1464
                                GError *error = NULL;
1465
                                char tname[16];
1466
                                g_snprintf(tname, sizeof(tname), "sip %s", session->account.username);
1467
                                g_thread_try_new(tname, janus_sip_sofia_thread, session, &error);
1468
                                if(error != NULL) {
1469
                                        JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the SIP Sofia thread...\n", error->code, error->message ? error->message : "??");
1470
                                        error_code = JANUS_SIP_ERROR_UNKNOWN_ERROR;
1471
                                        g_snprintf(error_cause, 512, "Got error %d (%s) trying to launch the SIP Sofia thread", error->code, error->message ? error->message : "??");
1472
                                        goto error;
1473
                                }
1474
                                long int timeout = 0;
1475
                                while(session->stack == NULL || session->stack->s_nua == NULL) {
1476
                                        g_usleep(100000);
1477
                                        timeout += 100000;
1478
                                        if(timeout >= 2000000) {
1479
                                                break;
1480
                                        }
1481
                                }
1482
                                if(timeout >= 2000000) {
1483
                                        JANUS_LOG(LOG_ERR, "Two seconds passed and still no NUA, problems with the thread?\n");
1484
                                        error_code = JANUS_SIP_ERROR_UNKNOWN_ERROR;
1485
                                        g_snprintf(error_cause, 512, "Two seconds passed and still no NUA, problems with the thread?");
1486
                                        goto error;
1487
                                }
1488
                        }
1489
                        if(session->stack->s_nh_r != NULL) {
1490
                                nua_handle_destroy(session->stack->s_nh_r);
1491
                                session->stack->s_nh_r = NULL;
1492
                        }
1493

    
1494
                        if (send_register) {
1495
                                session->stack->s_nh_r = nua_handle(session->stack->s_nua, session, TAG_END());
1496
                                if(session->stack->s_nh_r == NULL) {
1497
                                        JANUS_LOG(LOG_ERR, "NUA Handle for REGISTER still null??\n");
1498
                                        error_code = JANUS_SIP_ERROR_LIBSOFIA_ERROR;
1499
                                        g_snprintf(error_cause, 512, "Invalid NUA Handle");
1500
                                        goto error;
1501
                                }
1502
                                char ttl_text[20];
1503
                                g_snprintf(ttl_text, sizeof(ttl_text), "%d", ttl);
1504
                                nua_register(session->stack->s_nh_r,
1505
                                        NUTAG_M_USERNAME(session->account.username),
1506
                                        SIPTAG_FROM_STR(username_text),
1507
                                        SIPTAG_TO_STR(username_text),
1508
                                        SIPTAG_EXPIRES_STR(ttl_text),
1509
                                        NUTAG_PROXY(proxy_text),
1510
                                        TAG_END());
1511
                                result = json_object();
1512
                                json_object_set_new(result, "event", json_string("registering"));
1513
                        } else {
1514
                                JANUS_LOG(LOG_VERB, "Not sending a SIP REGISTER: either send_register was set to false or guest mode was enabled\n");
1515
                                session->account.registration_status = janus_sip_registration_status_disabled;
1516
                                result = json_object();
1517
                                json_object_set_new(result, "event", json_string("registered"));
1518
                                json_object_set_new(result, "username", json_string(session->account.username));
1519
                                json_object_set_new(result, "register_sent", json_false());
1520
                        }
1521
                } else if(!strcasecmp(request_text, "call")) {
1522
                        /* Call another peer */
1523
                        if(session->stack == NULL) {
1524
                                JANUS_LOG(LOG_ERR, "Wrong state (register first)\n");
1525
                                error_code = JANUS_SIP_ERROR_WRONG_STATE;
1526
                                g_snprintf(error_cause, 512, "Wrong state (register first)");
1527
                                goto error;
1528
                        }
1529
                        if(session->status >= janus_sip_call_status_inviting) {
1530
                                JANUS_LOG(LOG_ERR, "Wrong state (already in a call? status=%s)\n", janus_sip_call_status_string(session->status));
1531
                                error_code = JANUS_SIP_ERROR_WRONG_STATE;
1532
                                g_snprintf(error_cause, 512, "Wrong state (already in a call? status=%s)", janus_sip_call_status_string(session->status));
1533
                                goto error;
1534
                        }
1535
                        JANUS_VALIDATE_JSON_OBJECT(root, call_parameters,
1536
                                error_code, error_cause, TRUE,
1537
                                JANUS_SIP_ERROR_MISSING_ELEMENT, JANUS_SIP_ERROR_INVALID_ELEMENT);
1538
                        if(error_code != 0)
1539
                                goto error;
1540
                        json_t *uri = json_object_get(root, "uri");
1541
                        /* Check if we need to ACK manually (e.g., for the Record-Route hack) */
1542
                        json_t *autoack = json_object_get(root, "autoack");
1543
                        gboolean do_autoack = autoack ? json_is_true(autoack) : TRUE;
1544
                        /* Check if the INVITE needs to be enriched with custom headers */
1545
                        char custom_headers[2048];
1546
                        custom_headers[0] = '\0';
1547
                        json_t *headers = json_object_get(root, "headers");
1548
                        if(headers) {
1549
                                if(json_object_size(headers) > 0) {
1550
                                        /* Parse custom headers */
1551
                                        const char *key = NULL;
1552
                                        json_t *value = NULL;
1553
                                        void *iter = json_object_iter(headers);
1554
                                        while(iter != NULL) {
1555
                                                key = json_object_iter_key(iter);
1556
                                                value = json_object_get(headers, key);
1557
                                                if(value == NULL || !json_is_string(value)) {
1558
                                                        JANUS_LOG(LOG_WARN, "Skipping header '%s': value is not a string\n", key);
1559
                                                        iter = json_object_iter_next(headers, iter);
1560
                                                        continue;
1561
                                                }
1562
                                                char h[255];
1563
                                                g_snprintf(h, 255, "%s: %s\r\n", key, json_string_value(value));
1564
                                                JANUS_LOG(LOG_VERB, "Adding custom header, %s", h);
1565
                                                g_strlcat(custom_headers, h, 2048);
1566
                                                iter = json_object_iter_next(headers, iter);
1567
                                        }
1568
                                }
1569
                        }
1570
                        /* SDES-SRTP is disabled by default, let's see if we need to enable it */
1571
                        gboolean offer_srtp = FALSE, require_srtp = FALSE;
1572
                        json_t *srtp = json_object_get(root, "srtp");
1573
                        if(srtp) {
1574
                                const char *srtp_text = json_string_value(srtp);
1575
                                if(!strcasecmp(srtp_text, "sdes_optional")) {
1576
                                        /* Negotiate SDES, but make it optional */
1577
                                        offer_srtp = TRUE;
1578
                                } else if(!strcasecmp(srtp_text, "sdes_mandatory")) {
1579
                                        /* Negotiate SDES, and require it */
1580
                                        offer_srtp = TRUE;
1581
                                        require_srtp = TRUE;
1582
                                } else {
1583
                                        JANUS_LOG(LOG_ERR, "Invalid element (srtp can only be sdes_optional or sdes_mandatory)\n");
1584
                                        error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
1585
                                        g_snprintf(error_cause, 512, "Invalid element (srtp can only be sdes_optional or sdes_mandatory)");
1586
                                        goto error;
1587
                                }
1588
                        }
1589
                        /* Parse address */
1590
                        const char *uri_text = json_string_value(uri);
1591
                        janus_sip_uri_t target_uri;
1592
                        if (janus_sip_parse_uri(&target_uri, uri_text) < 0) {
1593
                                JANUS_LOG(LOG_ERR, "Invalid user address %s\n", uri_text);
1594
                                error_code = JANUS_SIP_ERROR_INVALID_ADDRESS;
1595
                                g_snprintf(error_cause, 512, "Invalid user address %s\n", uri_text);
1596
                                goto error;
1597
                        }
1598
                        /* Any SDP to handle? if not, something's wrong */
1599
                        const char *msg_sdp_type = json_string_value(json_object_get(msg->jsep, "type"));
1600
                        const char *msg_sdp = json_string_value(json_object_get(msg->jsep, "sdp"));
1601
                        if(!msg_sdp) {
1602
                                JANUS_LOG(LOG_ERR, "Missing SDP\n");
1603
                                error_code = JANUS_SIP_ERROR_MISSING_SDP;
1604
                                g_snprintf(error_cause, 512, "Missing SDP");
1605
                                goto error;
1606
                        }
1607
                        if(strstr(msg_sdp, "m=application")) {
1608
                                JANUS_LOG(LOG_ERR, "The SIP plugin does not support DataChannels\n");
1609
                                error_code = JANUS_SIP_ERROR_MISSING_SDP;
1610
                                g_snprintf(error_cause, 512, "The SIP plugin does not support DataChannels");
1611
                                goto error;
1612
                        }
1613
                        JANUS_LOG(LOG_VERB, "%s is calling %s\n", session->account.username, uri_text);
1614
                        JANUS_LOG(LOG_VERB, "This is involving a negotiation (%s) as well:\n%s\n", msg_sdp_type, msg_sdp);
1615
                        /* Clean up SRTP stuff from before first, in case it's still needed */
1616
                        janus_sip_srtp_cleanup(session);
1617
                        session->media.require_srtp = require_srtp;
1618
                        session->media.has_srtp_local = offer_srtp;
1619
                        if(offer_srtp) {
1620
                                JANUS_LOG(LOG_VERB, "Going to negotiate SDES-SRTP (%s)...\n", require_srtp ? "mandatory" : "optional");
1621
                        }
1622
                        /* Parse the SDP we got, manipulate some things, and generate a new one */
1623
                        sdp_parser_t *parser = sdp_parse(session->stack->s_home, msg_sdp, strlen(msg_sdp), 0);
1624
                        sdp_session_t *parsed_sdp = sdp_session(parser);
1625
                        if(!parsed_sdp) {
1626
                                JANUS_LOG(LOG_ERR, "Error parsing SDP");
1627
                                sdp_parser_free(parser);
1628
                                error_code = JANUS_SIP_ERROR_MISSING_SDP;
1629
                                g_snprintf(error_cause, 512, "Error parsing SDP");
1630
                                goto error;
1631
                        }
1632
                        /* Allocate RTP ports and merge them with the anonymized SDP */
1633
                        if(strstr(msg_sdp, "m=audio") && !strstr(msg_sdp, "m=audio 0")) {
1634
                                JANUS_LOG(LOG_VERB, "Going to negotiate audio...\n");
1635
                                session->media.has_audio = 1;        /* FIXME Maybe we need a better way to signal this */
1636
                        }
1637
                        if(strstr(msg_sdp, "m=video") && !strstr(msg_sdp, "m=video 0")) {
1638
                                JANUS_LOG(LOG_VERB, "Going to negotiate video...\n");
1639
                                session->media.has_video = 1;        /* FIXME Maybe we need a better way to signal this */
1640
                        }
1641
                        if(janus_sip_allocate_local_ports(session) < 0) {
1642
                                JANUS_LOG(LOG_ERR, "Could not allocate RTP/RTCP ports\n");
1643
                                sdp_parser_free(parser);
1644
                                error_code = JANUS_SIP_ERROR_IO_ERROR;
1645
                                g_snprintf(error_cause, 512, "Could not allocate RTP/RTCP ports");
1646
                                goto error;
1647
                        }
1648
                        char *sdp = janus_sip_sdp_manipulate(session, parsed_sdp, FALSE);
1649
                        if(sdp == NULL) {
1650
                                JANUS_LOG(LOG_ERR, "Could not allocate RTP/RTCP ports\n");
1651
                                sdp_parser_free(parser);
1652
                                error_code = JANUS_SIP_ERROR_IO_ERROR;
1653
                                g_snprintf(error_cause, 512, "Could not allocate RTP/RTCP ports");
1654
                                goto error;
1655
                        }
1656
                        JANUS_LOG(LOG_VERB, "Prepared SDP for INVITE:\n%s", sdp);
1657
                        /* Prepare the From header */
1658
                        char from_hdr[1024];
1659
                        if (session->account.display_name) {
1660
                                g_snprintf(from_hdr, sizeof(from_hdr), "\"%s\" <%s>", session->account.display_name, session->account.identity);
1661
                        } else {
1662
                                g_snprintf(from_hdr, sizeof(from_hdr), "%s", session->account.identity);
1663
                        }
1664
                        /* Prepare the stack */
1665
                        if(session->stack->s_nh_i != NULL)
1666
                                nua_handle_destroy(session->stack->s_nh_i);
1667
                        session->stack->s_nh_i = nua_handle(session->stack->s_nua, session, TAG_END());
1668
                        if(session->stack->s_nh_i == NULL) {
1669
                                JANUS_LOG(LOG_WARN, "NUA Handle for INVITE still null??\n");
1670
                                g_free(sdp);
1671
                                sdp_parser_free(parser);
1672
                                error_code = JANUS_SIP_ERROR_LIBSOFIA_ERROR;
1673
                                g_snprintf(error_cause, 512, "Invalid NUA Handle");
1674
                                goto error;
1675
                        }
1676
                        g_atomic_int_set(&session->hangingup, 0);
1677
                        session->status = janus_sip_call_status_inviting;
1678
                        /* Send INVITE */
1679
                        session->media.autoack = do_autoack;
1680
                        nua_invite(session->stack->s_nh_i,
1681
                                SIPTAG_FROM_STR(from_hdr),
1682
                                SIPTAG_TO_STR(uri_text),
1683
                                SOATAG_USER_SDP_STR(sdp),
1684
                                NUTAG_PROXY(session->account.proxy),
1685
                                TAG_IF(strlen(custom_headers) > 0, SIPTAG_HEADER_STR(custom_headers)),
1686
                                NUTAG_AUTOANSWER(0),
1687
                                NUTAG_AUTOACK(do_autoack),
1688
                                TAG_END());
1689
                        g_free(sdp);
1690
                        sdp_parser_free(parser);
1691
                        session->callee = g_strdup(uri_text);
1692
                        if(session->transaction)
1693
                                g_free(session->transaction);
1694
                        session->transaction = msg->transaction ? g_strdup(msg->transaction) : NULL;
1695
                        /* Send an ack back */
1696
                        result = json_object();
1697
                        json_object_set_new(result, "event", json_string("calling"));
1698
                } else if(!strcasecmp(request_text, "accept")) {
1699
                        if(session->status != janus_sip_call_status_invited) {
1700
                                JANUS_LOG(LOG_ERR, "Wrong state (not invited? status=%s)\n", janus_sip_call_status_string(session->status));
1701
                                error_code = JANUS_SIP_ERROR_WRONG_STATE;
1702
                                g_snprintf(error_cause, 512, "Wrong state (not invited? status=%s)", janus_sip_call_status_string(session->status));
1703
                                goto error;
1704
                        }
1705
                        if(session->callee == NULL) {
1706
                                JANUS_LOG(LOG_ERR, "Wrong state (no caller?)\n");
1707
                                error_code = JANUS_SIP_ERROR_WRONG_STATE;
1708
                                g_snprintf(error_cause, 512, "Wrong state (no caller?)");
1709
                                goto error;
1710
                        }
1711
                        JANUS_VALIDATE_JSON_OBJECT(root, accept_parameters,
1712
                                error_code, error_cause, TRUE,
1713
                                JANUS_SIP_ERROR_MISSING_ELEMENT, JANUS_SIP_ERROR_INVALID_ELEMENT);
1714
                        if(error_code != 0)
1715
                                goto error;
1716
                        json_t *srtp = json_object_get(root, "srtp");
1717
                        gboolean answer_srtp = FALSE;
1718
                        if(srtp) {
1719
                                const char *srtp_text = json_string_value(srtp);
1720
                                if(!strcasecmp(srtp_text, "sdes_optional")) {
1721
                                        /* Negotiate SDES, but make it optional */
1722
                                        answer_srtp = TRUE;
1723
                                } else if(!strcasecmp(srtp_text, "sdes_mandatory")) {
1724
                                        /* Negotiate SDES, and require it */
1725
                                        answer_srtp = TRUE;
1726
                                        session->media.require_srtp = TRUE;
1727
                                } else {
1728
                                        JANUS_LOG(LOG_ERR, "Invalid element (srtp can only be sdes_optional or sdes_mandatory)\n");
1729
                                        error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
1730
                                        g_snprintf(error_cause, 512, "Invalid element (srtp can only be sdes_optional or sdes_mandatory)");
1731
                                        goto error;
1732
                                }
1733
                        }
1734
                        if(session->media.require_srtp && !session->media.has_srtp_remote) {
1735
                                JANUS_LOG(LOG_ERR, "Can't accept the call: SDES-SRTP required, but caller didn't offer it\n");
1736
                                error_code = JANUS_SIP_ERROR_TOO_STRICT;
1737
                                g_snprintf(error_cause, 512, "Can't accept the call: SDES-SRTP required, but caller didn't offer it");
1738
                                goto error;
1739
                        }
1740
                        answer_srtp = answer_srtp || session->media.has_srtp_remote;
1741
                        /* Any SDP to handle? if not, something's wrong */
1742
                        const char *msg_sdp_type = json_string_value(json_object_get(msg->jsep, "type"));
1743
                        const char *msg_sdp = json_string_value(json_object_get(msg->jsep, "sdp"));
1744
                        if(!msg_sdp) {
1745
                                JANUS_LOG(LOG_ERR, "Missing SDP\n");
1746
                                error_code = JANUS_SIP_ERROR_MISSING_SDP;
1747
                                g_snprintf(error_cause, 512, "Missing SDP");
1748
                                goto error;
1749
                        }
1750
                        /* Accept a call from another peer */
1751
                        JANUS_LOG(LOG_VERB, "We're accepting the call from %s\n", session->callee);
1752
                        JANUS_LOG(LOG_VERB, "This is involving a negotiation (%s) as well:\n%s\n", msg_sdp_type, msg_sdp);
1753
                        session->media.has_srtp_local = answer_srtp;
1754
                        if(answer_srtp) {
1755
                                JANUS_LOG(LOG_VERB, "Going to negotiate SDES-SRTP (%s)...\n", session->media.require_srtp ? "mandatory" : "optional");
1756
                        }
1757
                        /* Parse the SDP we got, manipulate some things, and generate a new one */
1758
                        sdp_parser_t *parser = sdp_parse(session->stack->s_home, msg_sdp, strlen(msg_sdp), 0);
1759
                        sdp_session_t *parsed_sdp = sdp_session(parser);
1760
                        if(!parsed_sdp) {
1761
                                JANUS_LOG(LOG_ERR, "Error parsing SDP");
1762
                                sdp_parser_free(parser);
1763
                                error_code = JANUS_SIP_ERROR_MISSING_SDP;
1764
                                g_snprintf(error_cause, 512, "Error parsing SDP");
1765
                                goto error;
1766
                        }
1767
                        /* Allocate RTP ports and merge them with the anonymized SDP */
1768
                        if(strstr(msg_sdp, "m=audio") && !strstr(msg_sdp, "m=audio 0")) {
1769
                                JANUS_LOG(LOG_VERB, "Going to negotiate audio...\n");
1770
                                session->media.has_audio = 1;        /* FIXME Maybe we need a better way to signal this */
1771
                        }
1772
                        if(strstr(msg_sdp, "m=video") && !strstr(msg_sdp, "m=video 0")) {
1773
                                JANUS_LOG(LOG_VERB, "Going to negotiate video...\n");
1774
                                session->media.has_video = 1;        /* FIXME Maybe we need a better way to signal this */
1775
                        }
1776
                        if(janus_sip_allocate_local_ports(session) < 0) {
1777
                                JANUS_LOG(LOG_ERR, "Could not allocate RTP/RTCP ports\n");
1778
                                sdp_parser_free(parser);
1779
                                error_code = JANUS_SIP_ERROR_IO_ERROR;
1780
                                g_snprintf(error_cause, 512, "Could not allocate RTP/RTCP ports");
1781
                                goto error;
1782
                        }
1783
                        char *sdp = janus_sip_sdp_manipulate(session, parsed_sdp, TRUE);
1784
                        if(sdp == NULL) {
1785
                                JANUS_LOG(LOG_ERR, "Could not allocate RTP/RTCP ports\n");
1786
                                sdp_parser_free(parser);
1787
                                error_code = JANUS_SIP_ERROR_IO_ERROR;
1788
                                g_snprintf(error_cause, 512, "Could not allocate RTP/RTCP ports");
1789
                                goto error;
1790
                        }
1791
                        if(session->media.audio_pt > -1) {
1792
                                session->media.audio_pt_name = janus_get_codec_from_pt(sdp, session->media.audio_pt);
1793
                                JANUS_LOG(LOG_VERB, "Detected audio codec: %d (%s)\n", session->media.audio_pt, session->media.audio_pt_name);
1794
                        }
1795
                        if(session->media.video_pt > -1) {
1796
                                session->media.video_pt_name = janus_get_codec_from_pt(sdp, session->media.video_pt);
1797
                                JANUS_LOG(LOG_VERB, "Detected video codec: %d (%s)\n", session->media.video_pt, session->media.video_pt_name);
1798
                        }
1799
                        JANUS_LOG(LOG_VERB, "Prepared SDP for 200 OK:\n%s", sdp);
1800
                        /* Send 200 OK */
1801
                        g_atomic_int_set(&session->hangingup, 0);
1802
                        session->status = janus_sip_call_status_incall;
1803
                        if(session->stack->s_nh_i == NULL) {
1804
                                JANUS_LOG(LOG_WARN, "NUA Handle for 200 OK still null??\n");
1805
                        }
1806
                        nua_respond(session->stack->s_nh_i,
1807
                                200, sip_status_phrase(200),
1808
                                SOATAG_USER_SDP_STR(sdp),
1809
                                NUTAG_AUTOANSWER(0),
1810
                                TAG_END());
1811
                        g_free(sdp);
1812
                        sdp_parser_free(parser);
1813
                        /* Send an ack back */
1814
                        result = json_object();
1815
                        json_object_set_new(result, "event", json_string("accepted"));
1816
                        /* Start the media */
1817
                        session->media.ready = 1;        /* FIXME Maybe we need a better way to signal this */
1818
                        GError *error = NULL;
1819
                        char tname[16];
1820
                        g_snprintf(tname, sizeof(tname), "siprtp %s", session->account.username);
1821
                        g_thread_try_new(tname, janus_sip_relay_thread, session, &error);
1822
                        if(error != NULL) {
1823
                                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the RTP/RTCP thread...\n", error->code, error->message ? error->message : "??");
1824
                        }
1825
                } else if(!strcasecmp(request_text, "decline")) {
1826
                        /* Reject an incoming call */
1827
                        if(session->status != janus_sip_call_status_invited) {
1828
                                JANUS_LOG(LOG_ERR, "Wrong state (not invited? status=%s)\n", janus_sip_call_status_string(session->status));
1829
                                /* Ignore */
1830
                                janus_sip_message_free(msg);
1831
                                continue;
1832
                                //~ g_snprintf(error_cause, 512, "Wrong state (not in a call?)");
1833
                                //~ goto error;
1834
                        }
1835
                        if(session->callee == NULL) {
1836
                                JANUS_LOG(LOG_ERR, "Wrong state (no callee?)\n");
1837
                                error_code = JANUS_SIP_ERROR_WRONG_STATE;
1838
                                g_snprintf(error_cause, 512, "Wrong state (no callee?)");
1839
                                goto error;
1840
                        }
1841
                        session->status = janus_sip_call_status_closing;
1842
                        if(session->stack->s_nh_i == NULL) {
1843
                                JANUS_LOG(LOG_WARN, "NUA Handle for 200 OK still null??\n");
1844
                        }
1845
                        int response_code = 486;
1846
                        json_t *code_json = json_object_get(root, "code");
1847
                        if (code_json && json_is_integer(code_json))
1848
                                response_code = json_integer_value(code_json);
1849
                        if (response_code <= 399) {
1850
                                JANUS_LOG(LOG_WARN, "Invalid SIP response code specified, using 486 to decline call\n");
1851
                                response_code = 486;
1852
                        }
1853
                        nua_respond(session->stack->s_nh_i, response_code, sip_status_phrase(response_code), TAG_END());
1854
                        g_free(session->callee);
1855
                        session->callee = NULL;
1856
                        /* Notify the operation */
1857
                        result = json_object();
1858
                        json_object_set_new(result, "event", json_string("declining"));
1859
                        json_object_set_new(result, "code", json_integer(response_code));
1860
                } else if(!strcasecmp(request_text, "hangup")) {
1861
                        /* Hangup an ongoing call */
1862
                        if(!(session->status == janus_sip_call_status_inviting || session->status == janus_sip_call_status_incall)) {
1863
                                JANUS_LOG(LOG_ERR, "Wrong state (not in a call? status=%s)\n", janus_sip_call_status_string(session->status));
1864
                                /* Ignore */
1865
                                janus_sip_message_free(msg);
1866
                                continue;
1867
                                //~ g_snprintf(error_cause, 512, "Wrong state (not in a call?)");
1868
                                //~ goto error;
1869
                        }
1870
                        if(session->callee == NULL) {
1871
                                JANUS_LOG(LOG_ERR, "Wrong state (no callee?)\n");
1872
                                error_code = JANUS_SIP_ERROR_WRONG_STATE;
1873
                                g_snprintf(error_cause, 512, "Wrong state (no callee?)");
1874
                                goto error;
1875
                        }
1876
                        session->status = janus_sip_call_status_closing;
1877
                        nua_bye(session->stack->s_nh_i, TAG_END());
1878
                        g_free(session->callee);
1879
                        session->callee = NULL;
1880
                        /* Notify the operation */
1881
                        result = json_object();
1882
                        json_object_set_new(result, "event", json_string("hangingup"));
1883
                } else if(!strcasecmp(request_text, "recording")) {
1884
                        /* Start or stop recording */
1885
                        if(!(session->status == janus_sip_call_status_inviting || session->status == janus_sip_call_status_incall)) {
1886
                                JANUS_LOG(LOG_ERR, "Wrong state (not in a call? status=%s)\n", janus_sip_call_status_string(session->status));
1887
                                g_snprintf(error_cause, 512, "Wrong state (not in a call?)");
1888
                                goto error;
1889
                        }
1890
                        if(session->callee == NULL) {
1891
                                JANUS_LOG(LOG_ERR, "Wrong state (no callee?)\n");
1892
                                error_code = JANUS_SIP_ERROR_WRONG_STATE;
1893
                                g_snprintf(error_cause, 512, "Wrong state (no callee?)");
1894
                                goto error;
1895
                        }
1896
                        JANUS_VALIDATE_JSON_OBJECT(root, recording_parameters,
1897
                                error_code, error_cause, TRUE,
1898
                                JANUS_SIP_ERROR_MISSING_ELEMENT, JANUS_SIP_ERROR_INVALID_ELEMENT);
1899
                        if(error_code != 0)
1900
                                goto error;
1901
                        json_t *action = json_object_get(root, "action");
1902
                        const char *action_text = json_string_value(action);
1903
                        if(strcasecmp(action_text, "start") && strcasecmp(action_text, "stop")) {
1904
                                JANUS_LOG(LOG_ERR, "Invalid action (should be start|stop)\n");
1905
                                error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
1906
                                g_snprintf(error_cause, 512, "Invalid action (should be start|stop)");
1907
                                goto error;
1908
                        }
1909
                        gboolean record_audio = FALSE, record_video = FALSE,        /* No media is recorded by default */
1910
                                record_peer_audio = FALSE, record_peer_video = FALSE;
1911
                        json_t *audio = json_object_get(root, "audio");
1912
                        record_audio = audio ? json_is_true(audio) : FALSE;
1913
                        json_t *video = json_object_get(root, "video");
1914
                        record_video = video ? json_is_true(video) : FALSE;
1915
                        json_t *peer_audio = json_object_get(root, "peer_audio");
1916
                        record_peer_audio = peer_audio ? json_is_true(peer_audio) : FALSE;
1917
                        json_t *peer_video = json_object_get(root, "peer_video");
1918
                        record_peer_video = peer_video ? json_is_true(peer_video) : FALSE;
1919
                        if(!record_audio && !record_video && !record_peer_audio && !record_peer_video) {
1920
                                JANUS_LOG(LOG_ERR, "Invalid request (at least one of audio, video, peer_audio and peer_video should be true)\n");
1921
                                error_code = JANUS_SIP_ERROR_RECORDING_ERROR;
1922
                                g_snprintf(error_cause, 512, "Invalid request (at least one of audio, video, peer_audio and peer_video should be true)");
1923
                                goto error;
1924
                        }
1925
                        json_t *recfile = json_object_get(root, "filename");
1926
                        const char *recording_base = json_string_value(recfile);
1927
                        janus_mutex_lock(&session->rec_mutex);
1928
                        if(!strcasecmp(action_text, "start")) {
1929
                                /* Start recording something */
1930
                                char filename[255];
1931
                                gint64 now = janus_get_real_time();
1932
                                if(record_peer_audio || record_peer_video) {
1933
                                        JANUS_LOG(LOG_INFO, "Starting recording of peer's %s (user %s, call %s)\n",
1934
                                                (record_peer_audio && record_peer_video ? "audio and video" : (record_peer_audio ? "audio" : "video")),
1935
                                                session->account.username, session->transaction);
1936
                                        /* Start recording this peer's audio and/or video */
1937
                                        if(record_peer_audio) {
1938
                                                memset(filename, 0, 255);
1939
                                                if(recording_base) {
1940
                                                        /* Use the filename and path we have been provided */
1941
                                                        g_snprintf(filename, 255, "%s-peer-audio", recording_base);
1942
                                                        /* FIXME This only works if offer/answer happened */
1943
                                                        session->arc_peer = janus_recorder_create(NULL, session->media.audio_pt_name, filename);
1944
                                                        if(session->arc_peer == NULL) {
1945
                                                                /* FIXME We should notify the fact the recorder could not be created */
1946
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an audio recording file for this peer!\n");
1947
                                                        }
1948
                                                } else {
1949
                                                        /* Build a filename */
1950
                                                        g_snprintf(filename, 255, "sip-%s-%s-%"SCNi64"-peer-audio",
1951
                                                                session->account.username ? session->account.username : "unknown",
1952
                                                                session->transaction ? session->transaction : "unknown",
1953
                                                                now);
1954
                                                        /* FIXME This only works if offer/answer happened */
1955
                                                        session->arc_peer = janus_recorder_create(NULL, session->media.audio_pt_name, filename);
1956
                                                        if(session->arc_peer == NULL) {
1957
                                                                /* FIXME We should notify the fact the recorder could not be created */
1958
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an audio recording file for this peer!\n");
1959
                                                        }
1960
                                                }
1961
                                        }
1962
                                        if(record_peer_video) {
1963
                                                memset(filename, 0, 255);
1964
                                                if(recording_base) {
1965
                                                        /* Use the filename and path we have been provided */
1966
                                                        g_snprintf(filename, 255, "%s-peer-video", recording_base);
1967
                                                        /* FIXME This only works if offer/answer happened */
1968
                                                        session->vrc_peer = janus_recorder_create(NULL, session->media.video_pt_name, filename);
1969
                                                        if(session->vrc_peer == NULL) {
1970
                                                                /* FIXME We should notify the fact the recorder could not be created */
1971
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an video recording file for this peer!\n");
1972
                                                        }
1973
                                                } else {
1974
                                                        /* Build a filename */
1975
                                                        g_snprintf(filename, 255, "sip-%s-%s-%"SCNi64"-peer-video",
1976
                                                                session->account.username ? session->account.username : "unknown",
1977
                                                                session->transaction ? session->transaction : "unknown",
1978
                                                                now);
1979
                                                        /* FIXME This only works if offer/answer happened */
1980
                                                        session->vrc_peer = janus_recorder_create(NULL, session->media.video_pt_name, filename);
1981
                                                        if(session->vrc_peer == NULL) {
1982
                                                                /* FIXME We should notify the fact the recorder could not be created */
1983
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an video recording file for this peer!\n");
1984
                                                        }
1985
                                                }
1986
                                                /* TODO We should send a FIR/PLI to this peer... */
1987
                                        }
1988
                                }
1989
                                if(record_audio || record_video) {
1990
                                        /* Start recording the user's audio and/or video */
1991
                                        JANUS_LOG(LOG_INFO, "Starting recording of user's %s (user %s, call %s)\n",
1992
                                                (record_audio && record_video ? "audio and video" : (record_audio ? "audio" : "video")),
1993
                                                session->account.username, session->transaction);
1994
                                        if(record_audio) {
1995
                                                memset(filename, 0, 255);
1996
                                                if(recording_base) {
1997
                                                        /* Use the filename and path we have been provided */
1998
                                                        g_snprintf(filename, 255, "%s-user-audio", recording_base);
1999
                                                        /* FIXME This only works if offer/answer happened */
2000
                                                        session->arc = janus_recorder_create(NULL, session->media.audio_pt_name, filename);
2001
                                                        if(session->arc == NULL) {
2002
                                                                /* FIXME We should notify the fact the recorder could not be created */
2003
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an audio recording file for this peer!\n");
2004
                                                        }
2005
                                                } else {
2006
                                                        /* Build a filename */
2007
                                                        g_snprintf(filename, 255, "sip-%s-%s-%"SCNi64"-own-audio",
2008
                                                                session->account.username ? session->account.username : "unknown",
2009
                                                                session->transaction ? session->transaction : "unknown",
2010
                                                                now);
2011
                                                        /* FIXME This only works if offer/answer happened */
2012
                                                        session->arc = janus_recorder_create(NULL, session->media.audio_pt_name, filename);
2013
                                                        if(session->arc == NULL) {
2014
                                                                /* FIXME We should notify the fact the recorder could not be created */
2015
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an audio recording file for this peer!\n");
2016
                                                        }
2017
                                                }
2018
                                        }
2019
                                        if(record_video) {
2020
                                                memset(filename, 0, 255);
2021
                                                if(recording_base) {
2022
                                                        /* Use the filename and path we have been provided */
2023
                                                        g_snprintf(filename, 255, "%s-user-video", recording_base);
2024
                                                        /* FIXME This only works if offer/answer happened */
2025
                                                        session->vrc = janus_recorder_create(NULL, session->media.video_pt_name, filename);
2026
                                                        if(session->vrc == NULL) {
2027
                                                                /* FIXME We should notify the fact the recorder could not be created */
2028
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an video recording file for this user!\n");
2029
                                                        }
2030
                                                } else {
2031
                                                        /* Build a filename */
2032
                                                        g_snprintf(filename, 255, "sip-%s-%s-%"SCNi64"-own-video",
2033
                                                                session->account.username ? session->account.username : "unknown",
2034
                                                                session->transaction ? session->transaction : "unknown",
2035
                                                                now);
2036
                                                        /* FIXME This only works if offer/answer happened */
2037
                                                        session->vrc = janus_recorder_create(NULL, session->media.video_pt_name, filename);
2038
                                                        if(session->vrc == NULL) {
2039
                                                                /* FIXME We should notify the fact the recorder could not be created */
2040
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an video recording file for this user!\n");
2041
                                                        }
2042
                                                }
2043
                                                /* Send a PLI */
2044
                                                JANUS_LOG(LOG_VERB, "Recording video, sending a PLI to kickstart it\n");
2045
                                                char buf[12];
2046
                                                memset(buf, 0, 12);
2047
                                                janus_rtcp_pli((char *)&buf, 12);
2048
                                                gateway->relay_rtcp(session->handle, 1, buf, 12);
2049
                                        }
2050
                                }
2051
                        } else {
2052
                                /* Stop recording something: notice that this never returns an error, even when we were not recording anything */
2053
                                if(record_audio) {
2054
                                        if(session->arc) {
2055
                                                janus_recorder_close(session->arc);
2056
                                                JANUS_LOG(LOG_INFO, "Closed user's audio recording %s\n", session->arc->filename ? session->arc->filename : "??");
2057
                                                janus_recorder_free(session->arc);
2058
                                        }
2059
                                        session->arc = NULL;
2060
                                }
2061
                                if(record_video) {
2062
                                        if(session->vrc) {
2063
                                                janus_recorder_close(session->vrc);
2064
                                                JANUS_LOG(LOG_INFO, "Closed user's video recording %s\n", session->vrc->filename ? session->vrc->filename : "??");
2065
                                                janus_recorder_free(session->vrc);
2066
                                        }
2067
                                        session->vrc = NULL;
2068
                                }
2069
                                if(record_peer_audio) {
2070
                                        if(session->arc_peer) {
2071
                                                janus_recorder_close(session->arc_peer);
2072
                                                JANUS_LOG(LOG_INFO, "Closed peer's audio recording %s\n", session->arc_peer->filename ? session->arc_peer->filename : "??");
2073
                                                janus_recorder_free(session->arc_peer);
2074
                                        }
2075
                                        session->arc_peer = NULL;
2076
                                }
2077
                                if(record_peer_video) {
2078
                                        if(session->vrc_peer) {
2079
                                                janus_recorder_close(session->vrc_peer);
2080
                                                JANUS_LOG(LOG_INFO, "Closed peer's video recording %s\n", session->vrc_peer->filename ? session->vrc_peer->filename : "??");
2081
                                                janus_recorder_free(session->vrc_peer);
2082
                                        }
2083
                                        session->vrc_peer = NULL;
2084
                                }
2085
                        }
2086
                        janus_mutex_unlock(&session->rec_mutex);
2087
                        /* Notify the result */
2088
                        result = json_object();
2089
                        json_object_set_new(result, "event", json_string("recordingupdated"));
2090
                } else if(!strcasecmp(request_text, "dtmf_info")) {
2091
                        /* Send DMTF tones using SIP INFO
2092
                         * (https://tools.ietf.org/html/draft-kaplan-dispatch-info-dtmf-package-00)
2093
                         */
2094
                        if(!(session->status == janus_sip_call_status_inviting || session->status == janus_sip_call_status_incall)) {
2095
                                JANUS_LOG(LOG_ERR, "Wrong state (not in a call? status=%s)\n", janus_sip_call_status_string(session->status));
2096
                                g_snprintf(error_cause, 512, "Wrong state (not in a call?)");
2097
                                goto error;
2098
                        }
2099
                        if(session->callee == NULL) {
2100
                                JANUS_LOG(LOG_ERR, "Wrong state (no callee?)\n");
2101
                                error_code = JANUS_SIP_ERROR_WRONG_STATE;
2102
                                g_snprintf(error_cause, 512, "Wrong state (no callee?)");
2103
                                goto error;
2104
                        }
2105
                        JANUS_VALIDATE_JSON_OBJECT(root, dtmf_info_parameters,
2106
                                error_code, error_cause, TRUE,
2107
                                JANUS_SIP_ERROR_MISSING_ELEMENT, JANUS_SIP_ERROR_INVALID_ELEMENT);
2108
                        if(error_code != 0)
2109
                                goto error;
2110
                        json_t *digit = json_object_get(root, "digit");
2111
                        const char *digit_text = json_string_value(digit);
2112
                        if(strlen(digit_text) != 1) {
2113
                                JANUS_LOG(LOG_ERR, "Invalid element (digit should be one character))\n");
2114
                                error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
2115
                                g_snprintf(error_cause, 512, "Invalid element (digit should be one character)");
2116
                                goto error;
2117
                        }
2118
                        int duration_ms = 0;
2119
                        json_t *duration = json_object_get(root, "duration");
2120
                        duration_ms = duration ? json_integer_value(duration) : 0;
2121
                        if (duration_ms <= 0 || duration_ms > 5000) {
2122
                                duration_ms = 160; /* default value */
2123
                        }
2124

    
2125
                        char payload[64];
2126
                        g_snprintf(payload, sizeof(payload), "Signal=%s\r\nDuration=%d", digit_text, duration_ms);
2127
                        nua_info(session->stack->s_nh_i,
2128
                                SIPTAG_CONTENT_TYPE_STR("application/dtmf-relay"),
2129
                                SIPTAG_PAYLOAD_STR(payload),
2130
                                TAG_END());
2131
                } else {
2132
                        JANUS_LOG(LOG_ERR, "Unknown request (%s)\n", request_text);
2133
                        error_code = JANUS_SIP_ERROR_INVALID_REQUEST;
2134
                        g_snprintf(error_cause, 512, "Unknown request (%s)", request_text);
2135
                        goto error;
2136
                }
2137

    
2138
                /* Prepare JSON event */
2139
                json_t *event = json_object();
2140
                json_object_set_new(event, "sip", json_string("event"));
2141
                if(result != NULL)
2142
                        json_object_set_new(event, "result", result);
2143
                int ret = gateway->push_event(msg->handle, &janus_sip_plugin, msg->transaction, event, NULL);
2144
                JANUS_LOG(LOG_VERB, "  >> Pushing event: %d (%s)\n", ret, janus_get_api_error(ret));
2145
                json_decref(event);
2146
                janus_sip_message_free(msg);
2147
                continue;
2148

    
2149
error:
2150
                {
2151
                        /* Prepare JSON error event */
2152
                        json_t *event = json_object();
2153
                        json_object_set_new(event, "sip", json_string("event"));
2154
                        json_object_set_new(event, "error_code", json_integer(error_code));
2155
                        json_object_set_new(event, "error", json_string(error_cause));
2156
                        int ret = gateway->push_event(msg->handle, &janus_sip_plugin, msg->transaction, event, NULL);
2157
                        JANUS_LOG(LOG_VERB, "  >> Pushing event: %d (%s)\n", ret, janus_get_api_error(ret));
2158
                        json_decref(event);
2159
                        janus_sip_message_free(msg);
2160
                }
2161
        }
2162
        JANUS_LOG(LOG_VERB, "Leaving SIP handler thread\n");
2163
        return NULL;
2164
}
2165

    
2166

    
2167
/* Sofia callbacks */
2168
void janus_sip_sofia_callback(nua_event_t event, int status, char const *phrase, nua_t *nua, nua_magic_t *magic, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tags[])
2169
{
2170
        janus_sip_session *session = (janus_sip_session *)magic;
2171
        ssip_t *ssip = session->stack;
2172
        switch (event) {
2173
        /* Status or Error Indications */
2174
                case nua_i_active:
2175
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2176
                        break;
2177
                case nua_i_error:
2178
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2179
                        break;
2180
                case nua_i_fork:
2181
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2182
                        break;
2183
                case nua_i_media_error:
2184
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2185
                        break;
2186
                case nua_i_subscription:
2187
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2188
                        break;
2189
                case nua_i_state:
2190
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2191
                        tagi_t const *ti = tl_find(tags, nutag_callstate);
2192
                        enum nua_callstate callstate = ti ? ti->t_value : -1;
2193
                        /* There are several call states, but we care about the terminated state in order to send the 'hangup' event
2194
                         * and the proceeding state in order to send the 'proceeding' event so the client can play a ringback tone for
2195
                         * the user since we don't send early media. (assuming this is the right session, of course).
2196
                         * http://sofia-sip.sourceforge.net/refdocs/nua/nua__tag_8h.html#a516dc237722dc8ca4f4aa3524b2b444b
2197
                         */
2198
                        if (callstate == nua_callstate_proceeding &&
2199
                                    (session->stack->s_nh_i == nh || session->stack->s_nh_i == NULL)) {
2200
                                json_t *call = json_object();
2201
                                json_object_set_new(call, "sip", json_string("event"));
2202
                                json_t *calling = json_object();
2203
                                json_object_set_new(calling, "event", json_string("proceeding"));
2204
                                json_object_set_new(calling, "code", json_integer(status));
2205
                                json_object_set_new(call, "result", calling);
2206
                                int ret = gateway->push_event(session->handle, &janus_sip_plugin, session->transaction, call, NULL);
2207
                                JANUS_LOG(LOG_VERB, "  >> Pushing event: %d (%s)\n", ret, janus_get_api_error(ret));
2208
                                json_decref(call);
2209
                        } else if(callstate == nua_callstate_terminated &&
2210
                                        (session->stack->s_nh_i == nh || session->stack->s_nh_i == NULL)) {
2211
                                session->status = janus_sip_call_status_idle;
2212
                                session->stack->s_nh_i = NULL;
2213
                                json_t *call = json_object();
2214
                                json_object_set_new(call, "sip", json_string("event"));
2215
                                json_t *calling = json_object();
2216
                                json_object_set_new(calling, "event", json_string("hangup"));
2217
                                json_object_set_new(calling, "code", json_integer(status));
2218
                                json_object_set_new(calling, "reason", json_string(phrase ? phrase : "???"));
2219
                                json_object_set_new(call, "result", calling);
2220
                                int ret = gateway->push_event(session->handle, &janus_sip_plugin, session->transaction, call, NULL);
2221
                                JANUS_LOG(LOG_VERB, "  >> Pushing event: %d (%s)\n", ret, janus_get_api_error(ret));
2222
                                json_decref(call);
2223
                                /* Get rid of any PeerConnection that may have been set up */
2224
                                if(session->transaction)
2225
                                        g_free(session->transaction);
2226
                                session->transaction = NULL;
2227
                                gateway->close_pc(session->handle);
2228
                        }
2229
                        break;
2230
                case nua_i_terminated:
2231
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2232
                        break;
2233
        /* SIP requests */
2234
                case nua_i_ack:
2235
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2236
                        break;
2237
                case nua_i_outbound:
2238
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2239
                        break;
2240
                case nua_i_bye: {
2241
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2242
                        break;
2243
                }
2244
                case nua_i_cancel: {
2245
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2246
                        break;
2247
                }
2248
                case nua_i_invite: {
2249
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2250
                        if(ssip == NULL) {
2251
                                JANUS_LOG(LOG_ERR, "\tInvalid SIP stack\n");
2252
                                nua_respond(nh, 500, sip_status_phrase(500), TAG_END());
2253
                                break;
2254
                        }
2255
                        if (!sip->sip_payload) {
2256
                                JANUS_LOG(LOG_ERR,"\tReceived re-invite without SDP - responding 200 OK\n");
2257
                                nua_respond(nh, 200, sip_status_phrase(200), TAG_END());
2258
                                break;
2259
                        }
2260
                        sdp_parser_t *parser = sdp_parse(ssip->s_home, sip->sip_payload->pl_data, sip->sip_payload->pl_len, 0);
2261
                        if(!sdp_session(parser)) {
2262
                                JANUS_LOG(LOG_ERR, "\tError parsing SDP!\n");
2263
                                nua_respond(nh, 488, sip_status_phrase(488), TAG_END());
2264
                                sdp_parser_free(parser);
2265
                                break;
2266
                        }
2267
                        if(session->stack->s_nh_i != NULL) {
2268
                                if(session->stack->s_nh_i == nh) {
2269
                                        if (sdp_session_cmp(sdp_session(session->raw_media), sdp_session(parser)) == 0) {
2270
                                                /* re-INVITE that is basically a session-refresh (no media-change needed), accept. */
2271
                                                nua_respond(nh, 200, sip_status_phrase(200), TAG_END());
2272
                                        } else {
2273
                                                /* re-INVITE, we don't support those. */
2274
                                                nua_respond(nh, 488, sip_status_phrase(488), TAG_END());
2275
                                        }
2276
                                } else if(session->status >= janus_sip_call_status_inviting) {
2277
                                        /* Busy with another call */
2278
                                        JANUS_LOG(LOG_VERB, "\tAlready in a call (busy, status=%s)\n", janus_sip_call_status_string(session->status));
2279
                                        nua_respond(nh, 486, sip_status_phrase(486), TAG_END());
2280
                                        /* Notify the web app about the missed invite */
2281
                                        json_t *missed = json_object();
2282
                                        json_object_set_new(missed, "sip", json_string("event"));
2283
                                        json_t *result = json_object();
2284
                                        json_object_set_new(result, "event", json_string("missed_call"));
2285
                                        char *caller_text = url_as_string(session->stack->s_home, sip->sip_from->a_url);
2286
                                        json_object_set_new(result, "caller", json_string(caller_text));
2287
                                        su_free(session->stack->s_home, caller_text);
2288
                                        if (sip->sip_from && sip->sip_from->a_display) {
2289
                                                json_object_set_new(result, "displayname", json_string(sip->sip_from->a_display));
2290
                                        }
2291
                                        json_object_set_new(missed, "result", result);
2292
                                        int ret = gateway->push_event(session->handle, &janus_sip_plugin, session->transaction, missed, NULL);
2293
                                        JANUS_LOG(LOG_VERB, "  >> Pushing event to peer: %d (%s)\n", ret, janus_get_api_error(ret));
2294
                                        json_decref(missed);
2295
                                }
2296
                                sdp_parser_free(parser);
2297
                                break;
2298
                        }
2299
                        /* New incoming call */
2300
                        session->callee = g_strdup(url_as_string(session->stack->s_home, sip->sip_from->a_url));
2301
                        session->status = janus_sip_call_status_invited;
2302
                        /* Clean up SRTP stuff from before first, in case it's still needed */
2303
                        janus_sip_srtp_cleanup(session);
2304
                        /* Parse SDP */
2305
                        char *fixed_sdp = g_strdup(sip->sip_payload->pl_data);
2306
                        JANUS_LOG(LOG_VERB, "Someone is inviting us in a call:\n%s", sip->sip_payload->pl_data);
2307
                        sdp_session_t *sdp = sdp_session(parser);
2308
                        janus_sip_sdp_process(session, sdp, FALSE);
2309
                        /* Send SDP to the browser */
2310
                        json_t *jsep = json_pack("{ssss}", "type", "offer", "sdp", fixed_sdp);
2311
                        json_t *call = json_object();
2312
                        json_object_set_new(call, "sip", json_string("event"));
2313
                        json_t *calling = json_object();
2314
                        json_object_set_new(calling, "event", json_string("incomingcall"));
2315
                        json_object_set_new(calling, "username", json_string(session->callee));
2316
                        if(sip->sip_from && sip->sip_from->a_display) {
2317
                                json_object_set_new(calling, "displayname", json_string(sip->sip_from->a_display));
2318
                        }
2319
                        if(session->media.has_srtp_remote) {
2320
                                /* FIXME Maybe a true/false instead? */
2321
                                json_object_set_new(calling, "srtp", json_string(session->media.require_srtp ? "sdes_mandatory" : "sdes_optional"));
2322
                        }
2323
                        json_object_set_new(call, "result", calling);
2324
                        int ret = gateway->push_event(session->handle, &janus_sip_plugin, session->transaction, call, jsep);
2325
                        JANUS_LOG(LOG_VERB, "  >> Pushing event to peer: %d (%s)\n", ret, janus_get_api_error(ret));
2326
                        json_decref(call);
2327
                        json_decref(jsep);
2328
                        g_free(fixed_sdp);
2329
                        sdp_parser_free(parser);
2330
                        /* Send a Ringing back */
2331
                        nua_respond(nh, 180, sip_status_phrase(180), TAG_END());
2332
                        session->stack->s_nh_i = nh;
2333
                        break;
2334
                }
2335
                case nua_i_options:
2336
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2337
                        /* FIXME Should we handle this message? for now we reply with a 405 Method Not Implemented */
2338
                        nua_respond(nh, 405, sip_status_phrase(405), TAG_END());
2339
                        break;
2340
        /* Responses */
2341
                case nua_r_get_params:
2342
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2343
                        break;
2344
                case nua_r_set_params:
2345
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2346
                        break;
2347
                case nua_r_notifier:
2348
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2349
                        break;
2350
                case nua_r_shutdown:
2351
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2352
                        if(status < 200 && !g_atomic_int_get(&stopping)) {
2353
                                /* shutdown in progress -> return */
2354
                                break;
2355
                        }
2356
                        if(ssip != NULL) {
2357
                                /* end the event loop. su_root_run() will return */
2358
                                su_root_break(ssip->s_root);
2359
                        }
2360
                        break;
2361
                case nua_r_terminate:
2362
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2363
                        break;
2364
        /* SIP responses */
2365
                case nua_r_bye:
2366
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2367
                        break;
2368
                case nua_r_cancel:
2369
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2370
                        break;
2371
                case nua_r_info:
2372
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2373
                        break;
2374
                case nua_r_invite: {
2375
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2376

    
2377
                        if(status < 200) {
2378
                                /* Not ready yet (FIXME May this be pranswer?? we don't handle it yet...) */
2379
                                break;
2380
                        } else if(status == 401 || status == 407) {
2381
                                char auth[256];
2382
                                const char* scheme;
2383
                                const char* realm;
2384
                                if(status == 401) {
2385
                                         /* Get scheme/realm from 401 error */
2386
                                        sip_www_authenticate_t const* www_auth = sip->sip_www_authenticate;
2387
                                        scheme = www_auth->au_scheme;
2388
                                        realm = msg_params_find(www_auth->au_params, "realm=");
2389
                                } else {
2390
                                         /* Get scheme/realm from 407 error, proxy-auth */
2391
                                        sip_proxy_authenticate_t const* proxy_auth = sip->sip_proxy_authenticate;
2392
                                        scheme = proxy_auth->au_scheme;
2393
                                        realm = msg_params_find(proxy_auth->au_params, "realm=");
2394
                                }
2395
                                memset(auth, 0, sizeof(auth));
2396
                                g_snprintf(auth, sizeof(auth), "%s%s:%s:%s:%s%s",
2397
                                        session->account.secret_type == janus_sip_secret_type_hashed ? "HA1+" : "",
2398
                                        scheme,
2399
                                        realm,
2400
                                        session->account.authuser ? session->account.authuser : "null",
2401
                                        session->account.secret_type == janus_sip_secret_type_hashed ? "HA1+" : "",
2402
                                        session->account.secret ? session->account.secret : "null");
2403
                                JANUS_LOG(LOG_VERB, "\t%s\n", auth);
2404
                                /* Authenticate */
2405
                                nua_authenticate(nh,
2406
                                        NUTAG_AUTH(auth),
2407
                                        TAG_END());
2408
                                break;
2409
                        } else if(status >= 400) {
2410
                                break;
2411
                        }
2412
                        if(ssip == NULL) {
2413
                                JANUS_LOG(LOG_ERR, "\tInvalid SIP stack\n");
2414
                                nua_respond(nh, 500, sip_status_phrase(500), TAG_END());
2415
                                break;
2416
                        }
2417
                        sdp_parser_t *parser = sdp_parse(ssip->s_home, sip->sip_payload->pl_data, sip->sip_payload->pl_len, 0);
2418
                        if(!sdp_session(parser)) {
2419
                                JANUS_LOG(LOG_ERR, "\tError parsing SDP!\n");
2420
                                nua_respond(nh, 488, sip_status_phrase(488), TAG_END());
2421
                                sdp_parser_free(parser);
2422
                                break;
2423
                        }
2424
                        /* Send an ACK, if needed */
2425
                        if(!session->media.autoack) {
2426
                                char *route = sip->sip_record_route ? url_as_string(session->stack->s_home, sip->sip_record_route->r_url) : NULL;
2427
                                JANUS_LOG(LOG_INFO, "Sending ACK (route=%s)\n", route ? route : "none");
2428
                                nua_ack(nh,
2429
                                        TAG_IF(route, NTATAG_DEFAULT_PROXY(route)),
2430
                                        TAG_END());
2431
                        }
2432
                        /* Parse SDP */
2433
                        JANUS_LOG(LOG_VERB, "Peer accepted our call:\n%s", sip->sip_payload->pl_data);
2434
                        session->status = janus_sip_call_status_incall;
2435
                        char *fixed_sdp = g_strdup(sip->sip_payload->pl_data);
2436
                        sdp_session_t *sdp = sdp_session(parser);
2437
                        janus_sip_sdp_process(session, sdp, TRUE);
2438
                        /* If we asked for SRTP and are not getting it, fail */
2439
                        if(session->media.require_srtp && !session->media.has_srtp_remote) {
2440
                                JANUS_LOG(LOG_ERR, "\tWe asked for mandatory SRTP but didn't get any in the reply!\n");
2441
                                sdp_parser_free(parser);
2442
                                g_free(fixed_sdp);
2443
                                /* Hangup immediately */
2444
                                session->status = janus_sip_call_status_closing;
2445
                                nua_bye(nh, TAG_END());
2446
                                g_free(session->callee);
2447
                                session->callee = NULL;
2448
                                break;
2449
                        }
2450
                        if(session->media.audio_pt > -1) {
2451
                                session->media.audio_pt_name = janus_get_codec_from_pt(fixed_sdp, session->media.audio_pt);
2452
                                JANUS_LOG(LOG_VERB, "Detected audio codec: %d (%s)\n", session->media.audio_pt, session->media.audio_pt_name);
2453
                        }
2454
                        if(session->media.video_pt > -1) {
2455
                                session->media.video_pt_name = janus_get_codec_from_pt(fixed_sdp, session->media.video_pt);
2456
                                JANUS_LOG(LOG_VERB, "Detected video codec: %d (%s)\n", session->media.video_pt, session->media.video_pt_name);
2457
                        }
2458
                        session->media.ready = 1;        /* FIXME Maybe we need a better way to signal this */
2459
                        if(session->raw_media != NULL)
2460
                                sdp_parser_free(session->raw_media);
2461
                        session->raw_media = parser;
2462
                        GError *error = NULL;
2463
                        char tname[16];
2464
                        g_snprintf(tname, sizeof(tname), "siprtp %s", session->account.username);
2465
                        g_thread_try_new(tname, janus_sip_relay_thread, session, &error);
2466
                        if(error != NULL) {
2467
                                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the RTP/RTCP thread...\n", error->code, error->message ? error->message : "??");
2468
                        }
2469
                        /* Send SDP to the browser */
2470
                        json_t *jsep = json_pack("{ssss}", "type", "answer", "sdp", fixed_sdp);
2471
                        json_t *call = json_object();
2472
                        json_object_set_new(call, "sip", json_string("event"));
2473
                        json_t *calling = json_object();
2474
                        json_object_set_new(calling, "event", json_string("accepted"));
2475
                        json_object_set_new(calling, "username", json_string(session->callee));
2476
                        json_object_set_new(call, "result", calling);
2477
                        int ret = gateway->push_event(session->handle, &janus_sip_plugin, session->transaction, call, jsep);
2478
                        JANUS_LOG(LOG_VERB, "  >> Pushing event to peer: %d (%s)\n", ret, janus_get_api_error(ret));
2479
                        json_decref(call);
2480
                        json_decref(jsep);
2481
                        g_free(fixed_sdp);
2482
                        break;
2483
                }
2484
                case nua_r_register: {
2485
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2486
                        if(status == 200) {
2487
                                if(session->account.registration_status < janus_sip_registration_status_registered)
2488
                                        session->account.registration_status = janus_sip_registration_status_registered;
2489
                                JANUS_LOG(LOG_VERB, "Successfully registered\n");
2490
                                /* Notify the browser */
2491
                                json_t *call = json_object();
2492
                                json_object_set_new(call, "sip", json_string("event"));
2493
                                json_t *calling = json_object();
2494
                                json_object_set_new(calling, "event", json_string("registered"));
2495
                                json_object_set_new(calling, "username", json_string(session->account.username));
2496
                                json_object_set_new(calling, "register_sent", json_true());
2497
                                json_object_set_new(call, "result", calling);
2498
                                int ret = gateway->push_event(session->handle, &janus_sip_plugin, session->transaction, call, NULL);
2499
                                JANUS_LOG(LOG_VERB, "  >> Pushing event to peer: %d (%s)\n", ret, janus_get_api_error(ret));
2500
                                json_decref(call);
2501
                        } else if(status == 401) {
2502
                                /* Get scheme/realm from 401 error */
2503
                                sip_www_authenticate_t const* www_auth = sip->sip_www_authenticate;
2504
                                char const* scheme = www_auth->au_scheme;
2505
                                const char* realm = msg_params_find(www_auth->au_params, "realm=");
2506
                                char auth[256];
2507
                                memset(auth, 0, sizeof(auth));
2508
                                g_snprintf(auth, sizeof(auth), "%s%s:%s:%s:%s%s",
2509
                                        session->account.secret_type == janus_sip_secret_type_hashed ? "HA1+" : "",
2510
                                        scheme,
2511
                                        realm,
2512
                                        session->account.authuser ? session->account.authuser : "null",
2513
                                        session->account.secret_type == janus_sip_secret_type_hashed ? "HA1+" : "",
2514
                                        session->account.secret);
2515
                                JANUS_LOG(LOG_VERB, "\t%s\n", auth);
2516
                                /* Authenticate */
2517
                                nua_authenticate(nh,
2518
                                        NUTAG_AUTH(auth),
2519
                                        TAG_END());
2520
                        } else if(status >= 400) {
2521
                                /* Authentication failed? */
2522
                                session->account.registration_status = janus_sip_registration_status_failed;
2523
                                /* Tell the browser... */
2524
                                json_t *event = json_object();
2525
                                json_object_set_new(event, "sip", json_string("event"));
2526
                                json_t *result = json_object();
2527
                                json_object_set_new(result, "event", json_string("registration_failed"));
2528
                                json_object_set_new(result, "code", json_integer(status));
2529
                                json_object_set_new(result, "reason", json_string(phrase ? phrase : ""));
2530
                                json_object_set_new(event, "result", result);
2531
                                int ret = gateway->push_event(session->handle, &janus_sip_plugin, session->transaction, event, NULL);
2532
                                JANUS_LOG(LOG_VERB, "  >> Pushing event to peer: %d (%s)\n", ret, janus_get_api_error(ret));
2533
                                json_decref(event);
2534
                        }
2535
                        break;
2536
                }
2537
                default:
2538
                        /* unknown event -> print out error message */
2539
                        JANUS_LOG(LOG_ERR, "Unknown event %d (%s)\n", event, nua_event_name(event));
2540
                        break;
2541
        }
2542
}
2543

    
2544
void janus_sip_sdp_process(janus_sip_session *session, sdp_session_t *sdp, gboolean answer) {
2545
        if(!session || !sdp)
2546
                return;
2547
        /* c= */
2548
        if(sdp->sdp_connection && sdp->sdp_connection->c_address) {
2549
                g_free(session->media.remote_ip);
2550
                session->media.remote_ip = g_strdup(sdp->sdp_connection->c_address);
2551
                JANUS_LOG(LOG_VERB, "  >> Media connection:\n");
2552
                JANUS_LOG(LOG_VERB, "       %s\n", session->media.remote_ip);
2553
        }
2554
        JANUS_LOG(LOG_VERB, "  >> Media lines:\n");
2555
        sdp_media_t *m = sdp->sdp_media;
2556
        while(m) {
2557
                session->media.require_srtp = session->media.require_srtp || (m->m_proto_name && !strcasecmp(m->m_proto_name, "RTP/SAVP"));
2558
                if(m->m_type == sdp_media_audio) {
2559
                        JANUS_LOG(LOG_VERB, "       Audio: %lu\n", m->m_port);
2560
                        if(m->m_port) {
2561
                                session->media.has_audio = 1;
2562
                                session->media.remote_audio_rtp_port = m->m_port;
2563
                                session->media.remote_audio_rtcp_port = m->m_port+1;        /* FIXME We're assuming RTCP is on the next port */
2564
                        }
2565
                } else if(m->m_type == sdp_media_video) {
2566
                        JANUS_LOG(LOG_VERB, "       Video: %lu\n", m->m_port);
2567
                        if(m->m_port) {
2568
                                session->media.has_video = 1;
2569
                                session->media.remote_video_rtp_port = m->m_port;
2570
                                session->media.remote_video_rtcp_port = m->m_port+1;        /* FIXME We're assuming RTCP is on the next port */
2571
                        }
2572
                } else {
2573
                        JANUS_LOG(LOG_WARN, "       Unsupported media line (not audio/video)\n");
2574
                        m = m->m_next;
2575
                        continue;
2576
                }
2577
                JANUS_LOG(LOG_VERB, "       Media connections:\n");
2578
                if(m->m_connections) {
2579
                        sdp_connection_t *c = m->m_connections;
2580
                        while(c) {
2581
                                if(c->c_address) {
2582
                                        g_free(session->media.remote_ip);
2583
                                        session->media.remote_ip = g_strdup(c->c_address);
2584
                                        JANUS_LOG(LOG_VERB, "         [%s]\n", session->media.remote_ip);
2585
                                }
2586
                                c = c->c_next;
2587
                        }
2588
                }
2589
                JANUS_LOG(LOG_VERB, "       Media RTP maps:\n");
2590
                sdp_rtpmap_t *r = m->m_rtpmaps;
2591
                while(r) {
2592
                        JANUS_LOG(LOG_VERB, "         [%u] %s\n", r->rm_pt, r->rm_encoding);
2593
                        r = r->rm_next;
2594
                }
2595
                JANUS_LOG(LOG_VERB, "       Media attributes:\n");
2596
                sdp_attribute_t *a = m->m_attributes;
2597
                while(a) {
2598
                        if(a->a_name) {
2599
                                if(!strcasecmp(a->a_name, "rtpmap")) {
2600
                                        JANUS_LOG(LOG_VERB, "         RTP Map:     %s\n", a->a_value);
2601
                                } else if(!strcasecmp(a->a_name, "crypto")) {
2602
                                        JANUS_LOG(LOG_VERB, "         Crypto:      %s\n", a->a_value);
2603
                                        if(m->m_type == sdp_media_audio || m->m_type == sdp_media_video) {
2604
                                                gint32 tag = 0;
2605
                                                int suite;
2606
                                                char crypto[40];
2607
                                                /* FIXME inline can be more complex than that, and we're currently only offering SHA1_80 */
2608
                                                int res = sscanf(a->a_value, "%"SCNi32" AES_CM_128_HMAC_SHA1_%2d inline:%40s",
2609
                                                        &tag, &suite, crypto);
2610
                                                if(res != 3) {
2611
                                                        JANUS_LOG(LOG_WARN, "Failed to parse crypto line, ignoring... %s\n", a->a_value);
2612
                                                } else {
2613
                                                        gboolean video = (m->m_type == sdp_media_video);
2614
                                                        int current_suite = video ? session->media.video_srtp_suite_in : session->media.audio_srtp_suite_in;
2615
                                                        if(current_suite == 0) {
2616
                                                                if(video)
2617
                                                                        session->media.video_srtp_suite_in = suite;
2618
                                                                else
2619
                                                                        session->media.audio_srtp_suite_in = suite;
2620
                                                                janus_sip_srtp_set_remote(session, video, crypto, suite);
2621
                                                                session->media.has_srtp_remote = TRUE;
2622
                                                        } else {
2623
                                                                JANUS_LOG(LOG_WARN, "We already configured a %s crypto context (AES_CM_128_HMAC_SHA1_%d), skipping additional crypto line\n",
2624
                                                                        video ? "video" : "audio", current_suite);
2625
                                                        }
2626
                                                }
2627
                                        }
2628
                                }
2629
                        }
2630
                        a = a->a_next;
2631
                }
2632
                if(answer && (m->m_type == sdp_media_audio || m->m_type == sdp_media_video)) {
2633
                        /* Check which codec was negotiated eventually */
2634
                        int pt = -1;
2635
                        if(!m->m_rtpmaps) {
2636
                                JANUS_LOG(LOG_VERB, "No RTP maps?? trying formats...\n");
2637
                                if(m->m_format) {
2638
                                        sdp_list_t *fmt = m->m_format;
2639
                                        pt = atoi(fmt->l_text);
2640
                                }
2641
                        } else {
2642
                                sdp_rtpmap_t *r = m->m_rtpmaps;
2643
                                pt = r->rm_pt;
2644
                        }
2645
                        if(pt > -1) {
2646
                                if(m->m_type == sdp_media_audio) {
2647
                                        session->media.audio_pt = pt;
2648
                                } else {
2649
                                        session->media.video_pt = pt;
2650
                                }
2651
                        }
2652
                }
2653
                m = m->m_next;
2654
        }
2655
}
2656

    
2657
char *janus_sip_sdp_manipulate(janus_sip_session *session, sdp_session_t *sdp, gboolean answer) {
2658
        if(!session || !session->stack || !sdp)
2659
                return NULL;
2660
        /* Placeholders for later */
2661
        sdp_attribute_t crypto_audio = {
2662
                .a_size = sizeof(sdp_attribute_t),
2663
                .a_name = "crypto",
2664
                .a_value = "audio"
2665
        };
2666
        sdp_attribute_t crypto_video = {
2667
                .a_size = sizeof(sdp_attribute_t),
2668
                .a_name = "crypto",
2669
                .a_value = "video"
2670
        };
2671
        /* Start replacing stuff */
2672
        if(sdp->sdp_connection && sdp->sdp_connection->c_address) {
2673
                sdp->sdp_connection->c_address = local_ip;
2674
        }
2675
        JANUS_LOG(LOG_VERB, "Setting protocol to %s\n", session->media.require_srtp ? "RTP/SAVP" : "RTP/AVP");
2676
        sdp_media_t *m = sdp->sdp_media;
2677
        while(m) {
2678
                m->m_proto = session->media.require_srtp ? sdp_proto_srtp : sdp_proto_rtp;
2679
                m->m_proto_name = session->media.require_srtp ? "RTP/SAVP" : "RTP/AVP";
2680
                if(m->m_type == sdp_media_audio) {
2681
                        m->m_port = session->media.local_audio_rtp_port;
2682
                        if(session->media.has_srtp_local) {
2683
                                sdp_attribute_append(&m->m_attributes, &crypto_audio);
2684
                        }
2685
                } else if(m->m_type == sdp_media_video) {
2686
                        m->m_port = session->media.local_video_rtp_port;
2687
                        if(session->media.has_srtp_local) {
2688
                                sdp_attribute_append(&m->m_attributes, &crypto_video);
2689
                        }
2690
                }
2691
                if(m->m_connections) {
2692
                        sdp_connection_t *c = m->m_connections;
2693
                        while(c) {
2694
                                c->c_address = local_ip;
2695
                                c = c->c_next;
2696
                        }
2697
                }
2698
                if(answer && (m->m_type == sdp_media_audio || m->m_type == sdp_media_video)) {
2699
                        /* Check which codec was negotiated eventually */
2700
                        int pt = -1;
2701
                        if(!m->m_rtpmaps) {
2702
                                JANUS_LOG(LOG_VERB, "No RTP maps?? trying formats...\n");
2703
                                if(m->m_format) {
2704
                                        sdp_list_t *fmt = m->m_format;
2705
                                        pt = atoi(fmt->l_text);
2706
                                }
2707
                        } else {
2708
                                sdp_rtpmap_t *r = m->m_rtpmaps;
2709
                                pt = r->rm_pt;
2710
                        }
2711
                        if(pt > -1) {
2712
                                if(m->m_type == sdp_media_audio) {
2713
                                        session->media.audio_pt = pt;
2714
                                } else {
2715
                                        session->media.video_pt = pt;
2716
                                }
2717
                        }
2718
                }
2719
                m = m->m_next;
2720
        }
2721
        /* Generate a SDP string out of our changes */
2722
        char buf[2048];
2723
        sdp_printer_t *printer = sdp_print(session->stack->s_home, sdp, buf, 2048, 0);
2724
        if(!sdp_message(printer)) {
2725
                sdp_printer_free(printer);
2726
                return NULL;
2727
        }
2728
        sdp_printer_free(printer);
2729
        char *new_sdp = g_strdup(buf);
2730
        /* If any crypto placeholer was there, fix that */
2731
        if(session->media.has_srtp_local) {
2732
                if(session->media.has_audio) {
2733
                        char *crypto = NULL;
2734
                        session->media.audio_srtp_suite_out = 80;
2735
                        janus_sip_srtp_set_local(session, FALSE, &crypto);
2736
                        /* FIXME 32? 80? Both? */
2737
                        char cryptoline[100];
2738
                        g_snprintf(cryptoline, 100, "a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:%s", crypto);
2739
                        g_free(crypto);
2740
                        new_sdp = janus_string_replace(new_sdp, "a=crypto:audio", cryptoline);
2741
                }
2742
                if(session->media.has_video) {
2743
                        char *crypto = NULL;
2744
                        session->media.video_srtp_suite_out = 80;
2745
                        janus_sip_srtp_set_local(session, TRUE, &crypto);
2746
                        /* FIXME 32? 80? Both? */
2747
                        char cryptoline[100];
2748
                        g_snprintf(cryptoline, 100, "a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:%s", crypto);
2749
                        g_free(crypto);
2750
                        new_sdp = janus_string_replace(new_sdp, "a=crypto:video", cryptoline);
2751
                }
2752
        }
2753
        return new_sdp;
2754
}
2755

    
2756
/* Bind local RTP/RTCP sockets */
2757
static int janus_sip_allocate_local_ports(janus_sip_session *session) {
2758
        if(session == NULL) {
2759
                JANUS_LOG(LOG_ERR, "Invalid session\n");
2760
                return -1;
2761
        }
2762
        /* Reset status */
2763
        if(session->media.audio_rtp_fd != -1) {
2764
                close(session->media.audio_rtp_fd);
2765
                session->media.audio_rtp_fd = -1;
2766
        }
2767
        if(session->media.audio_rtcp_fd != -1) {
2768
                close(session->media.audio_rtcp_fd);
2769
                session->media.audio_rtcp_fd = -1;
2770
        }
2771
        session->media.local_audio_rtp_port = 0;
2772
        session->media.local_audio_rtcp_port = 0;
2773
        session->media.audio_ssrc = 0;
2774
        if(session->media.video_rtp_fd != -1) {
2775
                close(session->media.video_rtp_fd);
2776
                session->media.video_rtp_fd = -1;
2777
        }
2778
        if(session->media.video_rtcp_fd != -1) {
2779
                close(session->media.video_rtcp_fd);
2780
                session->media.video_rtcp_fd = -1;
2781
        }
2782
        session->media.local_video_rtp_port = 0;
2783
        session->media.local_video_rtcp_port = 0;
2784
        session->media.video_ssrc = 0;
2785
        /* Start */
2786
        int attempts = 100;        /* FIXME Don't retry forever */
2787
        if(session->media.has_audio) {
2788
                JANUS_LOG(LOG_VERB, "Allocating audio ports:\n");
2789
                struct sockaddr_in audio_rtp_address, audio_rtcp_address;
2790
                while(session->media.local_audio_rtp_port == 0 || session->media.local_audio_rtcp_port == 0) {
2791
                        if(attempts == 0)        /* Too many failures */
2792
                                return -1;
2793
                        if(session->media.audio_rtp_fd == -1) {
2794
                                session->media.audio_rtp_fd = socket(AF_INET, SOCK_DGRAM, 0);
2795
                        }
2796
                        if(session->media.audio_rtcp_fd == -1) {
2797
                                session->media.audio_rtcp_fd = socket(AF_INET, SOCK_DGRAM, 0);
2798
                        }
2799
                        int rtp_port = g_random_int_range(10000, 60000);        /* FIXME Should this be configurable? */
2800
                        if(rtp_port % 2)
2801
                                rtp_port++;        /* Pick an even port for RTP */
2802
                        audio_rtp_address.sin_family = AF_INET;
2803
                        audio_rtp_address.sin_port = htons(rtp_port);
2804
                        inet_pton(AF_INET, local_ip, &audio_rtp_address.sin_addr.s_addr);
2805
                        if(bind(session->media.audio_rtp_fd, (struct sockaddr *)(&audio_rtp_address), sizeof(struct sockaddr)) < 0) {
2806
                                JANUS_LOG(LOG_ERR, "Bind failed for audio RTP (port %d), trying a different one...\n", rtp_port);
2807
                                attempts--;
2808
                                continue;
2809
                        }
2810
                        JANUS_LOG(LOG_VERB, "Audio RTP listener bound to port %d\n", rtp_port);
2811
                        int rtcp_port = rtp_port+1;
2812
                        audio_rtcp_address.sin_family = AF_INET;
2813
                        audio_rtcp_address.sin_port = htons(rtcp_port);
2814
                        inet_pton(AF_INET, local_ip, &audio_rtcp_address.sin_addr.s_addr);
2815
                        if(bind(session->media.audio_rtcp_fd, (struct sockaddr *)(&audio_rtcp_address), sizeof(struct sockaddr)) < 0) {
2816
                                JANUS_LOG(LOG_ERR, "Bind failed for audio RTCP (port %d), trying a different one...\n", rtcp_port);
2817
                                /* RTP socket is not valid anymore, reset it */
2818
                                close(session->media.audio_rtp_fd);
2819
                                session->media.audio_rtp_fd = -1;
2820
                                attempts--;
2821
                                continue;
2822
                        }
2823
                        JANUS_LOG(LOG_VERB, "Audio RTCP listener bound to port %d\n", rtcp_port);
2824
                        session->media.local_audio_rtp_port = rtp_port;
2825
                        session->media.local_audio_rtcp_port = rtcp_port;
2826
                }
2827
        }
2828
        if(session->media.has_video) {
2829
                JANUS_LOG(LOG_VERB, "Allocating video ports:\n");
2830
                struct sockaddr_in video_rtp_address, video_rtcp_address;
2831
                while(session->media.local_video_rtp_port == 0 || session->media.local_video_rtcp_port == 0) {
2832
                        if(attempts == 0)        /* Too many failures */
2833
                                return -1;
2834
                        if(session->media.video_rtp_fd == -1) {
2835
                                session->media.video_rtp_fd = socket(AF_INET, SOCK_DGRAM, 0);
2836
                        }
2837
                        if(session->media.video_rtcp_fd == -1) {
2838
                                session->media.video_rtcp_fd = socket(AF_INET, SOCK_DGRAM, 0);
2839
                        }
2840
                        int rtp_port = g_random_int_range(10000, 60000);        /* FIXME Should this be configurable? */
2841
                        if(rtp_port % 2)
2842
                                rtp_port++;        /* Pick an even port for RTP */
2843
                        video_rtp_address.sin_family = AF_INET;
2844
                        video_rtp_address.sin_port = htons(rtp_port);
2845
                        inet_pton(AF_INET, local_ip, &video_rtp_address.sin_addr.s_addr);
2846
                        if(bind(session->media.video_rtp_fd, (struct sockaddr *)(&video_rtp_address), sizeof(struct sockaddr)) < 0) {
2847
                                JANUS_LOG(LOG_ERR, "Bind failed for video RTP (port %d), trying a different one...\n", rtp_port);
2848
                                attempts--;
2849
                                continue;
2850
                        }
2851
                        JANUS_LOG(LOG_VERB, "Video RTP listener bound to port %d\n", rtp_port);
2852
                        int rtcp_port = rtp_port+1;
2853
                        video_rtcp_address.sin_family = AF_INET;
2854
                        video_rtcp_address.sin_port = htons(rtcp_port);
2855
                        inet_pton(AF_INET, local_ip, &video_rtcp_address.sin_addr.s_addr);
2856
                        if(bind(session->media.video_rtcp_fd, (struct sockaddr *)(&video_rtcp_address), sizeof(struct sockaddr)) < 0) {
2857
                                JANUS_LOG(LOG_ERR, "Bind failed for video RTCP (port %d), trying a different one...\n", rtcp_port);
2858
                                /* RTP socket is not valid anymore, reset it */
2859
                                close(session->media.video_rtp_fd);
2860
                                session->media.video_rtp_fd = -1;
2861
                                attempts--;
2862
                                continue;
2863
                        }
2864
                        JANUS_LOG(LOG_VERB, "Video RTCP listener bound to port %d\n", rtcp_port);
2865
                        session->media.local_video_rtp_port = rtp_port;
2866
                        session->media.local_video_rtcp_port = rtcp_port;
2867
                }
2868
        }
2869
        return 0;
2870
}
2871

    
2872
/* Thread to relay RTP/RTCP frames coming from the SIP peer */
2873
static void *janus_sip_relay_thread(void *data) {
2874
        janus_sip_session *session = (janus_sip_session *)data;
2875
        if(!session || !session->account.username || !session->callee) {
2876
                g_thread_unref(g_thread_self());
2877
                return NULL;
2878
        }
2879
        JANUS_LOG(LOG_VERB, "Starting relay thread (%s <--> %s)\n", session->account.username, session->callee);
2880

    
2881
        gboolean have_server_ip = TRUE;
2882
        struct sockaddr_in server_addr;
2883
        memset(&server_addr, 0, sizeof(server_addr));
2884
        server_addr.sin_family = AF_INET;
2885
        if((inet_aton(session->media.remote_ip, &server_addr.sin_addr)) <= 0) {        /* Not a numeric IP... */
2886
                struct hostent *host = gethostbyname(session->media.remote_ip);        /* ...resolve name */
2887
                if(!host) {
2888
                        JANUS_LOG(LOG_ERR, "[SIP-%s] Couldn't get host (%s)\n", session->account.username, session->media.remote_ip);
2889
                        have_server_ip = FALSE;
2890
                } else {
2891
                        server_addr.sin_addr = *(struct in_addr *)host->h_addr_list;
2892
                }
2893
        }
2894

    
2895
        /* Connect peers (FIXME This pretty much sucks right now) */
2896
        if(have_server_ip && session->media.remote_audio_rtp_port) {
2897
                server_addr.sin_port = htons(session->media.remote_audio_rtp_port);
2898
                if(connect(session->media.audio_rtp_fd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1) {
2899
                        JANUS_LOG(LOG_ERR, "[SIP-%s] Couldn't connect audio RTP? (%s:%d)\n", session->account.username, session->media.remote_ip, session->media.remote_audio_rtp_port);
2900
                        JANUS_LOG(LOG_ERR, "[SIP-%s]   -- %d (%s)\n", session->account.username, errno, strerror(errno));
2901
                }
2902
        }
2903
        if(have_server_ip && session->media.remote_audio_rtcp_port) {
2904
                server_addr.sin_port = htons(session->media.remote_audio_rtcp_port);
2905
                if(connect(session->media.audio_rtcp_fd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1) {
2906
                        JANUS_LOG(LOG_ERR, "[SIP-%s] Couldn't connect audio RTCP? (%s:%d)\n", session->account.username, session->media.remote_ip, session->media.remote_audio_rtcp_port);
2907
                        JANUS_LOG(LOG_ERR, "[SIP-%s]   -- %d (%s)\n", session->account.username, errno, strerror(errno));
2908
                }
2909
        }
2910
        if(have_server_ip && session->media.remote_video_rtp_port) {
2911
                server_addr.sin_port = htons(session->media.remote_video_rtp_port);
2912
                if(connect(session->media.video_rtp_fd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1) {
2913
                        JANUS_LOG(LOG_ERR, "[SIP-%s] Couldn't connect video RTP? (%s:%d)\n", session->account.username, session->media.remote_ip, session->media.remote_video_rtp_port);
2914
                        JANUS_LOG(LOG_ERR, "[SIP-%s]   -- %d (%s)\n", session->account.username, errno, strerror(errno));
2915
                }
2916
        }
2917
        if(have_server_ip && session->media.remote_video_rtcp_port) {
2918
                server_addr.sin_port = htons(session->media.remote_video_rtcp_port);
2919
                if(connect(session->media.video_rtcp_fd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1) {
2920
                        JANUS_LOG(LOG_ERR, "[SIP-%s] Couldn't connect video RTCP? (%s:%d)\n", session->account.username, session->media.remote_ip, session->media.remote_video_rtcp_port);
2921
                        JANUS_LOG(LOG_ERR, "[SIP-%s]   -- %d (%s)\n", session->account.username, errno, strerror(errno));
2922
                }
2923
        }
2924

    
2925
        if(!session->callee) {
2926
                JANUS_LOG(LOG_VERB, "[SIP-%s] Leaving thread, no callee...\n", session->account.username);
2927
                g_thread_unref(g_thread_self());
2928
                return NULL;
2929
        }
2930
        /* File descriptors */
2931
        socklen_t addrlen;
2932
        struct sockaddr_in remote;
2933
        int resfd = 0, bytes = 0;
2934
        struct pollfd fds[4];
2935
        char buffer[1500];
2936
        memset(buffer, 0, 1500);
2937
        /* Loop */
2938
        int num = 0;
2939
        gboolean goon = TRUE;
2940
        while(goon && session != NULL && !session->destroyed &&
2941
                        session->status > janus_sip_call_status_idle &&
2942
                        session->status < janus_sip_call_status_closing) {        /* FIXME We need a per-call watchdog as well */
2943
                /* Prepare poll */
2944
                num = 0;
2945
                if(session->media.audio_rtp_fd != -1) {
2946
                        fds[num].fd = session->media.audio_rtp_fd;
2947
                        fds[num].events = POLLIN;
2948
                        fds[num].revents = 0;
2949
                        num++;
2950
                }
2951
                if(session->media.audio_rtcp_fd != -1) {
2952
                        fds[num].fd = session->media.audio_rtcp_fd;
2953
                        fds[num].events = POLLIN;
2954
                        fds[num].revents = 0;
2955
                        num++;
2956
                }
2957
                if(session->media.video_rtp_fd != -1) {
2958
                        fds[num].fd = session->media.video_rtp_fd;
2959
                        fds[num].events = POLLIN;
2960
                        fds[num].revents = 0;
2961
                        num++;
2962
                }
2963
                if(session->media.video_rtcp_fd != -1) {
2964
                        fds[num].fd = session->media.video_rtcp_fd;
2965
                        fds[num].events = POLLIN;
2966
                        fds[num].revents = 0;
2967
                        num++;
2968
                }
2969
                /* Wait for some data */
2970
                resfd = poll(fds, num, 1000);
2971
                if(resfd < 0) {
2972
                        JANUS_LOG(LOG_ERR, "[SIP-%s] Error polling...\n", session->account.username);
2973
                        JANUS_LOG(LOG_ERR, "[SIP-%s]   -- %d (%s)\n", session->account.username, errno, strerror(errno));
2974
                        break;
2975
                } else if(resfd == 0) {
2976
                        /* No data, keep going */
2977
                        continue;
2978
                }
2979
                if(session == NULL || session->destroyed ||
2980
                                session->status <= janus_sip_call_status_idle ||
2981
                                session->status >= janus_sip_call_status_closing)
2982
                        break;
2983
                int i = 0;
2984
                for(i=0; i<num; i++) {
2985
                        if(fds[i].revents & (POLLERR | POLLHUP)) {
2986
                                /* Socket error? */
2987
                                JANUS_LOG(LOG_ERR, "[SIP-%s] Error polling: %s...\n", session->account.username,
2988
                                        fds[i].revents & POLLERR ? "POLLERR" : "POLLHUP");
2989
                                JANUS_LOG(LOG_ERR, "[SIP-%s]   -- %d (%s)\n", session->account.username, errno, strerror(errno));
2990
                                goon = FALSE;        /* Can we assume it's pretty much over, after a POLLERR? */
2991
                                /* FIXME Simulate a "hangup" coming from the browser */
2992
                                janus_sip_message *msg = g_malloc0(sizeof(janus_sip_message));
2993
                                msg->handle = session->handle;
2994
                                msg->message = json_pack("{ss}", "request", "hangup");
2995
                                msg->transaction = NULL;
2996
                                msg->jsep = NULL;
2997
                                g_async_queue_push(messages, msg);
2998
                                break;
2999
                        } else if(fds[i].revents & POLLIN) {
3000
                                /* Got an RTP/RTCP packet */
3001
                                if(session->media.audio_rtp_fd != -1 && fds[i].fd == session->media.audio_rtp_fd) {
3002
                                        /* Got something audio (RTP) */
3003
                                        addrlen = sizeof(remote);
3004
                                        bytes = recvfrom(session->media.audio_rtp_fd, buffer, 1500, 0, (struct sockaddr*)&remote, &addrlen);
3005
                                        //~ JANUS_LOG(LOG_VERB, "************************\nGot %d bytes on the audio RTP channel...\n", bytes);
3006
                                        //~ rtp_header_t *rtp = (rtp_header_t *)buffer;
3007
                                        //~ JANUS_LOG(LOG_VERB, " ... parsed RTP packet (ssrc=%u, pt=%u, seq=%u, ts=%u)...\n",
3008
                                                //~ ntohl(rtp->ssrc), rtp->type, ntohs(rtp->seq_number), ntohl(rtp->timestamp));
3009
                                        if(session->media.audio_ssrc_peer == 0) {
3010
                                                rtp_header *header = (rtp_header *)buffer;
3011
                                                session->media.audio_ssrc_peer = ntohl(header->ssrc);
3012
                                                JANUS_LOG(LOG_VERB, "Got SIP peer audio SSRC: %"SCNu32"\n", session->media.audio_ssrc_peer);
3013
                                        }
3014
                                        /* Is this SRTP? */
3015
                                        if(session->media.has_srtp_remote) {
3016
                                                int buflen = bytes;
3017
                                                err_status_t res = srtp_unprotect(session->media.audio_srtp_in, buffer, &buflen);
3018
                                                if(res != err_status_ok && res != err_status_replay_fail && res != err_status_replay_old) {
3019
                                                        rtp_header *header = (rtp_header *)buffer;
3020
                                                        guint32 timestamp = ntohl(header->timestamp);
3021
                                                        guint16 seq = ntohs(header->seq_number);
3022
                                                        JANUS_LOG(LOG_ERR, "[SIP-%s] Audio SRTP unprotect error: %s (len=%d-->%d, ts=%"SCNu32", seq=%"SCNu16")\n",
3023
                                                                session->account.username, janus_sip_get_srtp_error(res), bytes, buflen, timestamp, seq);
3024
                                                        continue;
3025
                                                }
3026
                                                bytes = buflen;
3027
                                        }
3028
                                        /* Save the frame if we're recording */
3029
                                        janus_recorder_save_frame(session->arc_peer, buffer, bytes);
3030
                                        /* Relay to browser */
3031
                                        gateway->relay_rtp(session->handle, 0, buffer, bytes);
3032
                                        continue;
3033
                                } else if(session->media.audio_rtcp_fd != -1 && fds[i].fd == session->media.audio_rtcp_fd) {
3034
                                        /* Got something audio (RTCP) */
3035
                                        addrlen = sizeof(remote);
3036
                                        bytes = recvfrom(session->media.audio_rtcp_fd, buffer, 1500, 0, (struct sockaddr*)&remote, &addrlen);
3037
                                        //~ JANUS_LOG(LOG_VERB, "************************\nGot %d bytes on the audio RTCP channel...\n", bytes);
3038
                                        /* Is this SRTCP? */
3039
                                        if(session->media.has_srtp_remote) {
3040
                                                int buflen = bytes;
3041
                                                err_status_t res = srtp_unprotect_rtcp(session->media.audio_srtp_in, buffer, &buflen);
3042
                                                if(res != err_status_ok && res != err_status_replay_fail && res != err_status_replay_old) {
3043
                                                        JANUS_LOG(LOG_ERR, "[SIP-%s] Audio SRTCP unprotect error: %s (len=%d-->%d)\n",
3044
                                                                session->account.username, janus_sip_get_srtp_error(res), bytes, buflen);
3045
                                                        continue;
3046
                                                }
3047
                                                bytes = buflen;
3048
                                        }
3049
                                        /* Relay to browser */
3050
                                        gateway->relay_rtcp(session->handle, 0, buffer, bytes);
3051
                                        continue;
3052
                                } else if(session->media.video_rtp_fd != -1 && fds[i].fd == session->media.video_rtp_fd) {
3053
                                        /* Got something video (RTP) */
3054
                                        addrlen = sizeof(remote);
3055
                                        bytes = recvfrom(session->media.video_rtp_fd, buffer, 1500, 0, (struct sockaddr*)&remote, &addrlen);
3056
                                        //~ JANUS_LOG(LOG_VERB, "************************\nGot %d bytes on the video RTP channel...\n", bytes);
3057
                                        //~ rtp_header_t *rtp = (rtp_header_t *)buffer;
3058
                                        //~ JANUS_LOG(LOG_VERB, " ... parsed RTP packet (ssrc=%u, pt=%u, seq=%u, ts=%u)...\n",
3059
                                                //~ ntohl(rtp->ssrc), rtp->type, ntohs(rtp->seq_number), ntohl(rtp->timestamp));
3060
                                        if(session->media.video_ssrc_peer == 0) {
3061
                                                rtp_header *header = (rtp_header *)buffer;
3062
                                                session->media.video_ssrc_peer = ntohl(header->ssrc);
3063
                                                JANUS_LOG(LOG_VERB, "Got SIP peer video SSRC: %"SCNu32"\n", session->media.video_ssrc_peer);
3064
                                        }
3065
                                        /* Is this SRTP? */
3066
                                        if(session->media.has_srtp_remote) {
3067
                                                int buflen = bytes;
3068
                                                err_status_t res = srtp_unprotect(session->media.video_srtp_in, buffer, &buflen);
3069
                                                if(res != err_status_ok && res != err_status_replay_fail && res != err_status_replay_old) {
3070
                                                        rtp_header *header = (rtp_header *)buffer;
3071
                                                        guint32 timestamp = ntohl(header->timestamp);
3072
                                                        guint16 seq = ntohs(header->seq_number);
3073
                                                        JANUS_LOG(LOG_ERR, "[SIP-%s] Video SRTP unprotect error: %s (len=%d-->%d, ts=%"SCNu32", seq=%"SCNu16")\n",
3074
                                                                session->account.username, janus_sip_get_srtp_error(res), bytes, buflen, timestamp, seq);
3075
                                                        continue;
3076
                                                }
3077
                                                bytes = buflen;
3078
                                        }
3079
                                        /* Save the frame if we're recording */
3080
                                        janus_recorder_save_frame(session->vrc_peer, buffer, bytes);
3081
                                        /* Relay to browser */
3082
                                        gateway->relay_rtp(session->handle, 1, buffer, bytes);
3083
                                        continue;
3084
                                } else if(session->media.video_rtcp_fd != -1 && fds[i].fd == session->media.video_rtcp_fd) {
3085
                                        /* Got something video (RTCP) */
3086
                                        addrlen = sizeof(remote);
3087
                                        bytes = recvfrom(session->media.video_rtcp_fd, buffer, 1500, 0, (struct sockaddr*)&remote, &addrlen);
3088
                                        //~ JANUS_LOG(LOG_VERB, "************************\nGot %d bytes on the video RTCP channel...\n", bytes);
3089
                                        /* Is this SRTCP? */
3090
                                        if(session->media.has_srtp_remote) {
3091
                                                int buflen = bytes;
3092
                                                err_status_t res = srtp_unprotect_rtcp(session->media.video_srtp_in, buffer, &buflen);
3093
                                                if(res != err_status_ok && res != err_status_replay_fail && res != err_status_replay_old) {
3094
                                                        JANUS_LOG(LOG_ERR, "[SIP-%s] Video SRTP unprotect error: %s (len=%d-->%d)\n",
3095
                                                                session->account.username, janus_sip_get_srtp_error(res), bytes, buflen);
3096
                                                        continue;
3097
                                                }
3098
                                                bytes = buflen;
3099
                                        }
3100
                                        /* Relay to browser */
3101
                                        gateway->relay_rtcp(session->handle, 1, buffer, bytes);
3102
                                        continue;
3103
                                }
3104
                        }
3105
                }
3106
        }
3107
        if(session->media.audio_rtp_fd != -1) {
3108
                close(session->media.audio_rtp_fd);
3109
                session->media.audio_rtp_fd = -1;
3110
        }
3111
        if(session->media.audio_rtcp_fd != -1) {
3112
                close(session->media.audio_rtcp_fd);
3113
                session->media.audio_rtcp_fd = -1;
3114
        }
3115
        session->media.local_audio_rtp_port = 0;
3116
        session->media.local_audio_rtcp_port = 0;
3117
        session->media.audio_ssrc = 0;
3118
        if(session->media.video_rtp_fd != -1) {
3119
                close(session->media.video_rtp_fd);
3120
                session->media.video_rtp_fd = -1;
3121
        }
3122
        if(session->media.video_rtcp_fd != -1) {
3123
                close(session->media.video_rtcp_fd);
3124
                session->media.video_rtcp_fd = -1;
3125
        }
3126
        session->media.local_video_rtp_port = 0;
3127
        session->media.local_video_rtcp_port = 0;
3128
        session->media.video_ssrc = 0;
3129
        /* Clean up SRTP stuff, if needed */
3130
        janus_sip_srtp_cleanup(session);
3131
        /* Done */
3132
        JANUS_LOG(LOG_VERB, "Leaving SIP relay thread\n");
3133
        g_thread_unref(g_thread_self());
3134
        return NULL;
3135
}
3136

    
3137

    
3138
/* Sofia Event thread */
3139
gpointer janus_sip_sofia_thread(gpointer user_data) {
3140
        janus_sip_session *session = (janus_sip_session *)user_data;
3141
        if(session == NULL || session->account.username == NULL) {
3142
                g_thread_unref(g_thread_self());
3143
                return NULL;
3144
        }
3145
        JANUS_LOG(LOG_VERB, "Joining sofia loop thread (%s)...\n", session->account.username);
3146
        session->stack = g_malloc0(sizeof(ssip_t));
3147
        session->stack->session = session;
3148
        session->stack->s_nua = NULL;
3149
        session->stack->s_nh_r = NULL;
3150
        session->stack->s_nh_i = NULL;
3151
        session->stack->s_root = su_root_create(session->stack);
3152
        su_home_init(session->stack->s_home);
3153
        JANUS_LOG(LOG_VERB, "Setting up sofia stack (sip:%s@%s)\n", session->account.username, local_ip);
3154
        char sip_url[128];
3155
        char sips_url[128];
3156
        char *ipv6;
3157
        ipv6 = strstr(local_ip, ":");
3158
        g_snprintf(sip_url, sizeof(sip_url), "sip:%s%s%s:*", ipv6 ? "[" : "", local_ip, ipv6 ? "]" : "");
3159
        g_snprintf(sips_url, sizeof(sips_url), "sips:%s%s%s:*", ipv6 ? "[" : "", local_ip, ipv6 ? "]" : "");
3160
        char outbound_options[256] = "use-rport no-validate";
3161
        if(keepalive_interval > 0)
3162
                g_strlcat(outbound_options, " options-keepalive", sizeof(outbound_options));
3163
        if(!behind_nat)
3164
                g_strlcat(outbound_options, " no-natify", sizeof(outbound_options));
3165
        session->stack->s_nua = nua_create(session->stack->s_root,
3166
                                janus_sip_sofia_callback,
3167
                                session,
3168
                                SIPTAG_ALLOW_STR("INVITE, ACK, BYE, CANCEL, OPTIONS"),
3169
                                NUTAG_M_USERNAME(session->account.username),
3170
                                NUTAG_URL(sip_url),
3171
                                TAG_IF(session->account.sips, NUTAG_SIPS_URL(sips_url)),
3172
                                SIPTAG_USER_AGENT_STR(session->account.user_agent ? session->account.user_agent : user_agent),
3173
                                NUTAG_KEEPALIVE(keepalive_interval * 1000),        /* Sofia expects it in milliseconds */
3174
                                NUTAG_OUTBOUND(outbound_options),
3175
                                SIPTAG_SUPPORTED(NULL),
3176
                                TAG_NULL());
3177
        su_root_run(session->stack->s_root);
3178
        /* When we get here, we're done */
3179
        nua_destroy(session->stack->s_nua);
3180
        su_root_destroy(session->stack->s_root);
3181
        session->stack->s_root = NULL;
3182
        su_home_deinit(session->stack->s_home);
3183
        su_home_unref(session->stack->s_home);
3184
        su_deinit();
3185
        if (session->stack) {
3186
                g_free(session->stack);
3187
                session->stack = NULL;
3188
        }
3189
        //~ stop = 1;
3190
        JANUS_LOG(LOG_VERB, "Leaving sofia loop thread...\n");
3191
        g_thread_unref(g_thread_self());
3192
        /* Cleaning up and removing the session is done in a lazy way */
3193
        janus_mutex_lock(&sessions_mutex);
3194
        old_sessions = g_list_append(old_sessions, session);
3195
        janus_mutex_unlock(&sessions_mutex);
3196
        return NULL;
3197
}