Statistics
| Branch: | Revision:

janus-gateway / plugins / janus_sip.c @ 4fa7a2cf

History | View | Annotate | Download (127 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, char *message, char *sdp_type, char *sdp);
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
char *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
        char *message;
193
        char *sdp_type;
194
        char *sdp;
195
} janus_sip_message;
196
static GAsyncQueue *messages = NULL;
197
static janus_sip_message exit_message;
198

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

    
203
        msg->handle = NULL;
204

    
205
        g_free(msg->transaction);
206
        msg->transaction = NULL;
207
        g_free(msg->message);
208
        msg->message = NULL;
209
        g_free(msg->sdp_type);
210
        msg->sdp_type = NULL;
211
        g_free(msg->sdp);
212
        msg->sdp = NULL;
213

    
214
        g_free(msg);
215
}
216

    
217

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

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

    
246

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

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

    
272

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

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

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

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

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

    
346

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

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

    
362

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

    
503

    
504
/* Sofia Event thread */
505
gpointer janus_sip_sofia_thread(gpointer user_data);
506
/* Sofia callbacks */
507
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[]);
508
/* SDP parsing and manipulation */
509
void janus_sip_sdp_process(janus_sip_session *session, sdp_session_t *sdp, gboolean answer);
510
char *janus_sip_sdp_manipulate(janus_sip_session *session, sdp_session_t *sdp, gboolean answer);
511
/* Media */
512
static int janus_sip_allocate_local_ports(janus_sip_session *session);
513
static void *janus_sip_relay_thread(void *data);
514

    
515

    
516
/* URI parsing utilies */
517

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

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

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

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

    
556

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

    
638

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

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

    
662
error:
663
        if (fd != -1)
664
                close(fd);
665
        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");
666
        g_strlcpy(buf, "127.0.0.1", buflen);
667
}
668

    
669

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

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

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

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

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

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

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

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

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

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

    
767
        g_atomic_int_set(&initialized, 1);
768

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

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

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

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

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

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

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

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

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

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

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

    
981
struct janus_plugin_result *janus_sip_handle_message(janus_plugin_session *handle, char *transaction, char *message, char *sdp_type, char *sdp) {
982
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
983
                return janus_plugin_result_new(JANUS_PLUGIN_ERROR, g_atomic_int_get(&stopping) ? "Shutting down" : "Plugin not initialized");
984
        JANUS_LOG(LOG_VERB, "%s\n", message);
985
        janus_sip_message *msg = g_malloc0(sizeof(janus_sip_message));
986
        msg->handle = handle;
987
        msg->transaction = transaction;
988
        msg->message = message;
989
        msg->sdp_type = sdp_type;
990
        msg->sdp = sdp;
991
        g_async_queue_push(messages, msg);
992

    
993
        /* All the requests to this plugin are handled asynchronously */
994
        return janus_plugin_result_new(JANUS_PLUGIN_OK_WAIT, NULL);
995
}
996

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

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

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

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

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

    
1281
                if(!strcasecmp(request_text, "register")) {
1282
                        /* Send a REGISTER */
1283
                        if(session->account.registration_status > janus_sip_registration_status_unregistered) {
1284
                                JANUS_LOG(LOG_ERR, "Already registered (%s)\n", session->account.username);
1285
                                error_code = JANUS_SIP_ERROR_ALREADY_REGISTERED;
1286
                                g_snprintf(error_cause, 512, "Already registered (%s)", session->account.username);
1287
                                goto error;
1288
                        }
1289

    
1290
                        /* Cleanup old values */
1291
                        if(session->account.identity != NULL)
1292
                                g_free(session->account.identity);
1293
                        session->account.identity = NULL;
1294
                        session->account.sips = TRUE;
1295
                        if(session->account.username != NULL)
1296
                                g_free(session->account.username);
1297
                        session->account.username = NULL;
1298
                        if(session->account.display_name != NULL)
1299
                                g_free(session->account.display_name);
1300
                        session->account.display_name = NULL;
1301
                        if(session->account.authuser != NULL)
1302
                                g_free(session->account.authuser);
1303
                        session->account.authuser = NULL;
1304
                        if(session->account.secret != NULL)
1305
                                g_free(session->account.secret);
1306
                        session->account.secret = NULL;
1307
                        session->account.secret_type = janus_sip_secret_type_unknown;
1308
                        if(session->account.proxy != NULL)
1309
                                g_free(session->account.proxy);
1310
                        session->account.proxy = NULL;
1311
                        if(session->account.user_agent != NULL)
1312
                                g_free(session->account.user_agent);
1313
                        session->account.user_agent = NULL;
1314
                        session->account.registration_status = janus_sip_registration_status_unregistered;
1315

    
1316
                        gboolean guest = FALSE;
1317
                        JANUS_VALIDATE_JSON_OBJECT(root, register_parameters,
1318
                                error_code, error_cause, TRUE,
1319
                                JANUS_SIP_ERROR_MISSING_ELEMENT, JANUS_SIP_ERROR_INVALID_ELEMENT);
1320
                        if(error_code != 0)
1321
                                goto error;
1322
                        json_t *type = json_object_get(root, "type");
1323
                        if(type != NULL) {
1324
                                const char *type_text = json_string_value(type);
1325
                                if(!strcmp(type_text, "guest")) {
1326
                                        JANUS_LOG(LOG_INFO, "Registering as a guest\n");
1327
                                        guest = TRUE;
1328
                                } else {
1329
                                        JANUS_LOG(LOG_WARN, "Unknown type '%s', ignoring...\n", type_text);
1330
                                }
1331
                        }
1332

    
1333
                        gboolean send_register = TRUE;
1334
                        json_t *do_register = json_object_get(root, "send_register");
1335
                        if(do_register != NULL) {
1336
                                if(guest) {
1337
                                        JANUS_LOG(LOG_ERR, "Conflicting elements: send_register cannot be true if guest is true\n");
1338
                                        error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
1339
                                        g_snprintf(error_cause, 512, "Conflicting elements: send_register cannot be true if guest is true");
1340
                                        goto error;
1341
                                }
1342
                                send_register = json_is_true(do_register);
1343
                        }
1344

    
1345
                        gboolean sips = TRUE;
1346
                        json_t *do_sips = json_object_get(root, "sips");
1347
                        if(do_sips != NULL) {
1348
                                sips = json_is_true(do_sips);
1349
                        }
1350

    
1351
                        /* Parse address */
1352
                        json_t *proxy = json_object_get(root, "proxy");
1353
                        const char *proxy_text = NULL;
1354

    
1355
                        if (proxy && !json_is_null(proxy)) {
1356
                                /* Has to be validated separately because it could be null */
1357
                                JANUS_VALIDATE_JSON_OBJECT(root, proxy_parameters,
1358
                                        error_code, error_cause, TRUE,
1359
                                        JANUS_SIP_ERROR_MISSING_ELEMENT, JANUS_SIP_ERROR_INVALID_ELEMENT);
1360
                                if(error_code != 0)
1361
                                        goto error;
1362
                                proxy_text = json_string_value(proxy);
1363
                                janus_sip_uri_t proxy_uri;
1364
                                if (janus_sip_parse_proxy_uri(&proxy_uri, proxy_text) < 0) {
1365
                                        JANUS_LOG(LOG_ERR, "Invalid proxy address %s\n", proxy_text);
1366
                                        error_code = JANUS_SIP_ERROR_INVALID_ADDRESS;
1367
                                        g_snprintf(error_cause, 512, "Invalid proxy address %s\n", proxy_text);
1368
                                        goto error;
1369
                                }
1370
                        }
1371

    
1372
                        /* Parse register TTL */
1373
                        int ttl = register_ttl;
1374
                        json_t *reg_ttl = json_object_get(root, "register_ttl");
1375
                        if (reg_ttl && json_is_integer(reg_ttl))
1376
                                ttl = json_integer_value(reg_ttl);
1377
                        if (ttl <= 0)
1378
                                ttl = JANUS_DEFAULT_REGISTER_TTL;
1379

    
1380
                        /* Parse display name */
1381
                        const char* display_name_text = NULL;
1382
                        json_t *display_name = json_object_get(root, "display_name");
1383
                        if (display_name && json_is_string(display_name))
1384
                                display_name_text = json_string_value(display_name);
1385

    
1386
                        /* Parse user agent */
1387
                        const char* user_agent_text = NULL;
1388
                        json_t *user_agent = json_object_get(root, "user_agent");
1389
                        if (user_agent && json_is_string(user_agent))
1390
                                user_agent_text = json_string_value(user_agent);
1391

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

    
1459
                        session->account.identity = g_strdup(username_text);
1460
                        session->account.sips = sips;
1461
                        session->account.username = g_strdup(user_id);
1462
                        if (display_name_text) {
1463
                                session->account.display_name = g_strdup(display_name_text);
1464
                        }
1465
                        if (user_agent_text) {
1466
                                session->account.user_agent = g_strdup(user_agent_text);
1467
                        }
1468
                        if (proxy_text) {
1469
                                session->account.proxy = g_strdup(proxy_text);
1470
                        }
1471

    
1472
                        session->account.registration_status = janus_sip_registration_status_registering;
1473
                        if(session->stack == NULL) {
1474
                                /* Start the thread first */
1475
                                GError *error = NULL;
1476
                                g_thread_try_new("worker", janus_sip_sofia_thread, session, &error);
1477
                                if(error != NULL) {
1478
                                        JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the SIP Sofia thread...\n", error->code, error->message ? error->message : "??");
1479
                                        error_code = JANUS_SIP_ERROR_UNKNOWN_ERROR;
1480
                                        g_snprintf(error_cause, 512, "Got error %d (%s) trying to launch the SIP Sofia thread", error->code, error->message ? error->message : "??");
1481
                                        goto error;
1482
                                }
1483
                                long int timeout = 0;
1484
                                while(session->stack == NULL || session->stack->s_nua == NULL) {
1485
                                        g_usleep(100000);
1486
                                        timeout += 100000;
1487
                                        if(timeout >= 2000000) {
1488
                                                break;
1489
                                        }
1490
                                }
1491
                                if(timeout >= 2000000) {
1492
                                        JANUS_LOG(LOG_ERR, "Two seconds passed and still no NUA, problems with the thread?\n");
1493
                                        error_code = JANUS_SIP_ERROR_UNKNOWN_ERROR;
1494
                                        g_snprintf(error_cause, 512, "Two seconds passed and still no NUA, problems with the thread?");
1495
                                        goto error;
1496
                                }
1497
                        }
1498
                        if(session->stack->s_nh_r != NULL) {
1499
                                nua_handle_destroy(session->stack->s_nh_r);
1500
                                session->stack->s_nh_r = NULL;
1501
                        }
1502

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

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

    
2137
                json_decref(root);
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
                char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
2144
                json_decref(event);
2145
                JANUS_LOG(LOG_VERB, "Pushing event: %s\n", event_text);
2146
                int ret = gateway->push_event(msg->handle, &janus_sip_plugin, msg->transaction, event_text, sdp_type, sdp);
2147
                JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
2148
                g_free(event_text);
2149
                if(sdp)
2150
                        g_free(sdp);
2151
                janus_sip_message_free(msg);
2152
                continue;
2153

    
2154
error:
2155
                {
2156
                        if(root != NULL)
2157
                                json_decref(root);
2158
                        /* Prepare JSON error event */
2159
                        json_t *event = json_object();
2160
                        json_object_set_new(event, "sip", json_string("event"));
2161
                        json_object_set_new(event, "error_code", json_integer(error_code));
2162
                        json_object_set_new(event, "error", json_string(error_cause));
2163
                        char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
2164
                        json_decref(event);
2165
                        JANUS_LOG(LOG_VERB, "Pushing event: %s\n", event_text);
2166
                        int ret = gateway->push_event(msg->handle, &janus_sip_plugin, msg->transaction, event_text, NULL, NULL);
2167
                        JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
2168
                        g_free(event_text);
2169
                        janus_sip_message_free(msg);
2170
                }
2171
        }
2172
        JANUS_LOG(LOG_VERB, "Leaving SIP handler thread\n");
2173
        return NULL;
2174
}
2175

    
2176

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

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

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

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

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

    
2889
/* Thread to relay RTP/RTCP frames coming from the SIP peer */
2890
static void *janus_sip_relay_thread(void *data) {
2891
        janus_sip_session *session = (janus_sip_session *)data;
2892
        if(!session || !session->account.username || !session->callee) {
2893
                g_thread_unref(g_thread_self());
2894
                return NULL;
2895
        }
2896
        JANUS_LOG(LOG_VERB, "Starting relay thread (%s <--> %s)\n", session->account.username, session->callee);
2897

    
2898
        gboolean have_server_ip = TRUE;
2899
        struct sockaddr_in server_addr;
2900
        memset(&server_addr, 0, sizeof(server_addr));
2901
        server_addr.sin_family = AF_INET;
2902
        if((inet_aton(session->media.remote_ip, &server_addr.sin_addr)) <= 0) {        /* Not a numeric IP... */
2903
                struct hostent *host = gethostbyname(session->media.remote_ip);        /* ...resolve name */
2904
                if(!host) {
2905
                        JANUS_LOG(LOG_ERR, "[SIP-%s] Couldn't get host (%s)\n", session->account.username, session->media.remote_ip);
2906
                        have_server_ip = FALSE;
2907
                } else {
2908
                        server_addr.sin_addr = *(struct in_addr *)host->h_addr_list;
2909
                }
2910
        }
2911

    
2912
        /* Connect peers (FIXME This pretty much sucks right now) */
2913
        if(have_server_ip && session->media.remote_audio_rtp_port) {
2914
                server_addr.sin_port = htons(session->media.remote_audio_rtp_port);
2915
                if(connect(session->media.audio_rtp_fd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1) {
2916
                        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);
2917
                        JANUS_LOG(LOG_ERR, "[SIP-%s]   -- %d (%s)\n", session->account.username, errno, strerror(errno));
2918
                }
2919
        }
2920
        if(have_server_ip && session->media.remote_audio_rtcp_port) {
2921
                server_addr.sin_port = htons(session->media.remote_audio_rtcp_port);
2922
                if(connect(session->media.audio_rtcp_fd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1) {
2923
                        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);
2924
                        JANUS_LOG(LOG_ERR, "[SIP-%s]   -- %d (%s)\n", session->account.username, errno, strerror(errno));
2925
                }
2926
        }
2927
        if(have_server_ip && session->media.remote_video_rtp_port) {
2928
                server_addr.sin_port = htons(session->media.remote_video_rtp_port);
2929
                if(connect(session->media.video_rtp_fd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1) {
2930
                        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);
2931
                        JANUS_LOG(LOG_ERR, "[SIP-%s]   -- %d (%s)\n", session->account.username, errno, strerror(errno));
2932
                }
2933
        }
2934
        if(have_server_ip && session->media.remote_video_rtcp_port) {
2935
                server_addr.sin_port = htons(session->media.remote_video_rtcp_port);
2936
                if(connect(session->media.video_rtcp_fd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1) {
2937
                        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);
2938
                        JANUS_LOG(LOG_ERR, "[SIP-%s]   -- %d (%s)\n", session->account.username, errno, strerror(errno));
2939
                }
2940
        }
2941

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

    
3155

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