Statistics
| Branch: | Revision:

janus-gateway / plugins / janus_sip.c @ 1d54077e

History | View | Annotate | Download (153 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
 * \section sipapi SIP Plugin API
27
 *
28
 * All requests you can send in the SIP Plugin API are asynchronous,
29
 * which means all responses (successes and errors) will be delivered
30
 * as events with the same transaction.
31
 *
32
 * The supported requests are \c register , \c unregister , \c call ,
33
 * \c accept, \c info , \c message , \c dtmf_info , \c recording ,
34
 * \c hold , \c unhold and \c hangup . \c register can be used,
35
 * as the name suggests, to register a username at a SIP registrar to
36
 * call and be called, while \c unregister unregisters it; \c call is used
37
 * to send an INVITE to a different SIP URI through the plugin, while
38
 * \c accept is used to accept the call in case one is invited instead
39
 * of inviting; \c hold and \c unhold can be used respectively to put a
40
 * call on-hold and to resume it; \c info allows you to send a generic
41
 * SIP INFO request, while \c dtmf_info is focused on using INFO for DTMF
42
 * instead; \c message is the method you use to send a SIP message
43
 * to the other peer; \c recording is used, instead, to record the
44
 * conversation to one or more .mjr files (depending on the direction you
45
 * want to record); finally, \c hangup can be used to terminate the
46
 * communication at any time, either to hangup (BYE) an ongoing call or
47
 * to cancel/decline (CANCEL/BYE) a call that hasn't started yet.
48
 *
49
 * Actual API docs: TBD.
50
 *
51
 * \ingroup plugins
52
 * \ref plugins
53
 */
54

    
55
#include "plugin.h"
56

    
57
#include <arpa/inet.h>
58
#include <net/if.h>
59

    
60
#include <jansson.h>
61

    
62
#include <sofia-sip/msg_header.h>
63
#include <sofia-sip/nua.h>
64
#include <sofia-sip/sdp.h>
65
#include <sofia-sip/sip_status.h>
66
#include <sofia-sip/url.h>
67
#include <sofia-sip/tport_tag.h>
68
#include <sofia-sip/su_log.h>
69

    
70
#include "../debug.h"
71
#include "../apierror.h"
72
#include "../config.h"
73
#include "../mutex.h"
74
#include "../record.h"
75
#include "../rtp.h"
76
#include "../rtcp.h"
77
#include "../sdp-utils.h"
78
#include "../utils.h"
79
#include "../ip-utils.h"
80

    
81

    
82
/* Plugin information */
83
#define JANUS_SIP_VERSION                        6
84
#define JANUS_SIP_VERSION_STRING        "0.0.6"
85
#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."
86
#define JANUS_SIP_NAME                                "JANUS SIP plugin"
87
#define JANUS_SIP_AUTHOR                        "Meetecho s.r.l."
88
#define JANUS_SIP_PACKAGE                        "janus.plugin.sip"
89

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

    
110
/* Plugin setup */
111
static janus_plugin janus_sip_plugin =
112
        JANUS_PLUGIN_INIT (
113
                .init = janus_sip_init,
114
                .destroy = janus_sip_destroy,
115

    
116
                .get_api_compatibility = janus_sip_get_api_compatibility,
117
                .get_version = janus_sip_get_version,
118
                .get_version_string = janus_sip_get_version_string,
119
                .get_description = janus_sip_get_description,
120
                .get_name = janus_sip_get_name,
121
                .get_author = janus_sip_get_author,
122
                .get_package = janus_sip_get_package,
123

    
124
                .create_session = janus_sip_create_session,
125
                .handle_message = janus_sip_handle_message,
126
                .setup_media = janus_sip_setup_media,
127
                .incoming_rtp = janus_sip_incoming_rtp,
128
                .incoming_rtcp = janus_sip_incoming_rtcp,
129
                .hangup_media = janus_sip_hangup_media,
130
                .destroy_session = janus_sip_destroy_session,
131
                .query_session = janus_sip_query_session,
132
        );
133

    
134
/* Plugin creator */
135
janus_plugin *create(void) {
136
        JANUS_LOG(LOG_VERB, "%s created!\n", JANUS_SIP_NAME);
137
        return &janus_sip_plugin;
138
}
139

    
140
/* Parameter validation */
141
static struct janus_json_parameter request_parameters[] = {
142
        {"request", JSON_STRING, JANUS_JSON_PARAM_REQUIRED}
143
};
144
static struct janus_json_parameter register_parameters[] = {
145
        {"type", JSON_STRING, 0},
146
        {"send_register", JANUS_JSON_BOOL, 0},
147
        {"sips", JANUS_JSON_BOOL, 0},
148
        {"username", JSON_STRING, JANUS_JSON_PARAM_REQUIRED},
149
        {"secret", JSON_STRING, 0},
150
        {"ha1_secret", JSON_STRING, 0},
151
        {"authuser", JSON_STRING, 0},
152
        {"headers", JSON_OBJECT, 0},
153
        {"refresh", JANUS_JSON_BOOL, 0}
154
};
155
static struct janus_json_parameter proxy_parameters[] = {
156
        {"proxy", JSON_STRING, 0},
157
        {"outbound_proxy", JSON_STRING, 0}
158
};
159
static struct janus_json_parameter call_parameters[] = {
160
        {"uri", JSON_STRING, JANUS_JSON_PARAM_REQUIRED},
161
        {"autoack", JANUS_JSON_BOOL, 0},
162
        {"headers", JSON_OBJECT, 0},
163
        {"srtp", JSON_STRING, 0}
164
};
165
static struct janus_json_parameter accept_parameters[] = {
166
        {"srtp", JSON_STRING, 0}
167
};
168
static struct janus_json_parameter recording_parameters[] = {
169
        {"action", JSON_STRING, JANUS_JSON_PARAM_REQUIRED},
170
        {"audio", JANUS_JSON_BOOL, 0},
171
        {"video", JANUS_JSON_BOOL, 0},
172
        {"peer_audio", JANUS_JSON_BOOL, 0},
173
        {"peer_video", JANUS_JSON_BOOL, 0},
174
        {"filename", JSON_STRING, 0}
175
};
176
static struct janus_json_parameter dtmf_info_parameters[] = {
177
        {"digit", JSON_STRING, JANUS_JSON_PARAM_REQUIRED},
178
        {"duration", JSON_INTEGER, JANUS_JSON_PARAM_POSITIVE}
179
};
180
static struct janus_json_parameter info_parameters[] = {
181
        {"type", JSON_STRING, JANUS_JSON_PARAM_REQUIRED},
182
        {"content", JSON_STRING, JANUS_JSON_PARAM_REQUIRED}
183
};
184
static struct janus_json_parameter sipmessage_parameters[] = {
185
        {"content", JSON_STRING, JANUS_JSON_PARAM_REQUIRED}
186
};
187

    
188
/* Useful stuff */
189
static volatile gint initialized = 0, stopping = 0;
190
static gboolean notify_events = TRUE;
191
static janus_callbacks *gateway = NULL;
192

    
193
static char *local_ip = NULL;
194
static int keepalive_interval = 120;
195
static gboolean behind_nat = FALSE;
196
static char *user_agent;
197
#define JANUS_DEFAULT_REGISTER_TTL        3600
198
static int register_ttl = JANUS_DEFAULT_REGISTER_TTL;
199

    
200
static GThread *handler_thread;
201
static GThread *watchdog;
202
static void *janus_sip_handler(void *data);
203

    
204
typedef struct janus_sip_message {
205
        janus_plugin_session *handle;
206
        char *transaction;
207
        json_t *message;
208
        json_t *jsep;
209
} janus_sip_message;
210
static GAsyncQueue *messages = NULL;
211
static janus_sip_message exit_message;
212

    
213
static void janus_sip_message_free(janus_sip_message *msg) {
214
        if(!msg || msg == &exit_message)
215
                return;
216

    
217
        msg->handle = NULL;
218

    
219
        g_free(msg->transaction);
220
        msg->transaction = NULL;
221
        if(msg->message)
222
                json_decref(msg->message);
223
        msg->message = NULL;
224
        if(msg->jsep)
225
                json_decref(msg->jsep);
226
        msg->jsep = NULL;
227

    
228
        g_free(msg);
229
}
230

    
231

    
232
typedef enum {
233
        janus_sip_registration_status_disabled = -2,
234
        janus_sip_registration_status_failed = -1,
235
        janus_sip_registration_status_unregistered = 0,
236
        janus_sip_registration_status_registering,
237
        janus_sip_registration_status_registered,
238
        janus_sip_registration_status_unregistering,
239
} janus_sip_registration_status;
240

    
241
static const char *janus_sip_registration_status_string(janus_sip_registration_status status) {
242
        switch(status) {
243
                case janus_sip_registration_status_disabled:
244
                        return "disabled";
245
                case janus_sip_registration_status_failed:
246
                        return "failed";
247
                case janus_sip_registration_status_unregistered:
248
                        return "unregistered";
249
                case janus_sip_registration_status_registering:
250
                        return "registering";
251
                case janus_sip_registration_status_registered:
252
                        return "registered";
253
                case janus_sip_registration_status_unregistering:
254
                        return "unregistering";
255
                default:
256
                        return "unknown";
257
        }
258
}
259

    
260

    
261
typedef enum {
262
        janus_sip_call_status_idle = 0,
263
        janus_sip_call_status_inviting,
264
        janus_sip_call_status_invited,
265
        janus_sip_call_status_incall,
266
        janus_sip_call_status_closing,
267
} janus_sip_call_status;
268

    
269
static const char *janus_sip_call_status_string(janus_sip_call_status status) {
270
        switch(status) {
271
                case janus_sip_call_status_idle:
272
                        return "idle";
273
                case janus_sip_call_status_inviting:
274
                        return "inviting";
275
                case janus_sip_call_status_invited:
276
                        return "invited";
277
                case janus_sip_call_status_incall:
278
                        return "incall";
279
                case janus_sip_call_status_closing:
280
                        return "closing";
281
                default:
282
                        return "unknown";
283
        }
284
}
285

    
286

    
287
/* Sofia stuff */
288
typedef struct ssip_s ssip_t;
289
typedef struct ssip_oper_s ssip_oper_t;
290

    
291
typedef enum {
292
        janus_sip_secret_type_plaintext = 1,
293
        janus_sip_secret_type_hashed = 2,
294
        janus_sip_secret_type_unknown
295
} janus_sip_secret_type;
296

    
297
typedef struct janus_sip_account {
298
        char *identity;
299
        char *user_agent;                /* Used to override the general UA string */
300
        gboolean sips;
301
        char *username;
302
        char *display_name;                /* Used for outgoing calls in the From header */
303
        char *authuser;                        /**< username to use for authentication */
304
        char *secret;
305
        janus_sip_secret_type secret_type;
306
        int sip_port;
307
        char *proxy;
308
        char *outbound_proxy;
309
        janus_sip_registration_status registration_status;
310
} janus_sip_account;
311

    
312
typedef struct janus_sip_media {
313
        char *remote_ip;
314
        gboolean ready;
315
        gboolean autoack;
316
        gboolean require_srtp, has_srtp_local, has_srtp_remote;
317
        gboolean on_hold;
318
        gboolean has_audio;
319
        int audio_rtp_fd, audio_rtcp_fd;
320
        int local_audio_rtp_port, remote_audio_rtp_port;
321
        int local_audio_rtcp_port, remote_audio_rtcp_port;
322
        guint32 audio_ssrc, audio_ssrc_peer;
323
        int audio_pt;
324
        const char *audio_pt_name;
325
        srtp_t audio_srtp_in, audio_srtp_out;
326
        srtp_policy_t audio_remote_policy, audio_local_policy;
327
        int audio_srtp_suite_in, audio_srtp_suite_out;
328
        gboolean audio_send;
329
        janus_sdp_mdirection pre_hold_audio_dir;
330
        gboolean has_video;
331
        int video_rtp_fd, video_rtcp_fd;
332
        int local_video_rtp_port, remote_video_rtp_port;
333
        int local_video_rtcp_port, remote_video_rtcp_port;
334
        guint32 video_ssrc, video_ssrc_peer;
335
        int video_pt;
336
        const char *video_pt_name;
337
        srtp_t video_srtp_in, video_srtp_out;
338
        srtp_policy_t video_remote_policy, video_local_policy;
339
        int video_srtp_suite_in, video_srtp_suite_out;
340
        gboolean video_send;
341
        janus_sdp_mdirection pre_hold_video_dir;
342
        janus_rtp_switching_context context;
343
        int pipefd[2];
344
        gboolean updated;
345
} janus_sip_media;
346

    
347
typedef struct janus_sip_session {
348
        janus_plugin_session *handle;
349
        ssip_t *stack;
350
        janus_sip_account account;
351
        janus_sip_call_status status;
352
        janus_sip_media media;
353
        char *transaction;
354
        char *callee;
355
        char *callid;
356
        janus_sdp *sdp;                                /* The SDP this user sent */
357
        janus_recorder *arc;                /* The Janus recorder instance for this user's audio, if enabled */
358
        janus_recorder *arc_peer;        /* The Janus recorder instance for the peer's audio, if enabled */
359
        janus_recorder *vrc;                /* The Janus recorder instance for this user's video, if enabled */
360
        janus_recorder *vrc_peer;        /* The Janus recorder instance for the peer's video, if enabled */
361
        janus_mutex rec_mutex;                /* Mutex to protect the recorders from race conditions */
362
        volatile gint hangingup;
363
        gint64 destroyed;        /* Time at which this session was marked as destroyed */
364
        janus_mutex mutex;
365
} janus_sip_session;
366
static GHashTable *sessions;
367
static GList *old_sessions;
368
static GHashTable *identities;
369
static GHashTable *callids;
370
static janus_mutex sessions_mutex;
371

    
372

    
373
#undef SU_ROOT_MAGIC_T
374
#define SU_ROOT_MAGIC_T        ssip_t
375
#undef NUA_MAGIC_T
376
#define NUA_MAGIC_T                ssip_t
377
#undef NUA_HMAGIC_T
378
#define NUA_HMAGIC_T        ssip_oper_t
379

    
380
struct ssip_s {
381
        su_home_t s_home[1];
382
        su_root_t *s_root;
383
        nua_t *s_nua;
384
        nua_handle_t *s_nh_r, *s_nh_i;
385
        janus_sip_session *session;
386
};
387

    
388

    
389
/* SRTP stuff (in case we need SDES) */
390
static int janus_sip_srtp_set_local(janus_sip_session *session, gboolean video, char **crypto) {
391
        if(session == NULL)
392
                return -1;
393
        /* Generate key/salt */
394
        uint8_t *key = g_malloc0(SRTP_MASTER_LENGTH);
395
        srtp_crypto_get_random(key, SRTP_MASTER_LENGTH);
396
        /* Set SRTP policies */
397
        srtp_policy_t *policy = video ? &session->media.video_local_policy : &session->media.audio_local_policy;
398
        srtp_crypto_policy_set_rtp_default(&(policy->rtp));
399
        srtp_crypto_policy_set_rtcp_default(&(policy->rtcp));
400
        policy->ssrc.type = ssrc_any_inbound;
401
        policy->key = key;
402
        policy->next = NULL;
403
        /* Create SRTP context */
404
        srtp_err_status_t res = srtp_create(video ? &session->media.video_srtp_out : &session->media.audio_srtp_out, policy);
405
        if(res != srtp_err_status_ok) {
406
                /* Something went wrong... */
407
                JANUS_LOG(LOG_ERR, "Oops, error creating outbound SRTP session: %d (%s)\n", res, janus_srtp_error_str(res));
408
                g_free(key);
409
                policy->key = NULL;
410
                return -2;
411
        }
412
        /* Base64 encode the salt */
413
        *crypto = g_base64_encode(key, SRTP_MASTER_LENGTH);
414
        if((video && session->media.video_srtp_out) || (!video && session->media.audio_srtp_out)) {
415
                JANUS_LOG(LOG_VERB, "%s outbound SRTP session created\n", video ? "Video" : "Audio");
416
        }
417
        return 0;
418
}
419
static int janus_sip_srtp_set_remote(janus_sip_session *session, gboolean video, const char *crypto, int suite) {
420
        if(session == NULL || crypto == NULL)
421
                return -1;
422
        /* Base64 decode the crypto string and set it as the remote SRTP context */
423
        gsize len = 0;
424
        guchar *decoded = g_base64_decode(crypto, &len);
425
        if(len < SRTP_MASTER_LENGTH) {
426
                /* FIXME Can this happen? */
427
                g_free(decoded);
428
                return -2;
429
        }
430
        /* Set SRTP policies */
431
        srtp_policy_t *policy = video ? &session->media.video_remote_policy : &session->media.audio_remote_policy;
432
        srtp_crypto_policy_set_rtp_default(&(policy->rtp));
433
        srtp_crypto_policy_set_rtcp_default(&(policy->rtcp));
434
        if(suite == 32) {
435
                srtp_crypto_policy_set_aes_cm_128_hmac_sha1_32(&(policy->rtp));
436
                srtp_crypto_policy_set_aes_cm_128_hmac_sha1_32(&(policy->rtcp));
437
        } else if(suite == 80) {
438
                srtp_crypto_policy_set_aes_cm_128_hmac_sha1_80(&(policy->rtp));
439
                srtp_crypto_policy_set_aes_cm_128_hmac_sha1_80(&(policy->rtcp));
440
        }
441
        policy->ssrc.type = ssrc_any_inbound;
442
        policy->key = decoded;
443
        policy->next = NULL;
444
        /* Create SRTP context */
445
        srtp_err_status_t res = srtp_create(video ? &session->media.video_srtp_in : &session->media.audio_srtp_in, policy);
446
        if(res != srtp_err_status_ok) {
447
                /* Something went wrong... */
448
                JANUS_LOG(LOG_ERR, "Oops, error creating inbound SRTP session: %d (%s)\n", res, janus_srtp_error_str(res));
449
                g_free(decoded);
450
                policy->key = NULL;
451
                return -2;
452
        }
453
        if((video && session->media.video_srtp_in) || (!video && session->media.audio_srtp_in)) {
454
                JANUS_LOG(LOG_VERB, "%s inbound SRTP session created\n", video ? "Video" : "Audio");
455
        }
456
        return 0;
457
}
458
static void janus_sip_srtp_cleanup(janus_sip_session *session) {
459
        if(session == NULL)
460
                return;
461
        session->media.autoack = TRUE;
462
        session->media.require_srtp = FALSE;
463
        session->media.has_srtp_local = FALSE;
464
        session->media.has_srtp_remote = FALSE;
465
        /* Audio */
466
        if(session->media.audio_srtp_out)
467
                srtp_dealloc(session->media.audio_srtp_out);
468
        session->media.audio_srtp_out = NULL;
469
        g_free(session->media.audio_local_policy.key);
470
        session->media.audio_local_policy.key = NULL;
471
        session->media.audio_srtp_suite_out = 0;
472
        if(session->media.audio_srtp_in)
473
                srtp_dealloc(session->media.audio_srtp_in);
474
        session->media.audio_srtp_in = NULL;
475
        g_free(session->media.audio_remote_policy.key);
476
        session->media.audio_remote_policy.key = NULL;
477
        session->media.audio_srtp_suite_in = 0;
478
        /* Video */
479
        if(session->media.video_srtp_out)
480
                srtp_dealloc(session->media.video_srtp_out);
481
        session->media.video_srtp_out = NULL;
482
        g_free(session->media.video_local_policy.key);
483
        session->media.video_local_policy.key = NULL;
484
        session->media.video_srtp_suite_out = 0;
485
        if(session->media.video_srtp_in)
486
                srtp_dealloc(session->media.video_srtp_in);
487
        session->media.video_srtp_in = NULL;
488
        g_free(session->media.video_remote_policy.key);
489
        session->media.video_remote_policy.key = NULL;
490
        session->media.video_srtp_suite_in = 0;
491
}
492

    
493

    
494
/* Sofia Event thread */
495
gpointer janus_sip_sofia_thread(gpointer user_data);
496
/* Sofia callbacks */
497
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[]);
498
/* SDP parsing and manipulation */
499
void janus_sip_sdp_process(janus_sip_session *session, janus_sdp *sdp, gboolean answer, gboolean update, gboolean *changed);
500
char *janus_sip_sdp_manipulate(janus_sip_session *session, janus_sdp *sdp, gboolean answer);
501
/* Media */
502
static int janus_sip_allocate_local_ports(janus_sip_session *session);
503
static void *janus_sip_relay_thread(void *data);
504

    
505

    
506
/* URI parsing utilies */
507

    
508
#define JANUS_SIP_URI_MAXLEN        1024
509
typedef struct {
510
        char data[JANUS_SIP_URI_MAXLEN];
511
        url_t url[1];
512
} janus_sip_uri_t;
513

    
514
/* Parses a SIP URI (SIPS is not supported), returns 0 on success, -1 otherwise */
515
static int janus_sip_parse_uri(janus_sip_uri_t *sip_uri, const char *data) {
516
        g_strlcpy(sip_uri->data, data, JANUS_SIP_URI_MAXLEN);
517
        if (url_d(sip_uri->url, sip_uri->data) < 0 || sip_uri->url->url_type != url_sip)
518
                return -1;
519
        return 0;
520
}
521

    
522
/* Similar to the above function, but it also accepts SIPS URIs */
523
static int janus_sip_parse_proxy_uri(janus_sip_uri_t *sip_uri, const char *data) {
524
        g_strlcpy(sip_uri->data, data, JANUS_SIP_URI_MAXLEN);
525
        if (url_d(sip_uri->url, sip_uri->data) < 0 || (sip_uri->url->url_type != url_sip && sip_uri->url->url_type != url_sips))
526
                return -1;
527
        return 0;
528
}
529

    
530
/* Error codes */
531
#define JANUS_SIP_ERROR_UNKNOWN_ERROR                499
532
#define JANUS_SIP_ERROR_NO_MESSAGE                        440
533
#define JANUS_SIP_ERROR_INVALID_JSON                441
534
#define JANUS_SIP_ERROR_INVALID_REQUEST                442
535
#define JANUS_SIP_ERROR_MISSING_ELEMENT                443
536
#define JANUS_SIP_ERROR_INVALID_ELEMENT                444
537
#define JANUS_SIP_ERROR_ALREADY_REGISTERED        445
538
#define JANUS_SIP_ERROR_INVALID_ADDRESS                446
539
#define JANUS_SIP_ERROR_WRONG_STATE                        447
540
#define JANUS_SIP_ERROR_MISSING_SDP                        448
541
#define JANUS_SIP_ERROR_LIBSOFIA_ERROR                449
542
#define JANUS_SIP_ERROR_IO_ERROR                        450
543
#define JANUS_SIP_ERROR_RECORDING_ERROR                451
544
#define JANUS_SIP_ERROR_TOO_STRICT                        452
545

    
546

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

    
641

    
642
/* Random string helper (for call-ids) */
643
static char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
644
static void janus_sip_random_string(int length, char *buffer) {
645
        if(length > 0 && buffer) {
646
                int l = (int)(sizeof(charset)-1);
647
                int i=0;
648
                for(i=0; i<length; i++) {
649
                        int key = rand() % l;
650
                        buffer[i] = charset[key];
651
                }
652
                buffer[length-1] = '\0';
653
        }
654
}
655

    
656

    
657
/* Sofia SIP logger function: when the Event Handlers mechanism is enabled,
658
 * we use this to intercept SIP messages sent by the stack (received
659
 * messages are more easily recoverable in janus_sip_sofia_callback) */
660
char sofia_log[2048];
661
char call_id[255];
662
gboolean skip = FALSE, started = FALSE, append = FALSE;
663
static void janus_sip_sofia_logger(void *stream, char const *fmt, va_list ap) {
664
        if(!fmt)
665
                return;
666
        char line[255];
667
        g_vsnprintf(line, sizeof(line), fmt, ap);
668
        if(skip) {
669
                /* This is a message we're not interested in: just check when it ends */
670
                if(line[3] == '-') {
671
                        skip = FALSE;
672
                        append = FALSE;
673
                }
674
                return;
675
        }
676
        if(append) {
677
                /* We're copying a message in our buffer: check if this is the end */
678
                if(line[3] == '-') {
679
                        if(!started) {
680
                                /* Ok, start appending from now on */
681
                                started = TRUE;
682
                                sofia_log[0] = '\0';
683
                                call_id[0] = '\0';
684
                        } else {
685
                                /* Message ended, handle it */
686
                                skip = FALSE;
687
                                append = FALSE;
688
                                /* Look for the session this message belongs to */
689
                                janus_sip_session *session = NULL;
690
                                if(strlen(call_id))
691
                                        session = g_hash_table_lookup(callids, call_id);
692
                                if(!session) {
693
                                        /* Couldn't find any SIP session with that Call-ID, check the request */
694
                                        if(strstr(sofia_log, "REGISTER") == sofia_log || strstr(sofia_log, "SIP/2.0 ") == sofia_log) {
695
                                                /* FIXME This is a REGISTER or a response code:
696
                                                 * check the To header and get the identity from there */
697
                                                char *from = strstr(sofia_log, "To: ");
698
                                                if(from) {
699
                                                        from = from+4;
700
                                                        char *start = strstr(from, "<");
701
                                                        if(start) {
702
                                                                start++;
703
                                                                char *end = strstr(from, ">");
704
                                                                if(end) {
705
                                                                        *end = '\0';
706
                                                                        g_snprintf(call_id, sizeof(call_id), "%s", start);
707
                                                                        *end = '>';
708
                                                                        session = g_hash_table_lookup(identities, call_id);
709
                                                                }
710
                                                        }
711
                                                }
712
                                        }
713
                                }
714
                                if(session) {
715
                                        /* Notify event handlers about the content of the whole outgoing SIP message */
716
                                        json_t *info = json_object();
717
                                        json_object_set_new(info, "event", json_string("sip-out"));
718
                                        json_object_set_new(info, "sip", json_string(sofia_log));
719
                                        gateway->notify_event(&janus_sip_plugin, session->handle, info);
720
                                } else {
721
                                        JANUS_LOG(LOG_WARN, "Couldn't find a session associated to this message, dropping it...\n%s", sofia_log);
722
                                }
723
                                /* Done, reset the buffers */
724
                                sofia_log[0] = '\0';
725
                                call_id[0] = '\0';
726
                        }
727
                        return;
728
                }
729
                if(strlen(line) == 1) {
730
                        /* Append a carriage and return */
731
                        g_strlcat(sofia_log, "\r\n", sizeof(sofia_log));
732
                } else {
733
                        /* If this is an OPTIONS, we don't care: drop it */
734
                        char *header = &line[3];
735
                        if(strstr(header, "OPTIONS") == header) {
736
                                skip = TRUE;
737
                                return;
738
                        }
739
                        /* Is this a Call-ID header? Keep note of it */
740
                        if(strstr(header, "Call-ID") == header) {
741
                                g_snprintf(call_id, sizeof(call_id), "%s", header+9);
742
                        }
743
                        /* Append the line to our buffer, skipping the indent */
744
                        g_strlcat(sofia_log, &line[3], sizeof(sofia_log));
745
                }
746
                return;
747
        }
748
        /* Still waiting to decide if this is a message we need */
749
        if(line[0] == 's' && line[1] == 'e' && line[2] == 'n' && line[3] == 'd' && line[4] == ' ') {
750
                /* An outgoing message is going to be logged, prepare for that */
751
                skip = FALSE;
752
                started = FALSE;
753
                append = TRUE;
754
                int length = atoi(&line[5]);
755
                JANUS_LOG(LOG_HUGE, "Intercepting message (%d bytes)\n", length);
756
                if(strstr(line, "-----"))
757
                        started = TRUE;
758
        }
759
}
760

    
761

    
762
/* Plugin implementation */
763
int janus_sip_init(janus_callbacks *callback, const char *config_path) {
764
        if(g_atomic_int_get(&stopping)) {
765
                /* Still stopping from before */
766
                return -1;
767
        }
768
        if(callback == NULL || config_path == NULL) {
769
                /* Invalid arguments */
770
                return -1;
771
        }
772

    
773
        /* Read configuration */
774
        char filename[255];
775
        g_snprintf(filename, 255, "%s/%s.cfg", config_path, JANUS_SIP_PACKAGE);
776
        JANUS_LOG(LOG_VERB, "Configuration file: %s\n", filename);
777
        janus_config *config = janus_config_parse(filename);
778
        if(config != NULL) {
779
                janus_config_print(config);
780

    
781
                janus_config_item *item = janus_config_get_item_drilldown(config, "general", "local_ip");
782
                if(item && item->value) {
783
                        /* Verify that the address is valid */
784
                        struct ifaddrs *ifas = NULL;
785
                        janus_network_address iface;
786
                        janus_network_address_string_buffer ibuf;
787
                        if(getifaddrs(&ifas) || ifas == NULL) {
788
                                JANUS_LOG(LOG_ERR, "Unable to acquire list of network devices/interfaces; some configurations may not work as expected...\n");
789
                        } else {
790
                                if(janus_network_lookup_interface(ifas, item->value, &iface) != 0) {
791
                                        JANUS_LOG(LOG_WARN, "Error setting local IP address to %s, falling back to detecting IP address...\n", item->value);
792
                                } else {
793
                                        if(janus_network_address_to_string_buffer(&iface, &ibuf) != 0 || janus_network_address_string_buffer_is_null(&ibuf)) {
794
                                                JANUS_LOG(LOG_WARN, "Error getting local IP address from %s, falling back to detecting IP address...\n", item->value);
795
                                        } else {
796
                                                local_ip = g_strdup(janus_network_address_string_from_buffer(&ibuf));
797
                                        }
798
                                }
799
                        }
800
                }
801

    
802
                item = janus_config_get_item_drilldown(config, "general", "keepalive_interval");
803
                if(item && item->value)
804
                        keepalive_interval = atoi(item->value);
805
                JANUS_LOG(LOG_VERB, "SIP keep-alive interval set to %d seconds\n", keepalive_interval);
806

    
807
                item = janus_config_get_item_drilldown(config, "general", "register_ttl");
808
                if(item && item->value)
809
                        register_ttl = atoi(item->value);
810
                JANUS_LOG(LOG_VERB, "SIP registration TTL set to %d seconds\n", register_ttl);
811

    
812
                item = janus_config_get_item_drilldown(config, "general", "behind_nat");
813
                if(item && item->value)
814
                        behind_nat = janus_is_true(item->value);
815

    
816
                item = janus_config_get_item_drilldown(config, "general", "user_agent");
817
                if(item && item->value)
818
                        user_agent = g_strdup(item->value);
819
                else
820
                        user_agent = g_strdup("Janus WebRTC Gateway SIP Plugin "JANUS_SIP_VERSION_STRING);
821
                JANUS_LOG(LOG_VERB, "SIP User-Agent set to %s\n", user_agent);
822

    
823
                item = janus_config_get_item_drilldown(config, "general", "events");
824
                if(item != NULL && item->value != NULL)
825
                        notify_events = janus_is_true(item->value);
826
                if(!notify_events && callback->events_is_enabled()) {
827
                        JANUS_LOG(LOG_WARN, "Notification of events to handlers disabled for %s\n", JANUS_SIP_NAME);
828
                }
829

    
830
                janus_config_destroy(config);
831
        }
832
        config = NULL;
833

    
834
        if(local_ip == NULL) {
835
                local_ip = janus_network_detect_local_ip_as_string(janus_network_query_options_any_ip);
836
                if(local_ip == NULL) {
837
                        JANUS_LOG(LOG_WARN, "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");
838
                        local_ip = g_strdup("127.0.0.1");
839
                }
840
        }
841
        JANUS_LOG(LOG_VERB, "Local IP set to %s\n", local_ip);
842

    
843
#ifdef HAVE_SRTP_2
844
        /* Init randomizer (for randum numbers in SRTP) */
845
        RAND_poll();
846
#endif
847

    
848
        /* Setup sofia */
849
        su_init();
850
        if(callback->events_is_enabled()) {
851
                /* Enable the transport logging, as we want to have access to the SIP messages */
852
                setenv("TPORT_LOG", "1", 1);
853
                su_log_redirect(NULL, janus_sip_sofia_logger, NULL);
854
        }
855

    
856
        sessions = g_hash_table_new(NULL, NULL);
857
        callids = g_hash_table_new(g_str_hash, g_str_equal);
858
        identities = g_hash_table_new(g_str_hash, g_str_equal);
859
        janus_mutex_init(&sessions_mutex);
860
        messages = g_async_queue_new_full((GDestroyNotify) janus_sip_message_free);
861
        /* This is the callback we'll need to invoke to contact the gateway */
862
        gateway = callback;
863

    
864
        g_atomic_int_set(&initialized, 1);
865

    
866
        GError *error = NULL;
867
        /* Start the sessions watchdog */
868
        watchdog = g_thread_try_new("sip watchdog", &janus_sip_watchdog, NULL, &error);
869
        if(error != NULL) {
870
                g_atomic_int_set(&initialized, 0);
871
                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the SIP watchdog thread...\n", error->code, error->message ? error->message : "??");
872
                return -1;
873
        }
874
        /* Launch the thread that will handle incoming messages */
875
        handler_thread = g_thread_try_new("sip handler", janus_sip_handler, NULL, &error);
876
        if(error != NULL) {
877
                g_atomic_int_set(&initialized, 0);
878
                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the SIP handler thread...\n", error->code, error->message ? error->message : "??");
879
                return -1;
880
        }
881
        JANUS_LOG(LOG_INFO, "%s initialized!\n", JANUS_SIP_NAME);
882
        return 0;
883
}
884

    
885
void janus_sip_destroy(void) {
886
        if(!g_atomic_int_get(&initialized))
887
                return;
888
        g_atomic_int_set(&stopping, 1);
889

    
890
        g_async_queue_push(messages, &exit_message);
891
        if(handler_thread != NULL) {
892
                g_thread_join(handler_thread);
893
                handler_thread = NULL;
894
        }
895
        if(watchdog != NULL) {
896
                g_thread_join(watchdog);
897
                watchdog = NULL;
898
        }
899
        /* FIXME We should destroy the sessions cleanly */
900
        janus_mutex_lock(&sessions_mutex);
901
        g_hash_table_destroy(sessions);
902
        g_hash_table_destroy(callids);
903
        g_hash_table_destroy(identities);
904
        sessions = NULL;
905
        callids = NULL;
906
        identities = NULL;
907
        janus_mutex_unlock(&sessions_mutex);
908
        g_async_queue_unref(messages);
909
        messages = NULL;
910
        g_atomic_int_set(&initialized, 0);
911
        g_atomic_int_set(&stopping, 0);
912

    
913
        /* Deinitialize sofia */
914
        su_deinit();
915

    
916
        g_free(local_ip);
917

    
918
        JANUS_LOG(LOG_INFO, "%s destroyed!\n", JANUS_SIP_NAME);
919
}
920

    
921
int janus_sip_get_api_compatibility(void) {
922
        /* Important! This is what your plugin MUST always return: don't lie here or bad things will happen */
923
        return JANUS_PLUGIN_API_VERSION;
924
}
925

    
926
int janus_sip_get_version(void) {
927
        return JANUS_SIP_VERSION;
928
}
929

    
930
const char *janus_sip_get_version_string(void) {
931
        return JANUS_SIP_VERSION_STRING;
932
}
933

    
934
const char *janus_sip_get_description(void) {
935
        return JANUS_SIP_DESCRIPTION;
936
}
937

    
938
const char *janus_sip_get_name(void) {
939
        return JANUS_SIP_NAME;
940
}
941

    
942
const char *janus_sip_get_author(void) {
943
        return JANUS_SIP_AUTHOR;
944
}
945

    
946
const char *janus_sip_get_package(void) {
947
        return JANUS_SIP_PACKAGE;
948
}
949

    
950
void janus_sip_create_session(janus_plugin_session *handle, int *error) {
951
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
952
                *error = -1;
953
                return;
954
        }
955
        janus_sip_session *session = g_malloc0(sizeof(janus_sip_session));
956
        session->handle = handle;
957
        session->account.identity = NULL;
958
        session->account.sips = TRUE;
959
        session->account.username = NULL;
960
        session->account.display_name = NULL;
961
        session->account.user_agent = NULL;
962
        session->account.authuser = NULL;
963
        session->account.secret = NULL;
964
        session->account.secret_type = janus_sip_secret_type_unknown;
965
        session->account.sip_port = 0;
966
        session->account.proxy = NULL;
967
        session->account.outbound_proxy = NULL;
968
        session->account.registration_status = janus_sip_registration_status_unregistered;
969
        session->status = janus_sip_call_status_idle;
970
        session->stack = NULL;
971
        session->transaction = NULL;
972
        session->callee = NULL;
973
        session->callid = NULL;
974
        session->sdp = NULL;
975
        session->media.remote_ip = NULL;
976
        session->media.ready = FALSE;
977
        session->media.autoack = TRUE;
978
        session->media.require_srtp = FALSE;
979
        session->media.has_srtp_local = FALSE;
980
        session->media.has_srtp_remote = FALSE;
981
        session->media.on_hold = FALSE;
982
        session->media.has_audio = FALSE;
983
        session->media.audio_rtp_fd = -1;
984
        session->media.audio_rtcp_fd= -1;
985
        session->media.local_audio_rtp_port = 0;
986
        session->media.remote_audio_rtp_port = 0;
987
        session->media.local_audio_rtcp_port = 0;
988
        session->media.remote_audio_rtcp_port = 0;
989
        session->media.audio_ssrc = 0;
990
        session->media.audio_ssrc_peer = 0;
991
        session->media.audio_pt = -1;
992
        session->media.audio_pt_name = NULL;
993
        session->media.audio_srtp_suite_in = 0;
994
        session->media.audio_srtp_suite_out = 0;
995
        session->media.audio_send = TRUE;
996
        session->media.pre_hold_audio_dir = JANUS_SDP_DEFAULT;
997
        session->media.has_video = FALSE;
998
        session->media.video_rtp_fd = -1;
999
        session->media.video_rtcp_fd= -1;
1000
        session->media.local_video_rtp_port = 0;
1001
        session->media.remote_video_rtp_port = 0;
1002
        session->media.local_video_rtcp_port = 0;
1003
        session->media.remote_video_rtcp_port = 0;
1004
        session->media.video_ssrc = 0;
1005
        session->media.video_ssrc_peer = 0;
1006
        session->media.video_pt = -1;
1007
        session->media.video_pt_name = NULL;
1008
        session->media.video_srtp_suite_in = 0;
1009
        session->media.video_srtp_suite_out = 0;
1010
        session->media.video_send = TRUE;
1011
        session->media.pre_hold_video_dir = JANUS_SDP_DEFAULT;
1012
        /* Initialize the RTP context */
1013
        janus_rtp_switching_context_reset(&session->media.context);
1014
        session->media.pipefd[0] = -1;
1015
        session->media.pipefd[1] = -1;
1016
        session->media.updated = FALSE;
1017
        janus_mutex_init(&session->rec_mutex);
1018
        session->destroyed = 0;
1019
        g_atomic_int_set(&session->hangingup, 0);
1020
        janus_mutex_init(&session->mutex);
1021
        handle->plugin_handle = session;
1022

    
1023
        janus_mutex_lock(&sessions_mutex);
1024
        g_hash_table_insert(sessions, handle, session);
1025
        janus_mutex_unlock(&sessions_mutex);
1026

    
1027
        return;
1028
}
1029

    
1030
void janus_sip_destroy_session(janus_plugin_session *handle, int *error) {
1031
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
1032
                *error = -1;
1033
                return;
1034
        }
1035
        janus_sip_session *session = (janus_sip_session *)handle->plugin_handle;
1036
        if(!session) {
1037
                JANUS_LOG(LOG_ERR, "No SIP session associated with this handle...\n");
1038
                *error = -2;
1039
                return;
1040
        }
1041
        janus_mutex_lock(&sessions_mutex);
1042
        if(!session->destroyed) {
1043
                g_hash_table_remove(sessions, handle);
1044
                janus_sip_hangup_media(handle);
1045
                session->destroyed = janus_get_monotonic_time();
1046
                JANUS_LOG(LOG_VERB, "Destroying SIP session (%s)...\n", session->account.username ? session->account.username : "unregistered user");
1047
                if(session->stack != NULL) {
1048
                        /* Shutdown the NUA: this will remove the session later on */
1049
                        nua_shutdown(session->stack->s_nua);
1050
                } else {
1051
                        /* No stack, maybe never registered: cleaning up and removing the session is done in a lazy way */
1052
                        old_sessions = g_list_append(old_sessions, session);
1053
                }
1054
        }
1055
        janus_mutex_unlock(&sessions_mutex);
1056
        return;
1057
}
1058

    
1059
json_t *janus_sip_query_session(janus_plugin_session *handle) {
1060
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
1061
                return NULL;
1062
        }
1063
        janus_sip_session *session = (janus_sip_session *)handle->plugin_handle;
1064
        if(!session) {
1065
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1066
                return NULL;
1067
        }
1068
        /* Provide some generic info, e.g., if we're in a call and with whom */
1069
        json_t *info = json_object();
1070
        json_object_set_new(info, "username", session->account.username ? json_string(session->account.username) : NULL);
1071
        json_object_set_new(info, "display_name", session->account.display_name ? json_string(session->account.display_name) : NULL);
1072
        json_object_set_new(info, "user_agent", session->account.user_agent ? json_string(session->account.user_agent) : NULL);
1073
        json_object_set_new(info, "identity", session->account.identity ? json_string(session->account.identity) : NULL);
1074
        json_object_set_new(info, "registration_status", json_string(janus_sip_registration_status_string(session->account.registration_status)));
1075
        json_object_set_new(info, "call_status", json_string(janus_sip_call_status_string(session->status)));
1076
        if(session->callee) {
1077
                json_object_set_new(info, "callee", json_string(session->callee ? session->callee : "??"));
1078
                json_object_set_new(info, "auto-ack", json_string(session->media.autoack ? "yes" : "no"));
1079
                json_object_set_new(info, "srtp-required", json_string(session->media.require_srtp ? "yes" : "no"));
1080
                json_object_set_new(info, "sdes-local", json_string(session->media.has_srtp_local ? "yes" : "no"));
1081
                json_object_set_new(info, "sdes-remote", json_string(session->media.has_srtp_remote ? "yes" : "no"));
1082
        }
1083
        if(session->arc || session->vrc || session->arc_peer || session->vrc_peer) {
1084
                json_t *recording = json_object();
1085
                if(session->arc && session->arc->filename)
1086
                        json_object_set_new(recording, "audio", json_string(session->arc->filename));
1087
                if(session->vrc && session->vrc->filename)
1088
                        json_object_set_new(recording, "video", json_string(session->vrc->filename));
1089
                if(session->arc_peer && session->arc_peer->filename)
1090
                        json_object_set_new(recording, "audio-peer", json_string(session->arc_peer->filename));
1091
                if(session->vrc_peer && session->vrc_peer->filename)
1092
                        json_object_set_new(recording, "video-peer", json_string(session->vrc_peer->filename));
1093
                json_object_set_new(info, "recording", recording);
1094
        }
1095
        json_object_set_new(info, "destroyed", json_integer(session->destroyed));
1096
        return info;
1097
}
1098

    
1099
struct janus_plugin_result *janus_sip_handle_message(janus_plugin_session *handle, char *transaction, json_t *message, json_t *jsep) {
1100
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
1101
                return janus_plugin_result_new(JANUS_PLUGIN_ERROR, g_atomic_int_get(&stopping) ? "Shutting down" : "Plugin not initialized", NULL);
1102
        janus_sip_message *msg = g_malloc0(sizeof(janus_sip_message));
1103
        msg->handle = handle;
1104
        msg->transaction = transaction;
1105
        msg->message = message;
1106
        msg->jsep = jsep;
1107
        g_async_queue_push(messages, msg);
1108

    
1109
        /* All the requests to this plugin are handled asynchronously */
1110
        return janus_plugin_result_new(JANUS_PLUGIN_OK_WAIT, NULL, NULL);
1111
}
1112

    
1113
void janus_sip_setup_media(janus_plugin_session *handle) {
1114
        JANUS_LOG(LOG_INFO, "WebRTC media is now available\n");
1115
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
1116
                return;
1117
        janus_sip_session *session = (janus_sip_session *)handle->plugin_handle;
1118
        if(!session) {
1119
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1120
                return;
1121
        }
1122
        if(session->destroyed)
1123
                return;
1124
        g_atomic_int_set(&session->hangingup, 0);
1125
        /* TODO Only relay RTP/RTCP when we get this event */
1126
}
1127

    
1128
void janus_sip_incoming_rtp(janus_plugin_session *handle, int video, char *buf, int len) {
1129
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
1130
                return;
1131
        if(gateway) {
1132
                /* Honour the audio/video active flags */
1133
                janus_sip_session *session = (janus_sip_session *)handle->plugin_handle;
1134
                if(!session || session->destroyed) {
1135
                        JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1136
                        return;
1137
                }
1138
                if(session->status != janus_sip_call_status_incall)
1139
                        return;
1140
                /* Forward to our SIP peer */
1141
                if(video) {
1142
                        if(!session->media.video_send) {
1143
                                /* Dropping video packet, peer doesn't want to receive it */
1144
                                return;
1145
                        }
1146
                        if(session->media.video_ssrc == 0) {
1147
                                rtp_header *header = (rtp_header *)buf;
1148
                                session->media.video_ssrc = ntohl(header->ssrc);
1149
                                JANUS_LOG(LOG_VERB, "Got SIP video SSRC: %"SCNu32"\n", session->media.video_ssrc);
1150
                        }
1151
                        if(session->media.has_video && session->media.video_rtp_fd != -1) {
1152
                                /* Save the frame if we're recording */
1153
                                janus_recorder_save_frame(session->vrc, buf, len);
1154
                                /* Is SRTP involved? */
1155
                                if(session->media.has_srtp_local) {
1156
                                        char sbuf[2048];
1157
                                        memcpy(&sbuf, buf, len);
1158
                                        int protected = len;
1159
                                        int res = srtp_protect(session->media.video_srtp_out, &sbuf, &protected);
1160
                                        if(res != srtp_err_status_ok) {
1161
                                                rtp_header *header = (rtp_header *)&sbuf;
1162
                                                guint32 timestamp = ntohl(header->timestamp);
1163
                                                guint16 seq = ntohs(header->seq_number);
1164
                                                JANUS_LOG(LOG_ERR, "[SIP-%s] Video SRTP protect error... %s (len=%d-->%d, ts=%"SCNu32", seq=%"SCNu16")...\n",
1165
                                                        session->account.username, janus_srtp_error_str(res), len, protected, timestamp, seq);
1166
                                        } else {
1167
                                                /* Forward the frame to the peer */
1168
                                                send(session->media.video_rtp_fd, sbuf, protected, 0);
1169
                                        }
1170
                                } else {
1171
                                        /* Forward the frame to the peer */
1172
                                        send(session->media.video_rtp_fd, buf, len, 0);
1173
                                }
1174
                        }
1175
                } else {
1176
                        if(!session->media.audio_send) {
1177
                                /* Dropping audio packet, peer doesn't want to receive it */
1178
                                return;
1179
                        }
1180
                        if(session->media.audio_ssrc == 0) {
1181
                                rtp_header *header = (rtp_header *)buf;
1182
                                session->media.audio_ssrc = ntohl(header->ssrc);
1183
                                JANUS_LOG(LOG_VERB, "Got SIP audio SSRC: %"SCNu32"\n", session->media.audio_ssrc);
1184
                        }
1185
                        if(session->media.has_audio && session->media.audio_rtp_fd != -1) {
1186
                                /* Save the frame if we're recording */
1187
                                janus_recorder_save_frame(session->arc, buf, len);
1188
                                /* Is SRTP involved? */
1189
                                if(session->media.has_srtp_local) {
1190
                                        char sbuf[2048];
1191
                                        memcpy(&sbuf, buf, len);
1192
                                        int protected = len;
1193
                                        int res = srtp_protect(session->media.audio_srtp_out, &sbuf, &protected);
1194
                                        if(res != srtp_err_status_ok) {
1195
                                                rtp_header *header = (rtp_header *)&sbuf;
1196
                                                guint32 timestamp = ntohl(header->timestamp);
1197
                                                guint16 seq = ntohs(header->seq_number);
1198
                                                JANUS_LOG(LOG_ERR, "[SIP-%s] Audio SRTP protect error... %s (len=%d-->%d, ts=%"SCNu32", seq=%"SCNu16")...\n",
1199
                                                        session->account.username, janus_srtp_error_str(res), len, protected, timestamp, seq);
1200
                                        } else {
1201
                                                /* Forward the frame to the peer */
1202
                                                send(session->media.audio_rtp_fd, sbuf, protected, 0);
1203
                                        }
1204
                                } else {
1205
                                        /* Forward the frame to the peer */
1206
                                        send(session->media.audio_rtp_fd, buf, len, 0);
1207
                                }
1208
                        }
1209
                }
1210
        }
1211
}
1212

    
1213
void janus_sip_incoming_rtcp(janus_plugin_session *handle, int video, char *buf, int len) {
1214
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
1215
                return;
1216
        if(gateway) {
1217
                janus_sip_session *session = (janus_sip_session *)handle->plugin_handle;
1218
                if(!session || session->destroyed) {
1219
                        JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1220
                        return;
1221
                }
1222
                if(session->status != janus_sip_call_status_incall)
1223
                        return;
1224
                /* Forward to our SIP peer */
1225
                if(video) {
1226
                        if(session->media.has_video && session->media.video_rtcp_fd != -1) {
1227
                                /* Fix SSRCs as the gateway does */
1228
                                JANUS_LOG(LOG_HUGE, "[SIP] Fixing SSRCs (local %u, peer %u)\n",
1229
                                        session->media.video_ssrc, session->media.video_ssrc_peer);
1230
                                janus_rtcp_fix_ssrc(NULL, (char *)buf, len, 1, session->media.video_ssrc, session->media.video_ssrc_peer);
1231
                                /* Is SRTP involved? */
1232
                                if(session->media.has_srtp_local) {
1233
                                        char sbuf[2048];
1234
                                        memcpy(&sbuf, buf, len);
1235
                                        int protected = len;
1236
                                        int res = srtp_protect_rtcp(session->media.video_srtp_out, &sbuf, &protected);
1237
                                        if(res != srtp_err_status_ok) {
1238
                                                JANUS_LOG(LOG_ERR, "[SIP-%s] Video SRTCP protect error... %s (len=%d-->%d)...\n",
1239
                                                        session->account.username, janus_srtp_error_str(res), len, protected);
1240
                                        } else {
1241
                                                /* Forward the message to the peer */
1242
                                                send(session->media.video_rtcp_fd, sbuf, protected, 0);
1243
                                        }
1244
                                } else {
1245
                                        /* Forward the message to the peer */
1246
                                        send(session->media.video_rtcp_fd, buf, len, 0);
1247
                                }
1248
                        }
1249
                } else {
1250
                        if(session->media.has_audio && session->media.audio_rtcp_fd != -1) {
1251
                                /* Fix SSRCs as the gateway does */
1252
                                JANUS_LOG(LOG_HUGE, "[SIP] Fixing SSRCs (local %u, peer %u)\n",
1253
                                        session->media.audio_ssrc, session->media.audio_ssrc_peer);
1254
                                janus_rtcp_fix_ssrc(NULL, (char *)buf, len, 1, session->media.audio_ssrc, session->media.audio_ssrc_peer);
1255
                                /* Is SRTP involved? */
1256
                                if(session->media.has_srtp_local) {
1257
                                        char sbuf[2048];
1258
                                        memcpy(&sbuf, buf, len);
1259
                                        int protected = len;
1260
                                        int res = srtp_protect_rtcp(session->media.audio_srtp_out, &sbuf, &protected);
1261
                                        if(res != srtp_err_status_ok) {
1262
                                                JANUS_LOG(LOG_ERR, "[SIP-%s] Audio SRTCP protect error... %s (len=%d-->%d)...\n",
1263
                                                        session->account.username, janus_srtp_error_str(res), len, protected);
1264
                                        } else {
1265
                                                /* Forward the message to the peer */
1266
                                                send(session->media.audio_rtcp_fd, sbuf, protected, 0);
1267
                                        }
1268
                                } else {
1269
                                        /* Forward the message to the peer */
1270
                                        send(session->media.audio_rtcp_fd, buf, len, 0);
1271
                                }
1272
                        }
1273
                }
1274
        }
1275
}
1276

    
1277
void janus_sip_hangup_media(janus_plugin_session *handle) {
1278
        JANUS_LOG(LOG_INFO, "No WebRTC media anymore\n");
1279
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
1280
                return;
1281
        janus_sip_session *session = (janus_sip_session *)handle->plugin_handle;
1282
        if(!session) {
1283
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1284
                return;
1285
        }
1286
        if(session->destroyed)
1287
                return;
1288
        if(g_atomic_int_add(&session->hangingup, 1))
1289
                return;
1290
        if(!(session->status == janus_sip_call_status_inviting ||
1291
                 session->status == janus_sip_call_status_invited ||
1292
                 session->status == janus_sip_call_status_incall))
1293
                return;
1294
        /* Get rid of the recorders, if available */
1295
        janus_mutex_lock(&session->rec_mutex);
1296
        if(session->arc) {
1297
                janus_recorder_close(session->arc);
1298
                JANUS_LOG(LOG_INFO, "Closed user's audio recording %s\n", session->arc->filename ? session->arc->filename : "??");
1299
                janus_recorder_free(session->arc);
1300
        }
1301
        session->arc = NULL;
1302
        if(session->arc_peer) {
1303
                janus_recorder_close(session->arc_peer);
1304
                JANUS_LOG(LOG_INFO, "Closed peer's audio recording %s\n", session->arc_peer->filename ? session->arc_peer->filename : "??");
1305
                janus_recorder_free(session->arc_peer);
1306
        }
1307
        session->arc_peer = NULL;
1308
        if(session->vrc) {
1309
                janus_recorder_close(session->vrc);
1310
                JANUS_LOG(LOG_INFO, "Closed user's video recording %s\n", session->vrc->filename ? session->vrc->filename : "??");
1311
                janus_recorder_free(session->vrc);
1312
        }
1313
        session->vrc = NULL;
1314
        if(session->vrc_peer) {
1315
                janus_recorder_close(session->vrc_peer);
1316
                JANUS_LOG(LOG_INFO, "Closed peer's video recording %s\n", session->vrc_peer->filename ? session->vrc_peer->filename : "??");
1317
                janus_recorder_free(session->vrc_peer);
1318
        }
1319
        session->vrc_peer = NULL;
1320
        janus_mutex_unlock(&session->rec_mutex);
1321
        /* FIXME Simulate a "hangup" coming from the browser */
1322
        janus_sip_message *msg = g_malloc0(sizeof(janus_sip_message));
1323
        msg->handle = handle;
1324
        msg->message = json_pack("{ss}", "request", "hangup");
1325
        msg->transaction = NULL;
1326
        msg->jsep = NULL;
1327
        g_async_queue_push(messages, msg);
1328
}
1329

    
1330
/* Thread to handle incoming messages */
1331
static void *janus_sip_handler(void *data) {
1332
        JANUS_LOG(LOG_VERB, "Joining SIP handler thread\n");
1333
        janus_sip_message *msg = NULL;
1334
        int error_code = 0;
1335
        char error_cause[512];
1336
        json_t *root = NULL;
1337
        while(g_atomic_int_get(&initialized) && !g_atomic_int_get(&stopping)) {
1338
                msg = g_async_queue_pop(messages);
1339
                if(msg == NULL)
1340
                        continue;
1341
                if(msg == &exit_message)
1342
                        break;
1343
                if(msg->handle == NULL) {
1344
                        janus_sip_message_free(msg);
1345
                        continue;
1346
                }
1347
                janus_sip_session *session = NULL;
1348
                janus_mutex_lock(&sessions_mutex);
1349
                if(g_hash_table_lookup(sessions, msg->handle) != NULL ) {
1350
                        session = (janus_sip_session *)msg->handle->plugin_handle;
1351
                }
1352
                janus_mutex_unlock(&sessions_mutex);
1353
                if(!session) {
1354
                        JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1355
                        janus_sip_message_free(msg);
1356
                        continue;
1357
                }
1358
                if(session->destroyed) {
1359
                        janus_sip_message_free(msg);
1360
                        continue;
1361
                }
1362
                /* Handle request */
1363
                error_code = 0;
1364
                root = msg->message;
1365
                if(msg->message == NULL) {
1366
                        JANUS_LOG(LOG_ERR, "No message??\n");
1367
                        error_code = JANUS_SIP_ERROR_NO_MESSAGE;
1368
                        g_snprintf(error_cause, 512, "%s", "No message??");
1369
                        goto error;
1370
                }
1371
                if(!json_is_object(root)) {
1372
                        JANUS_LOG(LOG_ERR, "JSON error: not an object\n");
1373
                        error_code = JANUS_SIP_ERROR_INVALID_JSON;
1374
                        g_snprintf(error_cause, 512, "JSON error: not an object");
1375
                        goto error;
1376
                }
1377
                JANUS_VALIDATE_JSON_OBJECT(root, request_parameters,
1378
                        error_code, error_cause, TRUE,
1379
                        JANUS_SIP_ERROR_MISSING_ELEMENT, JANUS_SIP_ERROR_INVALID_ELEMENT);
1380
                if(error_code != 0)
1381
                        goto error;
1382
                json_t *request = json_object_get(root, "request");
1383
                const char *request_text = json_string_value(request);
1384
                json_t *result = NULL;
1385

    
1386
                if(!strcasecmp(request_text, "register")) {
1387
                        /* Send a REGISTER */
1388
                        JANUS_VALIDATE_JSON_OBJECT(root, register_parameters,
1389
                                error_code, error_cause, TRUE,
1390
                                JANUS_SIP_ERROR_MISSING_ELEMENT, JANUS_SIP_ERROR_INVALID_ELEMENT);
1391
                        if(error_code != 0)
1392
                                goto error;
1393
                        gboolean refresh = json_is_true(json_object_get(root, "refresh"));
1394
                        if(session->account.registration_status > janus_sip_registration_status_unregistered && !refresh) {
1395
                                JANUS_LOG(LOG_ERR, "Already registered (%s)\n", session->account.username);
1396
                                error_code = JANUS_SIP_ERROR_ALREADY_REGISTERED;
1397
                                g_snprintf(error_cause, 512, "Already registered (%s)", session->account.username);
1398
                                goto error;
1399
                        }
1400
                        /* Parse the request */
1401
                        gboolean guest = FALSE;
1402
                        json_t *type = json_object_get(root, "type");
1403
                        if(type != NULL) {
1404
                                const char *type_text = json_string_value(type);
1405
                                if(!strcmp(type_text, "guest")) {
1406
                                        JANUS_LOG(LOG_INFO, "Registering as a guest\n");
1407
                                        guest = TRUE;
1408
                                } else {
1409
                                        JANUS_LOG(LOG_WARN, "Unknown type '%s', ignoring...\n", type_text);
1410
                                }
1411
                        }
1412

    
1413
                        gboolean send_register = TRUE;
1414
                        json_t *do_register = json_object_get(root, "send_register");
1415
                        if(do_register != NULL) {
1416
                                if(guest) {
1417
                                        JANUS_LOG(LOG_ERR, "Conflicting elements: send_register cannot be true if guest is true\n");
1418
                                        error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
1419
                                        g_snprintf(error_cause, 512, "Conflicting elements: send_register cannot be true if guest is true");
1420
                                        goto error;
1421
                                }
1422
                                send_register = json_is_true(do_register);
1423
                        }
1424

    
1425
                        gboolean sips = TRUE;
1426
                        json_t *do_sips = json_object_get(root, "sips");
1427
                        if(do_sips != NULL) {
1428
                                sips = json_is_true(do_sips);
1429
                        }
1430

    
1431
                        /* Parse addresses */
1432
                        json_t *proxy = json_object_get(root, "proxy");
1433
                        const char *proxy_text = NULL;
1434
                        if (proxy && !json_is_null(proxy)) {
1435
                                /* Has to be validated separately because it could be null */
1436
                                JANUS_VALIDATE_JSON_OBJECT(root, proxy_parameters,
1437
                                        error_code, error_cause, TRUE,
1438
                                        JANUS_SIP_ERROR_MISSING_ELEMENT, JANUS_SIP_ERROR_INVALID_ELEMENT);
1439
                                if(error_code != 0)
1440
                                        goto error;
1441
                                proxy_text = json_string_value(proxy);
1442
                                janus_sip_uri_t proxy_uri;
1443
                                if (janus_sip_parse_proxy_uri(&proxy_uri, proxy_text) < 0) {
1444
                                        JANUS_LOG(LOG_ERR, "Invalid proxy address %s\n", proxy_text);
1445
                                        error_code = JANUS_SIP_ERROR_INVALID_ADDRESS;
1446
                                        g_snprintf(error_cause, 512, "Invalid proxy address %s\n", proxy_text);
1447
                                        goto error;
1448
                                }
1449
                        }
1450
                        json_t *outbound_proxy = json_object_get(root, "outbound_proxy");
1451
                        const char *obproxy_text = NULL;
1452
                        if (outbound_proxy && !json_is_null(outbound_proxy)) {
1453
                                /* Has to be validated separately because it could be null */
1454
                                JANUS_VALIDATE_JSON_OBJECT(root, proxy_parameters,
1455
                                        error_code, error_cause, TRUE,
1456
                                        JANUS_SIP_ERROR_MISSING_ELEMENT, JANUS_SIP_ERROR_INVALID_ELEMENT);
1457
                                if(error_code != 0)
1458
                                        goto error;
1459
                                obproxy_text = json_string_value(outbound_proxy);
1460
                                janus_sip_uri_t outbound_proxy_uri;
1461
                                if (janus_sip_parse_proxy_uri(&outbound_proxy_uri, obproxy_text) < 0) {
1462
                                        JANUS_LOG(LOG_ERR, "Invalid outbound_proxy address %s\n", obproxy_text);
1463
                                        error_code = JANUS_SIP_ERROR_INVALID_ADDRESS;
1464
                                        g_snprintf(error_cause, 512, "Invalid outbound_proxy address %s\n", obproxy_text);
1465
                                        goto error;
1466
                                }
1467
                        }
1468

    
1469
                        /* Parse register TTL */
1470
                        int ttl = register_ttl;
1471
                        json_t *reg_ttl = json_object_get(root, "register_ttl");
1472
                        if (reg_ttl && json_is_integer(reg_ttl))
1473
                                ttl = json_integer_value(reg_ttl);
1474
                        if (ttl <= 0)
1475
                                ttl = JANUS_DEFAULT_REGISTER_TTL;
1476

    
1477
                        /* Parse display name */
1478
                        const char* display_name_text = NULL;
1479
                        json_t *display_name = json_object_get(root, "display_name");
1480
                        if (display_name && json_is_string(display_name))
1481
                                display_name_text = json_string_value(display_name);
1482

    
1483
                        /* Parse user agent */
1484
                        const char* user_agent_text = NULL;
1485
                        json_t *user_agent = json_object_get(root, "user_agent");
1486
                        if (user_agent && json_is_string(user_agent))
1487
                                user_agent_text = json_string_value(user_agent);
1488

    
1489
                        /* Now the user part (always needed, even for the guest case) */
1490
                        json_t *username = json_object_get(root, "username");
1491
                        if(!username) {
1492
                                /* The username is mandatory even when registering as guests */
1493
                                JANUS_LOG(LOG_ERR, "Missing element (username)\n");
1494
                                error_code = JANUS_SIP_ERROR_MISSING_ELEMENT;
1495
                                g_snprintf(error_cause, 512, "Missing element (username)");
1496
                                goto error;
1497
                        }
1498
                        const char *username_text = NULL;
1499
                        const char *secret_text = NULL;
1500
                        const char *authuser_text = NULL;
1501
                        janus_sip_secret_type secret_type = janus_sip_secret_type_plaintext;
1502
                        janus_sip_uri_t username_uri;
1503
                        char user_id[256];
1504
                        /* Parse address */
1505
                        username_text = json_string_value(username);
1506
                        if(janus_sip_parse_uri(&username_uri, username_text) < 0) {
1507
                                JANUS_LOG(LOG_ERR, "Invalid user address %s\n", username_text);
1508
                                error_code = JANUS_SIP_ERROR_INVALID_ADDRESS;
1509
                                g_snprintf(error_cause, 512, "Invalid user address %s\n", username_text);
1510
                                goto error;
1511
                        }
1512
                        g_strlcpy(user_id, username_uri.url->url_user, sizeof(user_id));
1513
                        if(guest) {
1514
                                /* Not needed, we can stop here: just say we're registered */
1515
                                JANUS_LOG(LOG_INFO, "Guest will have username %s\n", user_id);
1516
                                send_register = FALSE;
1517
                        } else {
1518
                                json_t *secret = json_object_get(root, "secret");
1519
                                json_t *ha1_secret = json_object_get(root, "ha1_secret");
1520
                                json_t *authuser = json_object_get(root, "authuser");
1521
                                if(!secret && !ha1_secret) {
1522
                                        JANUS_LOG(LOG_ERR, "Missing element (secret or ha1_secret)\n");
1523
                                        error_code = JANUS_SIP_ERROR_MISSING_ELEMENT;
1524
                                        g_snprintf(error_cause, 512, "Missing element (secret or ha1_secret)");
1525
                                        goto error;
1526
                                }
1527
                                if(secret && ha1_secret) {
1528
                                        JANUS_LOG(LOG_ERR, "Conflicting elements specified (secret and ha1_secret)\n");
1529
                                        error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
1530
                                        g_snprintf(error_cause, 512, "Conflicting elements specified (secret and ha1_secret)");
1531
                                        goto error;
1532
                                }
1533
                                if(secret) {
1534
                                        secret_text = json_string_value(secret);
1535
                                        secret_type = janus_sip_secret_type_plaintext;
1536
                                } else {
1537
                                        secret_text = json_string_value(ha1_secret);
1538
                                        secret_type = janus_sip_secret_type_hashed;
1539
                                }
1540
                                if (authuser) {
1541
                                        authuser_text = json_string_value(authuser);
1542
                                }
1543
                                /* Got the values, try registering now */
1544
                                JANUS_LOG(LOG_VERB, "Registering user %s (auth=%s, secret %s) @ %s through %s (outbound proxy: %s)\n",
1545
                                        username_text, secret_text, username_uri.url->url_host,
1546
                                        authuser_text != NULL ? authuser_text : username_text,
1547
                                        proxy_text != NULL ? proxy_text : "(null)",
1548
                                        obproxy_text != NULL ? obproxy_text : "none");
1549
                        }
1550
                        /* If this is a refresh, get rid of the old values */
1551
                        if(refresh) {
1552
                                /* Cleanup old values */
1553
                                if(session->account.identity != NULL) {
1554
                                        g_hash_table_remove(identities, session->account.identity);
1555
                                        g_free(session->account.identity);
1556
                                }
1557
                                session->account.identity = NULL;
1558
                                session->account.sips = TRUE;
1559
                                if(session->account.username != NULL)
1560
                                        g_free(session->account.username);
1561
                                session->account.username = NULL;
1562
                                if(session->account.display_name != NULL)
1563
                                        g_free(session->account.display_name);
1564
                                session->account.display_name = NULL;
1565
                                if(session->account.authuser != NULL)
1566
                                        g_free(session->account.authuser);
1567
                                session->account.authuser = NULL;
1568
                                if(session->account.secret != NULL)
1569
                                        g_free(session->account.secret);
1570
                                session->account.secret = NULL;
1571
                                session->account.secret_type = janus_sip_secret_type_unknown;
1572
                                if(session->account.proxy != NULL)
1573
                                        g_free(session->account.proxy);
1574
                                session->account.proxy = NULL;
1575
                                if(session->account.outbound_proxy != NULL)
1576
                                        g_free(session->account.outbound_proxy);
1577
                                session->account.outbound_proxy = NULL;
1578
                                if(session->account.user_agent != NULL)
1579
                                        g_free(session->account.user_agent);
1580
                                session->account.user_agent = NULL;
1581
                                session->account.registration_status = janus_sip_registration_status_unregistered;
1582
                        }
1583
                        session->account.identity = g_strdup(username_text);
1584
                        g_hash_table_insert(identities, session->account.identity, session);
1585
                        session->account.sips = sips;
1586
                        session->account.username = g_strdup(user_id);
1587
                        session->account.authuser = g_strdup(authuser_text ? authuser_text : user_id);
1588
                        session->account.secret = secret_text ? g_strdup(secret_text) : NULL;
1589
                        session->account.secret_type = secret_type;
1590
                        if(display_name_text) {
1591
                                session->account.display_name = g_strdup(display_name_text);
1592
                        }
1593
                        if(user_agent_text) {
1594
                                session->account.user_agent = g_strdup(user_agent_text);
1595
                        }
1596
                        if(proxy_text) {
1597
                                session->account.proxy = g_strdup(proxy_text);
1598
                        }
1599
                        if(obproxy_text) {
1600
                                session->account.outbound_proxy = g_strdup(obproxy_text);
1601
                        }
1602

    
1603
                        session->account.registration_status = janus_sip_registration_status_registering;
1604
                        if(!refresh && session->stack == NULL) {
1605
                                /* Start the thread first */
1606
                                GError *error = NULL;
1607
                                char tname[16];
1608
                                g_snprintf(tname, sizeof(tname), "sip %s", session->account.username);
1609
                                g_thread_try_new(tname, janus_sip_sofia_thread, session, &error);
1610
                                if(error != NULL) {
1611
                                        JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the SIP Sofia thread...\n", error->code, error->message ? error->message : "??");
1612
                                        error_code = JANUS_SIP_ERROR_UNKNOWN_ERROR;
1613
                                        g_snprintf(error_cause, 512, "Got error %d (%s) trying to launch the SIP Sofia thread", error->code, error->message ? error->message : "??");
1614
                                        goto error;
1615
                                }
1616
                                long int timeout = 0;
1617
                                while(session->stack == NULL || session->stack->s_nua == NULL) {
1618
                                        g_usleep(100000);
1619
                                        timeout += 100000;
1620
                                        if(timeout >= 2000000) {
1621
                                                break;
1622
                                        }
1623
                                }
1624
                                if(timeout >= 2000000) {
1625
                                        JANUS_LOG(LOG_ERR, "Two seconds passed and still no NUA, problems with the thread?\n");
1626
                                        error_code = JANUS_SIP_ERROR_UNKNOWN_ERROR;
1627
                                        g_snprintf(error_cause, 512, "Two seconds passed and still no NUA, problems with the thread?");
1628
                                        goto error;
1629
                                }
1630
                        }
1631
                        if(session->stack->s_nh_r != NULL) {
1632
                                nua_handle_destroy(session->stack->s_nh_r);
1633
                                session->stack->s_nh_r = NULL;
1634
                        }
1635

    
1636
                        if(send_register) {
1637
                                /* Check if the REGISTER needs to be enriched with custom headers */
1638
                                char custom_headers[2048];
1639
                                custom_headers[0] = '\0';
1640
                                json_t *headers = json_object_get(root, "headers");
1641
                                if(headers) {
1642
                                        if(json_object_size(headers) > 0) {
1643
                                                /* Parse custom headers */
1644
                                                const char *key = NULL;
1645
                                                json_t *value = NULL;
1646
                                                void *iter = json_object_iter(headers);
1647
                                                while(iter != NULL) {
1648
                                                        key = json_object_iter_key(iter);
1649
                                                        value = json_object_get(headers, key);
1650
                                                        if(value == NULL || !json_is_string(value)) {
1651
                                                                JANUS_LOG(LOG_WARN, "Skipping header '%s': value is not a string\n", key);
1652
                                                                iter = json_object_iter_next(headers, iter);
1653
                                                                continue;
1654
                                                        }
1655
                                                        char h[255];
1656
                                                        g_snprintf(h, 255, "%s: %s\r\n", key, json_string_value(value));
1657
                                                        JANUS_LOG(LOG_VERB, "Adding custom header, %s", h);
1658
                                                        g_strlcat(custom_headers, h, 2048);
1659
                                                        iter = json_object_iter_next(headers, iter);
1660
                                                }
1661
                                        }
1662
                                }
1663
                                session->stack->s_nh_r = nua_handle(session->stack->s_nua, session, TAG_END());
1664
                                if(session->stack->s_nh_r == NULL) {
1665
                                        JANUS_LOG(LOG_ERR, "NUA Handle for REGISTER still null??\n");
1666
                                        error_code = JANUS_SIP_ERROR_LIBSOFIA_ERROR;
1667
                                        g_snprintf(error_cause, 512, "Invalid NUA Handle");
1668
                                        goto error;
1669
                                }
1670
                                char ttl_text[20];
1671
                                g_snprintf(ttl_text, sizeof(ttl_text), "%d", ttl);
1672
                                nua_register(session->stack->s_nh_r,
1673
                                        NUTAG_M_USERNAME(session->account.authuser),
1674
                                        NUTAG_M_DISPLAY(session->account.display_name),
1675
                                        SIPTAG_FROM_STR(username_text),
1676
                                        SIPTAG_TO_STR(username_text),
1677
                                        TAG_IF(strlen(custom_headers) > 0, SIPTAG_HEADER_STR(custom_headers)),
1678
                                        SIPTAG_EXPIRES_STR(ttl_text),
1679
                                        NUTAG_REGISTRAR(proxy_text),
1680
                                        NUTAG_PROXY(obproxy_text),
1681
                                        TAG_END());
1682
                                result = json_object();
1683
                                json_object_set_new(result, "event", json_string("registering"));
1684
                        } else {
1685
                                JANUS_LOG(LOG_VERB, "Not sending a SIP REGISTER: either send_register was set to false or guest mode was enabled\n");
1686
                                session->account.registration_status = janus_sip_registration_status_disabled;
1687
                                result = json_object();
1688
                                json_object_set_new(result, "event", json_string("registered"));
1689
                                json_object_set_new(result, "username", json_string(session->account.username));
1690
                                json_object_set_new(result, "register_sent", json_false());
1691
                                /* Also notify event handlers */
1692
                                if(notify_events && gateway->events_is_enabled()) {
1693
                                        json_t *info = json_object();
1694
                                        json_object_set_new(info, "event", json_string("registered"));
1695
                                        json_object_set_new(info, "identity", json_string(session->account.identity));
1696
                                        json_object_set_new(info, "type", json_string("guest"));
1697
                                        gateway->notify_event(&janus_sip_plugin, session->handle, info);
1698
                                }
1699
                        }
1700
                } else if(!strcasecmp(request_text, "unregister")) {
1701
                        if(session->stack == NULL) {
1702
                                JANUS_LOG(LOG_ERR, "Wrong state (register first)\n");
1703
                                error_code = JANUS_SIP_ERROR_WRONG_STATE;
1704
                                g_snprintf(error_cause, 512, "Wrong state (register first)");
1705
                                goto error;
1706
                        }
1707
                        if(session->account.registration_status < janus_sip_registration_status_registered) {
1708
                                JANUS_LOG(LOG_ERR, "Wrong state (not registered)\n");
1709
                                error_code = JANUS_SIP_ERROR_WRONG_STATE;
1710
                                g_snprintf(error_cause, 512, "Wrong state (not registered)");
1711
                                goto error;
1712
                        }
1713
                        if(session->stack->s_nh_r == NULL) {
1714
                                JANUS_LOG(LOG_ERR, "NUA Handle for REGISTER still null??\n");
1715
                                error_code = JANUS_SIP_ERROR_LIBSOFIA_ERROR;
1716
                                g_snprintf(error_cause, 512, "Invalid NUA Handle");
1717
                                goto error;
1718
                        }
1719
                        /* Unregister now */
1720
                        session->account.registration_status = janus_sip_registration_status_unregistering;
1721
                        nua_unregister(session->stack->s_nh_r, TAG_END());
1722
                        result = json_object();
1723
                        json_object_set_new(result, "event", json_string("unregistering"));
1724
                } else if(!strcasecmp(request_text, "call")) {
1725
                        /* Call another peer */
1726
                        if(session->stack == NULL) {
1727
                                JANUS_LOG(LOG_ERR, "Wrong state (register first)\n");
1728
                                error_code = JANUS_SIP_ERROR_WRONG_STATE;
1729
                                g_snprintf(error_cause, 512, "Wrong state (register first)");
1730
                                goto error;
1731
                        }
1732
                        if(session->status >= janus_sip_call_status_inviting) {
1733
                                JANUS_LOG(LOG_ERR, "Wrong state (already in a call? status=%s)\n", janus_sip_call_status_string(session->status));
1734
                                error_code = JANUS_SIP_ERROR_WRONG_STATE;
1735
                                g_snprintf(error_cause, 512, "Wrong state (already in a call? status=%s)", janus_sip_call_status_string(session->status));
1736
                                goto error;
1737
                        }
1738
                        JANUS_VALIDATE_JSON_OBJECT(root, call_parameters,
1739
                                error_code, error_cause, TRUE,
1740
                                JANUS_SIP_ERROR_MISSING_ELEMENT, JANUS_SIP_ERROR_INVALID_ELEMENT);
1741
                        if(error_code != 0)
1742
                                goto error;
1743
                        json_t *uri = json_object_get(root, "uri");
1744
                        /* Check if we need to ACK manually (e.g., for the Record-Route hack) */
1745
                        json_t *autoack = json_object_get(root, "autoack");
1746
                        gboolean do_autoack = autoack ? json_is_true(autoack) : TRUE;
1747
                        /* Check if the INVITE needs to be enriched with custom headers */
1748
                        char custom_headers[2048];
1749
                        custom_headers[0] = '\0';
1750
                        json_t *headers = json_object_get(root, "headers");
1751
                        if(headers) {
1752
                                if(json_object_size(headers) > 0) {
1753
                                        /* Parse custom headers */
1754
                                        const char *key = NULL;
1755
                                        json_t *value = NULL;
1756
                                        void *iter = json_object_iter(headers);
1757
                                        while(iter != NULL) {
1758
                                                key = json_object_iter_key(iter);
1759
                                                value = json_object_get(headers, key);
1760
                                                if(value == NULL || !json_is_string(value)) {
1761
                                                        JANUS_LOG(LOG_WARN, "Skipping header '%s': value is not a string\n", key);
1762
                                                        iter = json_object_iter_next(headers, iter);
1763
                                                        continue;
1764
                                                }
1765
                                                char h[255];
1766
                                                g_snprintf(h, 255, "%s: %s\r\n", key, json_string_value(value));
1767
                                                JANUS_LOG(LOG_VERB, "Adding custom header, %s", h);
1768
                                                g_strlcat(custom_headers, h, 2048);
1769
                                                iter = json_object_iter_next(headers, iter);
1770
                                        }
1771
                                }
1772
                        }
1773
                        /* SDES-SRTP is disabled by default, let's see if we need to enable it */
1774
                        gboolean offer_srtp = FALSE, require_srtp = FALSE;
1775
                        json_t *srtp = json_object_get(root, "srtp");
1776
                        if(srtp) {
1777
                                const char *srtp_text = json_string_value(srtp);
1778
                                if(!strcasecmp(srtp_text, "sdes_optional")) {
1779
                                        /* Negotiate SDES, but make it optional */
1780
                                        offer_srtp = TRUE;
1781
                                } else if(!strcasecmp(srtp_text, "sdes_mandatory")) {
1782
                                        /* Negotiate SDES, and require it */
1783
                                        offer_srtp = TRUE;
1784
                                        require_srtp = TRUE;
1785
                                } else {
1786
                                        JANUS_LOG(LOG_ERR, "Invalid element (srtp can only be sdes_optional or sdes_mandatory)\n");
1787
                                        error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
1788
                                        g_snprintf(error_cause, 512, "Invalid element (srtp can only be sdes_optional or sdes_mandatory)");
1789
                                        goto error;
1790
                                }
1791
                        }
1792
                        /* Parse address */
1793
                        const char *uri_text = json_string_value(uri);
1794
                        janus_sip_uri_t target_uri;
1795
                        if (janus_sip_parse_uri(&target_uri, uri_text) < 0) {
1796
                                JANUS_LOG(LOG_ERR, "Invalid user address %s\n", uri_text);
1797
                                error_code = JANUS_SIP_ERROR_INVALID_ADDRESS;
1798
                                g_snprintf(error_cause, 512, "Invalid user address %s\n", uri_text);
1799
                                goto error;
1800
                        }
1801
                        /* Any SDP to handle? if not, something's wrong */
1802
                        const char *msg_sdp_type = json_string_value(json_object_get(msg->jsep, "type"));
1803
                        const char *msg_sdp = json_string_value(json_object_get(msg->jsep, "sdp"));
1804
                        if(!msg_sdp) {
1805
                                JANUS_LOG(LOG_ERR, "Missing SDP\n");
1806
                                error_code = JANUS_SIP_ERROR_MISSING_SDP;
1807
                                g_snprintf(error_cause, 512, "Missing SDP");
1808
                                goto error;
1809
                        }
1810
                        if(strstr(msg_sdp, "m=application")) {
1811
                                JANUS_LOG(LOG_ERR, "The SIP plugin does not support DataChannels\n");
1812
                                error_code = JANUS_SIP_ERROR_MISSING_SDP;
1813
                                g_snprintf(error_cause, 512, "The SIP plugin does not support DataChannels");
1814
                                goto error;
1815
                        }
1816
                        JANUS_LOG(LOG_VERB, "%s is calling %s\n", session->account.username, uri_text);
1817
                        JANUS_LOG(LOG_VERB, "This is involving a negotiation (%s) as well:\n%s\n", msg_sdp_type, msg_sdp);
1818
                        /* Clean up SRTP stuff from before first, in case it's still needed */
1819
                        janus_sip_srtp_cleanup(session);
1820
                        session->media.require_srtp = require_srtp;
1821
                        session->media.has_srtp_local = offer_srtp;
1822
                        if(offer_srtp) {
1823
                                JANUS_LOG(LOG_VERB, "Going to negotiate SDES-SRTP (%s)...\n", require_srtp ? "mandatory" : "optional");
1824
                        }
1825
                        /* Parse the SDP we got, manipulate some things, and generate a new one */
1826
                        char sdperror[100];
1827
                        janus_sdp *parsed_sdp = janus_sdp_parse(msg_sdp, sdperror, sizeof(sdperror));
1828
                        if(!parsed_sdp) {
1829
                                JANUS_LOG(LOG_ERR, "Error parsing SDP: %s\n", sdperror);
1830
                                error_code = JANUS_SIP_ERROR_MISSING_SDP;
1831
                                g_snprintf(error_cause, 512, "Error parsing SDP: %s", sdperror);
1832
                                goto error;
1833
                        }
1834
                        /* Allocate RTP ports and merge them with the anonymized SDP */
1835
                        if(strstr(msg_sdp, "m=audio") && !strstr(msg_sdp, "m=audio 0")) {
1836
                                JANUS_LOG(LOG_VERB, "Going to negotiate audio...\n");
1837
                                session->media.has_audio = TRUE;        /* FIXME Maybe we need a better way to signal this */
1838
                        }
1839
                        if(strstr(msg_sdp, "m=video") && !strstr(msg_sdp, "m=video 0")) {
1840
                                JANUS_LOG(LOG_VERB, "Going to negotiate video...\n");
1841
                                session->media.has_video = TRUE;        /* FIXME Maybe we need a better way to signal this */
1842
                        }
1843
                        if(janus_sip_allocate_local_ports(session) < 0) {
1844
                                JANUS_LOG(LOG_ERR, "Could not allocate RTP/RTCP ports\n");
1845
                                janus_sdp_free(parsed_sdp);
1846
                                error_code = JANUS_SIP_ERROR_IO_ERROR;
1847
                                g_snprintf(error_cause, 512, "Could not allocate RTP/RTCP ports");
1848
                                goto error;
1849
                        }
1850
                        char *sdp = janus_sip_sdp_manipulate(session, parsed_sdp, FALSE);
1851
                        if(sdp == NULL) {
1852
                                JANUS_LOG(LOG_ERR, "Could not allocate RTP/RTCP ports\n");
1853
                                janus_sdp_free(parsed_sdp);
1854
                                error_code = JANUS_SIP_ERROR_IO_ERROR;
1855
                                g_snprintf(error_cause, 512, "Could not allocate RTP/RTCP ports");
1856
                                goto error;
1857
                        }
1858
                        /* Take note of the SDP (may be useful for UPDATEs or re-INVITEs) */
1859
                        janus_sdp_free(session->sdp);
1860
                        session->sdp = parsed_sdp;
1861
                        JANUS_LOG(LOG_VERB, "Prepared SDP for INVITE:\n%s", sdp);
1862
                        /* Prepare the From header */
1863
                        char from_hdr[1024];
1864
                        if (session->account.display_name) {
1865
                                g_snprintf(from_hdr, sizeof(from_hdr), "\"%s\" <%s>", session->account.display_name, session->account.identity);
1866
                        } else {
1867
                                g_snprintf(from_hdr, sizeof(from_hdr), "%s", session->account.identity);
1868
                        }
1869
                        /* Prepare the stack */
1870
                        if(session->stack->s_nh_i != NULL)
1871
                                nua_handle_destroy(session->stack->s_nh_i);
1872
                        session->stack->s_nh_i = nua_handle(session->stack->s_nua, session, TAG_END());
1873
                        if(session->stack->s_nh_i == NULL) {
1874
                                JANUS_LOG(LOG_WARN, "NUA Handle for INVITE still null??\n");
1875
                                g_free(sdp);
1876
                                session->sdp = NULL;
1877
                                janus_sdp_free(parsed_sdp);
1878
                                error_code = JANUS_SIP_ERROR_LIBSOFIA_ERROR;
1879
                                g_snprintf(error_cause, 512, "Invalid NUA Handle");
1880
                                goto error;
1881
                        }
1882
                        g_atomic_int_set(&session->hangingup, 0);
1883
                        session->status = janus_sip_call_status_inviting;
1884
                        /* Create a random call-id */
1885
                        char callid[24];
1886
                        janus_sip_random_string(24, (char *)&callid);
1887
                        /* Also notify event handlers */
1888
                        if(notify_events && gateway->events_is_enabled()) {
1889
                                json_t *info = json_object();
1890
                                json_object_set_new(info, "event", json_string("calling"));
1891
                                json_object_set_new(info, "callee", json_string(uri_text));
1892
                                json_object_set_new(info, "call-id", json_string(callid));
1893
                                json_object_set_new(info, "sdp", json_string(sdp));
1894
                                gateway->notify_event(&janus_sip_plugin, session->handle, info);
1895
                        }
1896
                        /* Send INVITE */
1897
                        session->callee = g_strdup(uri_text);
1898
                        session->callid = g_strdup(callid);
1899
                        g_hash_table_insert(callids, session->callid, session);
1900
                        session->media.autoack = do_autoack;
1901
                        nua_invite(session->stack->s_nh_i,
1902
                                SIPTAG_FROM_STR(from_hdr),
1903
                                SIPTAG_TO_STR(uri_text),
1904
                                SIPTAG_CALL_ID_STR(callid),
1905
                                SOATAG_USER_SDP_STR(sdp),
1906
                                NUTAG_PROXY(session->account.outbound_proxy),
1907
                                TAG_IF(strlen(custom_headers) > 0, SIPTAG_HEADER_STR(custom_headers)),
1908
                                NUTAG_AUTOANSWER(0),
1909
                                NUTAG_AUTOACK(do_autoack),
1910
                                TAG_END());
1911
                        g_free(sdp);
1912
                        if(session->transaction)
1913
                                g_free(session->transaction);
1914
                        session->transaction = msg->transaction ? g_strdup(msg->transaction) : NULL;
1915
                        /* Send an ack back */
1916
                        result = json_object();
1917
                        json_object_set_new(result, "event", json_string("calling"));
1918
                } else if(!strcasecmp(request_text, "accept")) {
1919
                        if(session->status != janus_sip_call_status_invited) {
1920
                                JANUS_LOG(LOG_ERR, "Wrong state (not invited? status=%s)\n", janus_sip_call_status_string(session->status));
1921
                                error_code = JANUS_SIP_ERROR_WRONG_STATE;
1922
                                g_snprintf(error_cause, 512, "Wrong state (not invited? status=%s)", janus_sip_call_status_string(session->status));
1923
                                goto error;
1924
                        }
1925
                        if(session->callee == NULL) {
1926
                                JANUS_LOG(LOG_ERR, "Wrong state (no caller?)\n");
1927
                                error_code = JANUS_SIP_ERROR_WRONG_STATE;
1928
                                g_snprintf(error_cause, 512, "Wrong state (no caller?)");
1929
                                goto error;
1930
                        }
1931
                        JANUS_VALIDATE_JSON_OBJECT(root, accept_parameters,
1932
                                error_code, error_cause, TRUE,
1933
                                JANUS_SIP_ERROR_MISSING_ELEMENT, JANUS_SIP_ERROR_INVALID_ELEMENT);
1934
                        if(error_code != 0)
1935
                                goto error;
1936
                        json_t *srtp = json_object_get(root, "srtp");
1937
                        gboolean answer_srtp = FALSE;
1938
                        if(srtp) {
1939
                                const char *srtp_text = json_string_value(srtp);
1940
                                if(!strcasecmp(srtp_text, "sdes_optional")) {
1941
                                        /* Negotiate SDES, but make it optional */
1942
                                        answer_srtp = TRUE;
1943
                                } else if(!strcasecmp(srtp_text, "sdes_mandatory")) {
1944
                                        /* Negotiate SDES, and require it */
1945
                                        answer_srtp = TRUE;
1946
                                        session->media.require_srtp = TRUE;
1947
                                } else {
1948
                                        JANUS_LOG(LOG_ERR, "Invalid element (srtp can only be sdes_optional or sdes_mandatory)\n");
1949
                                        error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
1950
                                        g_snprintf(error_cause, 512, "Invalid element (srtp can only be sdes_optional or sdes_mandatory)");
1951
                                        goto error;
1952
                                }
1953
                        }
1954
                        if(session->media.require_srtp && !session->media.has_srtp_remote) {
1955
                                JANUS_LOG(LOG_ERR, "Can't accept the call: SDES-SRTP required, but caller didn't offer it\n");
1956
                                error_code = JANUS_SIP_ERROR_TOO_STRICT;
1957
                                g_snprintf(error_cause, 512, "Can't accept the call: SDES-SRTP required, but caller didn't offer it");
1958
                                goto error;
1959
                        }
1960
                        answer_srtp = answer_srtp || session->media.has_srtp_remote;
1961
                        /* Any SDP to handle? if not, something's wrong */
1962
                        const char *msg_sdp_type = json_string_value(json_object_get(msg->jsep, "type"));
1963
                        const char *msg_sdp = json_string_value(json_object_get(msg->jsep, "sdp"));
1964
                        if(!msg_sdp) {
1965
                                JANUS_LOG(LOG_ERR, "Missing SDP\n");
1966
                                error_code = JANUS_SIP_ERROR_MISSING_SDP;
1967
                                g_snprintf(error_cause, 512, "Missing SDP");
1968
                                goto error;
1969
                        }
1970
                        /* Accept a call from another peer */
1971
                        JANUS_LOG(LOG_VERB, "We're accepting the call from %s\n", session->callee);
1972
                        gboolean answer = !strcasecmp(msg_sdp_type, "answer");
1973
                        if(!answer) {
1974
                                JANUS_LOG(LOG_VERB, "This is a response to an offerless INVITE\n");
1975
                        }
1976
                        JANUS_LOG(LOG_VERB, "This is involving a negotiation (%s) as well:\n%s\n", msg_sdp_type, msg_sdp);
1977
                        session->media.has_srtp_local = answer_srtp;
1978
                        if(answer_srtp) {
1979
                                JANUS_LOG(LOG_VERB, "Going to negotiate SDES-SRTP (%s)...\n", session->media.require_srtp ? "mandatory" : "optional");
1980
                        }
1981
                        /* Parse the SDP we got, manipulate some things, and generate a new one */
1982
                        char sdperror[100];
1983
                        janus_sdp *parsed_sdp = janus_sdp_parse(msg_sdp, sdperror, sizeof(sdperror));
1984
                        if(!parsed_sdp) {
1985
                                JANUS_LOG(LOG_ERR, "Error parsing SDP: %s\n", sdperror);
1986
                                error_code = JANUS_SIP_ERROR_MISSING_SDP;
1987
                                g_snprintf(error_cause, 512, "Error parsing SDP: %s", sdperror);
1988
                                goto error;
1989
                        }
1990
                        /* Allocate RTP ports and merge them with the anonymized SDP */
1991
                        if(strstr(msg_sdp, "m=audio") && !strstr(msg_sdp, "m=audio 0")) {
1992
                                JANUS_LOG(LOG_VERB, "Going to negotiate audio...\n");
1993
                                session->media.has_audio = TRUE;        /* FIXME Maybe we need a better way to signal this */
1994
                        }
1995
                        if(strstr(msg_sdp, "m=video") && !strstr(msg_sdp, "m=video 0")) {
1996
                                JANUS_LOG(LOG_VERB, "Going to negotiate video...\n");
1997
                                session->media.has_video = TRUE;        /* FIXME Maybe we need a better way to signal this */
1998
                        }
1999
                        if(janus_sip_allocate_local_ports(session) < 0) {
2000
                                JANUS_LOG(LOG_ERR, "Could not allocate RTP/RTCP ports\n");
2001
                                janus_sdp_free(parsed_sdp);
2002
                                error_code = JANUS_SIP_ERROR_IO_ERROR;
2003
                                g_snprintf(error_cause, 512, "Could not allocate RTP/RTCP ports");
2004
                                goto error;
2005
                        }
2006
                        char *sdp = janus_sip_sdp_manipulate(session, parsed_sdp, TRUE);
2007
                        if(sdp == NULL) {
2008
                                JANUS_LOG(LOG_ERR, "Could not allocate RTP/RTCP ports\n");
2009
                                janus_sdp_free(parsed_sdp);
2010
                                error_code = JANUS_SIP_ERROR_IO_ERROR;
2011
                                g_snprintf(error_cause, 512, "Could not allocate RTP/RTCP ports");
2012
                                goto error;
2013
                        }
2014
                        if(session->media.audio_pt > -1) {
2015
                                session->media.audio_pt_name = janus_get_codec_from_pt(sdp, session->media.audio_pt);
2016
                                JANUS_LOG(LOG_VERB, "Detected audio codec: %d (%s)\n", session->media.audio_pt, session->media.audio_pt_name);
2017
                        }
2018
                        if(session->media.video_pt > -1) {
2019
                                session->media.video_pt_name = janus_get_codec_from_pt(sdp, session->media.video_pt);
2020
                                JANUS_LOG(LOG_VERB, "Detected video codec: %d (%s)\n", session->media.video_pt, session->media.video_pt_name);
2021
                        }
2022
                        /* Take note of the SDP (may be useful for UPDATEs or re-INVITEs) */
2023
                        janus_sdp_free(session->sdp);
2024
                        session->sdp = parsed_sdp;
2025
                        JANUS_LOG(LOG_VERB, "Prepared SDP for 200 OK:\n%s", sdp);
2026
                        /* Also notify event handlers */
2027
                        if(notify_events && gateway->events_is_enabled()) {
2028
                                json_t *info = json_object();
2029
                                json_object_set_new(info, "event", json_string("accepted"));
2030
                                if(session->callid)
2031
                                        json_object_set_new(info, "call-id", json_string(session->callid));
2032
                                gateway->notify_event(&janus_sip_plugin, session->handle, info);
2033
                        }
2034
                        /* Send 200 OK */
2035
                        if(!answer) {
2036
                                if(session->transaction)
2037
                                        g_free(session->transaction);
2038
                                session->transaction = msg->transaction ? g_strdup(msg->transaction) : NULL;
2039
                        }
2040
                        g_atomic_int_set(&session->hangingup, 0);
2041
                        session->status = janus_sip_call_status_incall;
2042
                        if(session->stack->s_nh_i == NULL) {
2043
                                JANUS_LOG(LOG_WARN, "NUA Handle for 200 OK still null??\n");
2044
                        }
2045
                        nua_respond(session->stack->s_nh_i,
2046
                                200, sip_status_phrase(200),
2047
                                SOATAG_USER_SDP_STR(sdp),
2048
                                NUTAG_AUTOANSWER(0),
2049
                                TAG_END());
2050
                        g_free(sdp);
2051
                        /* Send an ack back */
2052
                        result = json_object();
2053
                        json_object_set_new(result, "event", json_string("accepted"));
2054
                        if(answer) {
2055
                                /* Start the media */
2056
                                session->media.ready = TRUE;        /* FIXME Maybe we need a better way to signal this */
2057
                                GError *error = NULL;
2058
                                char tname[16];
2059
                                g_snprintf(tname, sizeof(tname), "siprtp %s", session->account.username);
2060
                                g_thread_try_new(tname, janus_sip_relay_thread, session, &error);
2061
                                if(error != NULL) {
2062
                                        JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the RTP/RTCP thread...\n", error->code, error->message ? error->message : "??");
2063
                                }
2064
                        }
2065
                } else if(!strcasecmp(request_text, "decline")) {
2066
                        /* Reject an incoming call */
2067
                        if(session->status != janus_sip_call_status_invited) {
2068
                                JANUS_LOG(LOG_ERR, "Wrong state (not invited? status=%s)\n", janus_sip_call_status_string(session->status));
2069
                                /* Ignore */
2070
                                janus_sip_message_free(msg);
2071
                                continue;
2072
                                //~ g_snprintf(error_cause, 512, "Wrong state (not in a call?)");
2073
                                //~ goto error;
2074
                        }
2075
                        if(session->callee == NULL) {
2076
                                JANUS_LOG(LOG_ERR, "Wrong state (no callee?)\n");
2077
                                error_code = JANUS_SIP_ERROR_WRONG_STATE;
2078
                                g_snprintf(error_cause, 512, "Wrong state (no callee?)");
2079
                                goto error;
2080
                        }
2081
                        session->media.ready = FALSE;
2082
                        session->media.on_hold = FALSE;
2083
                        session->status = janus_sip_call_status_closing;
2084
                        if(session->stack->s_nh_i == NULL) {
2085
                                JANUS_LOG(LOG_WARN, "NUA Handle for 200 OK still null??\n");
2086
                        }
2087
                        int response_code = 486;
2088
                        json_t *code_json = json_object_get(root, "code");
2089
                        if (code_json && json_is_integer(code_json))
2090
                                response_code = json_integer_value(code_json);
2091
                        if (response_code <= 399) {
2092
                                JANUS_LOG(LOG_WARN, "Invalid SIP response code specified, using 486 to decline call\n");
2093
                                response_code = 486;
2094
                        }
2095
                        nua_respond(session->stack->s_nh_i, response_code, sip_status_phrase(response_code), TAG_END());
2096
                        /* Also notify event handlers */
2097
                        if(notify_events && gateway->events_is_enabled()) {
2098
                                json_t *info = json_object();
2099
                                json_object_set_new(info, "event", json_string("declined"));
2100
                                json_object_set_new(info, "callee", json_string(session->callee));
2101
                                if(session->callid)
2102
                                        json_object_set_new(info, "call-id", json_string(session->callid));
2103
                                json_object_set_new(info, "code", json_integer(response_code));
2104
                                gateway->notify_event(&janus_sip_plugin, session->handle, info);
2105
                        }
2106
                        g_free(session->callee);
2107
                        session->callee = NULL;
2108
                        /* Notify the operation */
2109
                        result = json_object();
2110
                        json_object_set_new(result, "event", json_string("declining"));
2111
                        json_object_set_new(result, "code", json_integer(response_code));
2112
                } else if(!strcasecmp(request_text, "hold") || !strcasecmp(request_text, "unhold")) {
2113
                        /* We either need to put the call on-hold, or resume it */
2114
                        if(!(session->status == janus_sip_call_status_inviting || session->status == janus_sip_call_status_incall)) {
2115
                                JANUS_LOG(LOG_ERR, "Wrong state (not in a call? status=%s)\n", janus_sip_call_status_string(session->status));
2116
                                /* Ignore */
2117
                                janus_sip_message_free(msg);
2118
                                continue;
2119
                                //~ g_snprintf(error_cause, 512, "Wrong state (not in a call?)");
2120
                                //~ goto error;
2121
                        }
2122
                        if(session->callee == NULL) {
2123
                                JANUS_LOG(LOG_ERR, "Wrong state (no callee?)\n");
2124
                                error_code = JANUS_SIP_ERROR_WRONG_STATE;
2125
                                g_snprintf(error_cause, 512, "Wrong state (no callee?)");
2126
                                goto error;
2127
                        }
2128
                        if(session->sdp == NULL) {
2129
                                JANUS_LOG(LOG_ERR, "Wrong state (no SDP?)\n");
2130
                                error_code = JANUS_SIP_ERROR_WRONG_STATE;
2131
                                g_snprintf(error_cause, 512, "Wrong state (no SDP?)");
2132
                                goto error;
2133
                        }
2134
                        gboolean hold = !strcasecmp(request_text, "hold");
2135
                        if(hold != session->media.on_hold) {
2136
                                /* To put the call on-hold, we need to set the direction to recvonly:
2137
                                 * resuming it means resuming the direction we had before */
2138
                                session->media.on_hold = hold;
2139
                                janus_sdp_mline *m = janus_sdp_mline_find(session->sdp, JANUS_SDP_AUDIO);
2140
                                if(m) {
2141
                                        if(hold) {
2142
                                                /* Take note of the original media direction */
2143
                                                session->media.pre_hold_audio_dir = m->direction;
2144
                                                /* Update the media direction */
2145
                                                switch(m->direction) {
2146
                                                        case JANUS_SDP_DEFAULT:
2147
                                                        case JANUS_SDP_SENDRECV:
2148
                                                                m->direction = JANUS_SDP_SENDONLY;
2149
                                                                break;
2150
                                                        default:
2151
                                                                m->direction = JANUS_SDP_INACTIVE;
2152
                                                                break;
2153
                                                }
2154
                                        } else {
2155
                                                m->direction = session->media.pre_hold_audio_dir;
2156
                                        }
2157
                                }
2158
                                m = janus_sdp_mline_find(session->sdp, JANUS_SDP_VIDEO);
2159
                                if(m) {
2160
                                        if(hold) {
2161
                                                /* Take note of the original media direction */
2162
                                                session->media.pre_hold_video_dir = m->direction;
2163
                                                /* Update the media direction */
2164
                                                switch(m->direction) {
2165
                                                        case JANUS_SDP_DEFAULT:
2166
                                                        case JANUS_SDP_SENDRECV:
2167
                                                                m->direction = JANUS_SDP_SENDONLY;
2168
                                                                break;
2169
                                                        default:
2170
                                                                m->direction = JANUS_SDP_INACTIVE;
2171
                                                                break;
2172
                                                }
2173
                                        } else {
2174
                                                m->direction = session->media.pre_hold_video_dir;
2175
                                        }
2176
                                }
2177
                                /* Send the re-INVITE */
2178
                                char *sdp = janus_sdp_write(session->sdp);
2179
                                nua_invite(session->stack->s_nh_i,
2180
                                        SOATAG_USER_SDP_STR(sdp),
2181
                                        TAG_END());
2182
                                g_free(sdp);
2183
                        }
2184
                        /* Send an ack back */
2185
                        result = json_object();
2186
                        json_object_set_new(result, "event", json_string(hold ? "holding" : "resuming"));
2187
                } else if(!strcasecmp(request_text, "hangup")) {
2188
                        /* Hangup an ongoing call */
2189
                        if(!(session->status == janus_sip_call_status_inviting || session->status == janus_sip_call_status_incall)) {
2190
                                JANUS_LOG(LOG_ERR, "Wrong state (not in a call? status=%s)\n", janus_sip_call_status_string(session->status));
2191
                                /* Ignore */
2192
                                janus_sip_message_free(msg);
2193
                                continue;
2194
                                //~ g_snprintf(error_cause, 512, "Wrong state (not in a call?)");
2195
                                //~ goto error;
2196
                        }
2197
                        if(session->callee == NULL) {
2198
                                JANUS_LOG(LOG_ERR, "Wrong state (no callee?)\n");
2199
                                error_code = JANUS_SIP_ERROR_WRONG_STATE;
2200
                                g_snprintf(error_cause, 512, "Wrong state (no callee?)");
2201
                                goto error;
2202
                        }
2203
                        session->media.ready = FALSE;
2204
                        session->media.on_hold = FALSE;
2205
                        session->status = janus_sip_call_status_closing;
2206
                        nua_bye(session->stack->s_nh_i, TAG_END());
2207
                        g_free(session->callee);
2208
                        session->callee = NULL;
2209
                        /* Notify the operation */
2210
                        result = json_object();
2211
                        json_object_set_new(result, "event", json_string("hangingup"));
2212
                } else if(!strcasecmp(request_text, "recording")) {
2213
                        /* Start or stop recording */
2214
                        if(!(session->status == janus_sip_call_status_inviting || session->status == janus_sip_call_status_incall)) {
2215
                                JANUS_LOG(LOG_ERR, "Wrong state (not in a call? status=%s)\n", janus_sip_call_status_string(session->status));
2216
                                g_snprintf(error_cause, 512, "Wrong state (not in a call?)");
2217
                                goto error;
2218
                        }
2219
                        if(session->callee == NULL) {
2220
                                JANUS_LOG(LOG_ERR, "Wrong state (no callee?)\n");
2221
                                error_code = JANUS_SIP_ERROR_WRONG_STATE;
2222
                                g_snprintf(error_cause, 512, "Wrong state (no callee?)");
2223
                                goto error;
2224
                        }
2225
                        JANUS_VALIDATE_JSON_OBJECT(root, recording_parameters,
2226
                                error_code, error_cause, TRUE,
2227
                                JANUS_SIP_ERROR_MISSING_ELEMENT, JANUS_SIP_ERROR_INVALID_ELEMENT);
2228
                        if(error_code != 0)
2229
                                goto error;
2230
                        json_t *action = json_object_get(root, "action");
2231
                        const char *action_text = json_string_value(action);
2232
                        if(strcasecmp(action_text, "start") && strcasecmp(action_text, "stop")) {
2233
                                JANUS_LOG(LOG_ERR, "Invalid action (should be start|stop)\n");
2234
                                error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
2235
                                g_snprintf(error_cause, 512, "Invalid action (should be start|stop)");
2236
                                goto error;
2237
                        }
2238
                        gboolean record_audio = FALSE, record_video = FALSE,        /* No media is recorded by default */
2239
                                record_peer_audio = FALSE, record_peer_video = FALSE;
2240
                        json_t *audio = json_object_get(root, "audio");
2241
                        record_audio = audio ? json_is_true(audio) : FALSE;
2242
                        json_t *video = json_object_get(root, "video");
2243
                        record_video = video ? json_is_true(video) : FALSE;
2244
                        json_t *peer_audio = json_object_get(root, "peer_audio");
2245
                        record_peer_audio = peer_audio ? json_is_true(peer_audio) : FALSE;
2246
                        json_t *peer_video = json_object_get(root, "peer_video");
2247
                        record_peer_video = peer_video ? json_is_true(peer_video) : FALSE;
2248
                        if(!record_audio && !record_video && !record_peer_audio && !record_peer_video) {
2249
                                JANUS_LOG(LOG_ERR, "Invalid request (at least one of audio, video, peer_audio and peer_video should be true)\n");
2250
                                error_code = JANUS_SIP_ERROR_RECORDING_ERROR;
2251
                                g_snprintf(error_cause, 512, "Invalid request (at least one of audio, video, peer_audio and peer_video should be true)");
2252
                                goto error;
2253
                        }
2254
                        json_t *recfile = json_object_get(root, "filename");
2255
                        const char *recording_base = json_string_value(recfile);
2256
                        janus_mutex_lock(&session->rec_mutex);
2257
                        if(!strcasecmp(action_text, "start")) {
2258
                                /* Start recording something */
2259
                                char filename[255];
2260
                                gint64 now = janus_get_real_time();
2261
                                if(record_peer_audio || record_peer_video) {
2262
                                        JANUS_LOG(LOG_INFO, "Starting recording of peer's %s (user %s, call %s)\n",
2263
                                                (record_peer_audio && record_peer_video ? "audio and video" : (record_peer_audio ? "audio" : "video")),
2264
                                                session->account.username, session->transaction);
2265
                                        /* Start recording this peer's audio and/or video */
2266
                                        if(record_peer_audio) {
2267
                                                memset(filename, 0, 255);
2268
                                                if(recording_base) {
2269
                                                        /* Use the filename and path we have been provided */
2270
                                                        g_snprintf(filename, 255, "%s-peer-audio", recording_base);
2271
                                                        /* FIXME This only works if offer/answer happened */
2272
                                                        session->arc_peer = janus_recorder_create(NULL, session->media.audio_pt_name, filename);
2273
                                                        if(session->arc_peer == NULL) {
2274
                                                                /* FIXME We should notify the fact the recorder could not be created */
2275
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an audio recording file for this peer!\n");
2276
                                                        }
2277
                                                } else {
2278
                                                        /* Build a filename */
2279
                                                        g_snprintf(filename, 255, "sip-%s-%s-%"SCNi64"-peer-audio",
2280
                                                                session->account.username ? session->account.username : "unknown",
2281
                                                                session->transaction ? session->transaction : "unknown",
2282
                                                                now);
2283
                                                        /* FIXME This only works if offer/answer happened */
2284
                                                        session->arc_peer = janus_recorder_create(NULL, session->media.audio_pt_name, filename);
2285
                                                        if(session->arc_peer == NULL) {
2286
                                                                /* FIXME We should notify the fact the recorder could not be created */
2287
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an audio recording file for this peer!\n");
2288
                                                        }
2289
                                                }
2290
                                        }
2291
                                        if(record_peer_video) {
2292
                                                memset(filename, 0, 255);
2293
                                                if(recording_base) {
2294
                                                        /* Use the filename and path we have been provided */
2295
                                                        g_snprintf(filename, 255, "%s-peer-video", recording_base);
2296
                                                        /* FIXME This only works if offer/answer happened */
2297
                                                        session->vrc_peer = janus_recorder_create(NULL, session->media.video_pt_name, filename);
2298
                                                        if(session->vrc_peer == NULL) {
2299
                                                                /* FIXME We should notify the fact the recorder could not be created */
2300
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an video recording file for this peer!\n");
2301
                                                        }
2302
                                                } else {
2303
                                                        /* Build a filename */
2304
                                                        g_snprintf(filename, 255, "sip-%s-%s-%"SCNi64"-peer-video",
2305
                                                                session->account.username ? session->account.username : "unknown",
2306
                                                                session->transaction ? session->transaction : "unknown",
2307
                                                                now);
2308
                                                        /* FIXME This only works if offer/answer happened */
2309
                                                        session->vrc_peer = janus_recorder_create(NULL, session->media.video_pt_name, filename);
2310
                                                        if(session->vrc_peer == NULL) {
2311
                                                                /* FIXME We should notify the fact the recorder could not be created */
2312
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an video recording file for this peer!\n");
2313
                                                        }
2314
                                                }
2315
                                                /* TODO We should send a FIR/PLI to this peer... */
2316
                                        }
2317
                                }
2318
                                if(record_audio || record_video) {
2319
                                        /* Start recording the user's audio and/or video */
2320
                                        JANUS_LOG(LOG_INFO, "Starting recording of user's %s (user %s, call %s)\n",
2321
                                                (record_audio && record_video ? "audio and video" : (record_audio ? "audio" : "video")),
2322
                                                session->account.username, session->transaction);
2323
                                        if(record_audio) {
2324
                                                memset(filename, 0, 255);
2325
                                                if(recording_base) {
2326
                                                        /* Use the filename and path we have been provided */
2327
                                                        g_snprintf(filename, 255, "%s-user-audio", recording_base);
2328
                                                        /* FIXME This only works if offer/answer happened */
2329
                                                        session->arc = janus_recorder_create(NULL, session->media.audio_pt_name, filename);
2330
                                                        if(session->arc == NULL) {
2331
                                                                /* FIXME We should notify the fact the recorder could not be created */
2332
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an audio recording file for this peer!\n");
2333
                                                        }
2334
                                                } else {
2335
                                                        /* Build a filename */
2336
                                                        g_snprintf(filename, 255, "sip-%s-%s-%"SCNi64"-own-audio",
2337
                                                                session->account.username ? session->account.username : "unknown",
2338
                                                                session->transaction ? session->transaction : "unknown",
2339
                                                                now);
2340
                                                        /* FIXME This only works if offer/answer happened */
2341
                                                        session->arc = janus_recorder_create(NULL, session->media.audio_pt_name, filename);
2342
                                                        if(session->arc == NULL) {
2343
                                                                /* FIXME We should notify the fact the recorder could not be created */
2344
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an audio recording file for this peer!\n");
2345
                                                        }
2346
                                                }
2347
                                        }
2348
                                        if(record_video) {
2349
                                                memset(filename, 0, 255);
2350
                                                if(recording_base) {
2351
                                                        /* Use the filename and path we have been provided */
2352
                                                        g_snprintf(filename, 255, "%s-user-video", recording_base);
2353
                                                        /* FIXME This only works if offer/answer happened */
2354
                                                        session->vrc = janus_recorder_create(NULL, session->media.video_pt_name, filename);
2355
                                                        if(session->vrc == NULL) {
2356
                                                                /* FIXME We should notify the fact the recorder could not be created */
2357
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an video recording file for this user!\n");
2358
                                                        }
2359
                                                } else {
2360
                                                        /* Build a filename */
2361
                                                        g_snprintf(filename, 255, "sip-%s-%s-%"SCNi64"-own-video",
2362
                                                                session->account.username ? session->account.username : "unknown",
2363
                                                                session->transaction ? session->transaction : "unknown",
2364
                                                                now);
2365
                                                        /* FIXME This only works if offer/answer happened */
2366
                                                        session->vrc = janus_recorder_create(NULL, session->media.video_pt_name, filename);
2367
                                                        if(session->vrc == NULL) {
2368
                                                                /* FIXME We should notify the fact the recorder could not be created */
2369
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an video recording file for this user!\n");
2370
                                                        }
2371
                                                }
2372
                                                /* Send a PLI */
2373
                                                JANUS_LOG(LOG_VERB, "Recording video, sending a PLI to kickstart it\n");
2374
                                                char buf[12];
2375
                                                janus_rtcp_pli((char *)&buf, 12);
2376
                                                gateway->relay_rtcp(session->handle, 1, buf, 12);
2377
                                        }
2378
                                }
2379
                        } else {
2380
                                /* Stop recording something: notice that this never returns an error, even when we were not recording anything */
2381
                                if(record_audio) {
2382
                                        if(session->arc) {
2383
                                                janus_recorder_close(session->arc);
2384
                                                JANUS_LOG(LOG_INFO, "Closed user's audio recording %s\n", session->arc->filename ? session->arc->filename : "??");
2385
                                                janus_recorder_free(session->arc);
2386
                                        }
2387
                                        session->arc = NULL;
2388
                                }
2389
                                if(record_video) {
2390
                                        if(session->vrc) {
2391
                                                janus_recorder_close(session->vrc);
2392
                                                JANUS_LOG(LOG_INFO, "Closed user's video recording %s\n", session->vrc->filename ? session->vrc->filename : "??");
2393
                                                janus_recorder_free(session->vrc);
2394
                                        }
2395
                                        session->vrc = NULL;
2396
                                }
2397
                                if(record_peer_audio) {
2398
                                        if(session->arc_peer) {
2399
                                                janus_recorder_close(session->arc_peer);
2400
                                                JANUS_LOG(LOG_INFO, "Closed peer's audio recording %s\n", session->arc_peer->filename ? session->arc_peer->filename : "??");
2401
                                                janus_recorder_free(session->arc_peer);
2402
                                        }
2403
                                        session->arc_peer = NULL;
2404
                                }
2405
                                if(record_peer_video) {
2406
                                        if(session->vrc_peer) {
2407
                                                janus_recorder_close(session->vrc_peer);
2408
                                                JANUS_LOG(LOG_INFO, "Closed peer's video recording %s\n", session->vrc_peer->filename ? session->vrc_peer->filename : "??");
2409
                                                janus_recorder_free(session->vrc_peer);
2410
                                        }
2411
                                        session->vrc_peer = NULL;
2412
                                }
2413
                        }
2414
                        janus_mutex_unlock(&session->rec_mutex);
2415
                        /* Notify the result */
2416
                        result = json_object();
2417
                        json_object_set_new(result, "event", json_string("recordingupdated"));
2418
                } else if(!strcasecmp(request_text, "info")) {
2419
                        /* Send a SIP INFO request: we'll need the payload type and content */
2420
                        if(!(session->status == janus_sip_call_status_inviting || session->status == janus_sip_call_status_incall)) {
2421
                                JANUS_LOG(LOG_ERR, "Wrong state (not in a call? status=%s)\n", janus_sip_call_status_string(session->status));
2422
                                g_snprintf(error_cause, 512, "Wrong state (not in a call?)");
2423
                                goto error;
2424
                        }
2425
                        if(session->callee == NULL) {
2426
                                JANUS_LOG(LOG_ERR, "Wrong state (no callee?)\n");
2427
                                error_code = JANUS_SIP_ERROR_WRONG_STATE;
2428
                                g_snprintf(error_cause, 512, "Wrong state (no callee?)");
2429
                                goto error;
2430
                        }
2431
                        JANUS_VALIDATE_JSON_OBJECT(root, info_parameters,
2432
                                error_code, error_cause, TRUE,
2433
                                JANUS_SIP_ERROR_MISSING_ELEMENT, JANUS_SIP_ERROR_INVALID_ELEMENT);
2434
                        if(error_code != 0)
2435
                                goto error;
2436
                        const char *info_type = json_string_value(json_object_get(root, "type"));
2437
                        const char *info_content = json_string_value(json_object_get(root, "content"));
2438
                        nua_info(session->stack->s_nh_i,
2439
                                SIPTAG_CONTENT_TYPE_STR(info_type),
2440
                                SIPTAG_PAYLOAD_STR(info_content),
2441
                                TAG_END());
2442
                        /* Notify the operation */
2443
                        result = json_object();
2444
                        json_object_set_new(result, "event", json_string("infosent"));
2445
                } else if(!strcasecmp(request_text, "message")) {
2446
                        /* Send a SIP MESSAGE request: we'll only need the content */
2447
                        if(!(session->status == janus_sip_call_status_inviting || session->status == janus_sip_call_status_incall)) {
2448
                                JANUS_LOG(LOG_ERR, "Wrong state (not in a call? status=%s)\n", janus_sip_call_status_string(session->status));
2449
                                g_snprintf(error_cause, 512, "Wrong state (not in a call?)");
2450
                                goto error;
2451
                        }
2452
                        if(session->callee == NULL) {
2453
                                JANUS_LOG(LOG_ERR, "Wrong state (no callee?)\n");
2454
                                error_code = JANUS_SIP_ERROR_WRONG_STATE;
2455
                                g_snprintf(error_cause, 512, "Wrong state (no callee?)");
2456
                                goto error;
2457
                        }
2458
                        JANUS_VALIDATE_JSON_OBJECT(root, sipmessage_parameters,
2459
                                error_code, error_cause, TRUE,
2460
                                JANUS_SIP_ERROR_MISSING_ELEMENT, JANUS_SIP_ERROR_INVALID_ELEMENT);
2461
                        if(error_code != 0)
2462
                                goto error;
2463
                        const char *msg_content = json_string_value(json_object_get(root, "content"));
2464
                        nua_message(session->stack->s_nh_i,
2465
                                NUTAG_URL(session->callee),
2466
                                SIPTAG_PAYLOAD_STR(msg_content),
2467
                                TAG_END());
2468
                        /* Notify the operation */
2469
                        result = json_object();
2470
                        json_object_set_new(result, "event", json_string("messagesent"));
2471
                } else if(!strcasecmp(request_text, "dtmf_info")) {
2472
                        /* Send DMTF tones using SIP INFO
2473
                         * (https://tools.ietf.org/html/draft-kaplan-dispatch-info-dtmf-package-00)
2474
                         */
2475
                        if(!(session->status == janus_sip_call_status_inviting || session->status == janus_sip_call_status_incall)) {
2476
                                JANUS_LOG(LOG_ERR, "Wrong state (not in a call? status=%s)\n", janus_sip_call_status_string(session->status));
2477
                                g_snprintf(error_cause, 512, "Wrong state (not in a call?)");
2478
                                goto error;
2479
                        }
2480
                        if(session->callee == NULL) {
2481
                                JANUS_LOG(LOG_ERR, "Wrong state (no callee?)\n");
2482
                                error_code = JANUS_SIP_ERROR_WRONG_STATE;
2483
                                g_snprintf(error_cause, 512, "Wrong state (no callee?)");
2484
                                goto error;
2485
                        }
2486
                        JANUS_VALIDATE_JSON_OBJECT(root, dtmf_info_parameters,
2487
                                error_code, error_cause, TRUE,
2488
                                JANUS_SIP_ERROR_MISSING_ELEMENT, JANUS_SIP_ERROR_INVALID_ELEMENT);
2489
                        if(error_code != 0)
2490
                                goto error;
2491
                        json_t *digit = json_object_get(root, "digit");
2492
                        const char *digit_text = json_string_value(digit);
2493
                        if(strlen(digit_text) != 1) {
2494
                                JANUS_LOG(LOG_ERR, "Invalid element (digit should be one character))\n");
2495
                                error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
2496
                                g_snprintf(error_cause, 512, "Invalid element (digit should be one character)");
2497
                                goto error;
2498
                        }
2499
                        int duration_ms = 0;
2500
                        json_t *duration = json_object_get(root, "duration");
2501
                        duration_ms = duration ? json_integer_value(duration) : 0;
2502
                        if (duration_ms <= 0 || duration_ms > 5000) {
2503
                                duration_ms = 160; /* default value */
2504
                        }
2505
                        char payload[64];
2506
                        g_snprintf(payload, sizeof(payload), "Signal=%s\r\nDuration=%d", digit_text, duration_ms);
2507
                        nua_info(session->stack->s_nh_i,
2508
                                SIPTAG_CONTENT_TYPE_STR("application/dtmf-relay"),
2509
                                SIPTAG_PAYLOAD_STR(payload),
2510
                                TAG_END());
2511
                        /* Notify the result */
2512
                        result = json_object();
2513
                        json_object_set_new(result, "event", json_string("dtmfsent"));
2514
                } else {
2515
                        JANUS_LOG(LOG_ERR, "Unknown request (%s)\n", request_text);
2516
                        error_code = JANUS_SIP_ERROR_INVALID_REQUEST;
2517
                        g_snprintf(error_cause, 512, "Unknown request (%s)", request_text);
2518
                        goto error;
2519
                }
2520

    
2521
                /* Prepare JSON event */
2522
                json_t *event = json_object();
2523
                json_object_set_new(event, "sip", json_string("event"));
2524
                if(result != NULL)
2525
                        json_object_set_new(event, "result", result);
2526
                int ret = gateway->push_event(msg->handle, &janus_sip_plugin, msg->transaction, event, NULL);
2527
                JANUS_LOG(LOG_VERB, "  >> Pushing event: %d (%s)\n", ret, janus_get_api_error(ret));
2528
                json_decref(event);
2529
                janus_sip_message_free(msg);
2530
                continue;
2531

    
2532
error:
2533
                {
2534
                        /* Prepare JSON error event */
2535
                        json_t *event = json_object();
2536
                        json_object_set_new(event, "sip", json_string("event"));
2537
                        json_object_set_new(event, "error_code", json_integer(error_code));
2538
                        json_object_set_new(event, "error", json_string(error_cause));
2539
                        int ret = gateway->push_event(msg->handle, &janus_sip_plugin, msg->transaction, event, NULL);
2540
                        JANUS_LOG(LOG_VERB, "  >> Pushing event: %d (%s)\n", ret, janus_get_api_error(ret));
2541
                        json_decref(event);
2542
                        janus_sip_message_free(msg);
2543
                }
2544
        }
2545
        JANUS_LOG(LOG_VERB, "Leaving SIP handler thread\n");
2546
        return NULL;
2547
}
2548

    
2549

    
2550
/* Sofia callbacks */
2551
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[])
2552
{
2553
        janus_sip_session *session = (janus_sip_session *)magic;
2554
        ssip_t *ssip = session->stack;
2555

    
2556
        /* Notify event handlers about the content of the whole incoming SIP message, if any */
2557
        if(gateway->events_is_enabled() && ssip) {
2558
                /* Print the incoming message */
2559
                size_t msg_size = 0;
2560
                msg_t* msg = nua_current_request(nua);
2561
                if(msg) {
2562
                        char *msg_str = msg_as_string(ssip->s_home, msg, NULL, 0, &msg_size);
2563
                        json_t *info = json_object();
2564
                        json_object_set_new(info, "event", json_string("sip-in"));
2565
                        json_object_set_new(info, "sip", json_string(msg_str));
2566
                        gateway->notify_event(&janus_sip_plugin, session->handle, info);
2567
                }
2568
        }
2569

    
2570
        switch (event) {
2571
        /* Status or Error Indications */
2572
                case nua_i_active:
2573
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2574
                        break;
2575
                case nua_i_error:
2576
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2577
                        break;
2578
                case nua_i_fork:
2579
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2580
                        break;
2581
                case nua_i_media_error:
2582
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2583
                        break;
2584
                case nua_i_subscription:
2585
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2586
                        break;
2587
                case nua_i_state:
2588
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2589
                        tagi_t const *ti = tl_find(tags, nutag_callstate);
2590
                        enum nua_callstate callstate = ti ? ti->t_value : -1;
2591
                        /* There are several call states, but we care about the terminated state in order to send the 'hangup' event
2592
                         * and the proceeding state in order to send the 'proceeding' event so the client can play a ringback tone for
2593
                         * the user since we don't send early media. (assuming this is the right session, of course).
2594
                         * http://sofia-sip.sourceforge.net/refdocs/nua/nua__tag_8h.html#a516dc237722dc8ca4f4aa3524b2b444b
2595
                         */
2596
                        if (callstate == nua_callstate_proceeding &&
2597
                                    (session->stack->s_nh_i == nh || session->stack->s_nh_i == NULL)) {
2598
                                json_t *call = json_object();
2599
                                json_object_set_new(call, "sip", json_string("event"));
2600
                                json_t *calling = json_object();
2601
                                json_object_set_new(calling, "event", json_string("proceeding"));
2602
                                json_object_set_new(calling, "code", json_integer(status));
2603
                                json_object_set_new(call, "result", calling);
2604
                                int ret = gateway->push_event(session->handle, &janus_sip_plugin, session->transaction, call, NULL);
2605
                                JANUS_LOG(LOG_VERB, "  >> Pushing event: %d (%s)\n", ret, janus_get_api_error(ret));
2606
                                json_decref(call);
2607
                                /* Also notify event handlers */
2608
                                if(notify_events && gateway->events_is_enabled()) {
2609
                                        json_t *info = json_object();
2610
                                        json_object_set_new(info, "event", json_string("proceeding"));
2611
                                        if(session->callid)
2612
                                                json_object_set_new(info, "call-id", json_string(session->callid));
2613
                                        json_object_set_new(info, "code", json_integer(status));
2614
                                        gateway->notify_event(&janus_sip_plugin, session->handle, info);
2615
                                }
2616
                        } else if(callstate == nua_callstate_terminated &&
2617
                                        (session->stack->s_nh_i == nh || session->stack->s_nh_i == NULL)) {
2618
                                session->media.ready = FALSE;
2619
                                session->media.on_hold = FALSE;
2620
                                session->status = janus_sip_call_status_idle;
2621
                                session->stack->s_nh_i = NULL;
2622
                                json_t *call = json_object();
2623
                                json_object_set_new(call, "sip", json_string("event"));
2624
                                json_t *calling = json_object();
2625
                                json_object_set_new(calling, "event", json_string("hangup"));
2626
                                json_object_set_new(calling, "code", json_integer(status));
2627
                                json_object_set_new(calling, "reason", json_string(phrase ? phrase : ""));
2628
                                json_object_set_new(call, "result", calling);
2629
                                int ret = gateway->push_event(session->handle, &janus_sip_plugin, session->transaction, call, NULL);
2630
                                JANUS_LOG(LOG_VERB, "  >> Pushing event: %d (%s)\n", ret, janus_get_api_error(ret));
2631
                                json_decref(call);
2632
                                /* Also notify event handlers */
2633
                                if(notify_events && gateway->events_is_enabled()) {
2634
                                        json_t *info = json_object();
2635
                                        json_object_set_new(info, "event", json_string("hangup"));
2636
                                        if(session->callid)
2637
                                                json_object_set_new(info, "call-id", json_string(session->callid));
2638
                                        json_object_set_new(info, "code", json_integer(status));
2639
                                        if(phrase)
2640
                                                json_object_set_new(info, "reason", json_string(phrase));
2641
                                        gateway->notify_event(&janus_sip_plugin, session->handle, info);
2642
                                }
2643
                                /* Get rid of any PeerConnection that may have been set up */
2644
                                if(session->callid)
2645
                                        g_hash_table_remove(callids, session->callid);
2646
                                g_free(session->callid);
2647
                                session->callid = NULL;
2648
                                g_free(session->transaction);
2649
                                session->transaction = NULL;
2650
                                gateway->close_pc(session->handle);
2651
                        }
2652
                        break;
2653
                case nua_i_terminated:
2654
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2655
                        break;
2656
        /* SIP requests */
2657
                case nua_i_ack: {
2658
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2659
                        /* We're only interested in this when there's been an offerless INVITE, as here's where we'd get our answer */
2660
                        if(sip->sip_payload && sip->sip_payload->pl_data) {
2661
                                JANUS_LOG(LOG_VERB, "This ACK contains a payload, probably as a result of an offerless INVITE: simulating 200 OK...\n");
2662
                                janus_sip_sofia_callback(nua_r_invite, 700, "ACK", nua, magic, nh, hmagic, sip, tags);
2663
                        }
2664
                        break;
2665
                }
2666
                case nua_i_outbound:
2667
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2668
                        break;
2669
                case nua_i_bye: {
2670
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2671
                        break;
2672
                }
2673
                case nua_i_cancel: {
2674
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2675
                        break;
2676
                }
2677
                case nua_i_invite: {
2678
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2679
                        if(ssip == NULL) {
2680
                                JANUS_LOG(LOG_ERR, "\tInvalid SIP stack\n");
2681
                                nua_respond(nh, 500, sip_status_phrase(500), TAG_END());
2682
                                break;
2683
                        }
2684
                        gboolean reinvite = FALSE;
2685
                        if(session->stack->s_nh_i != NULL) {
2686
                                if(session->stack->s_nh_i == nh) {
2687
                                        /* re-INVITE, we'll check what changed later */
2688
                                        reinvite = TRUE;
2689
                                        JANUS_LOG(LOG_VERB, "Got a re-INVITE...\n");
2690
                                } else if(session->status >= janus_sip_call_status_inviting) {
2691
                                        /* Busy with another call */
2692
                                        JANUS_LOG(LOG_VERB, "\tAlready in a call (busy, status=%s)\n", janus_sip_call_status_string(session->status));
2693
                                        nua_respond(nh, 486, sip_status_phrase(486), TAG_END());
2694
                                        /* Notify the web app about the missed invite */
2695
                                        json_t *missed = json_object();
2696
                                        json_object_set_new(missed, "sip", json_string("event"));
2697
                                        json_t *result = json_object();
2698
                                        json_object_set_new(result, "event", json_string("missed_call"));
2699
                                        char *caller_text = url_as_string(session->stack->s_home, sip->sip_from->a_url);
2700
                                        json_object_set_new(result, "caller", json_string(caller_text));
2701
                                        su_free(session->stack->s_home, caller_text);
2702
                                        if (sip->sip_from && sip->sip_from->a_display) {
2703
                                                json_object_set_new(result, "displayname", json_string(sip->sip_from->a_display));
2704
                                        }
2705
                                        json_object_set_new(missed, "result", result);
2706
                                        int ret = gateway->push_event(session->handle, &janus_sip_plugin, session->transaction, missed, NULL);
2707
                                        JANUS_LOG(LOG_VERB, "  >> Pushing event to peer: %d (%s)\n", ret, janus_get_api_error(ret));
2708
                                        json_decref(missed);
2709
                                        /* Also notify event handlers */
2710
                                        if(notify_events && gateway->events_is_enabled()) {
2711
                                                json_t *info = json_object();
2712
                                                json_object_set_new(info, "event", json_string("missed_call"));
2713
                                                json_object_set_new(info, "caller", json_string(caller_text));
2714
                                                gateway->notify_event(&janus_sip_plugin, session->handle, info);
2715
                                        }
2716
                                        break;
2717
                                }
2718
                        }
2719
                        /* Check if there's an SDP to process */
2720
                        janus_sdp *sdp = NULL;
2721
                        if(!sip->sip_payload) {
2722
                                JANUS_LOG(LOG_VERB,"Received offerless %s\n", reinvite ? "re-INVITE" : "INVITE");
2723
                        } else {
2724
                                char sdperror[100];
2725
                                sdp = janus_sdp_parse(sip->sip_payload->pl_data, sdperror, sizeof(sdperror));
2726
                                if(!sdp) {
2727
                                        JANUS_LOG(LOG_ERR, "\tError parsing SDP! %s\n", sdperror);
2728
                                        nua_respond(nh, 488, sip_status_phrase(488), TAG_END());
2729
                                        break;
2730
                                }
2731
                        }
2732
                        if(!reinvite) {
2733
                                /* New incoming call */
2734
                                session->callee = g_strdup(url_as_string(session->stack->s_home, sip->sip_from->a_url));
2735
                                session->callid = sip && sip->sip_call_id ? g_strdup(sip->sip_call_id->i_id) : NULL;
2736
                                if(session->callid)
2737
                                        g_hash_table_insert(callids, session->callid, session);
2738
                                session->status = janus_sip_call_status_invited;
2739
                                /* Clean up SRTP stuff from before first, in case it's still needed */
2740
                                janus_sip_srtp_cleanup(session);
2741
                        }
2742
                        /* Parse SDP */
2743
                        JANUS_LOG(LOG_VERB, "Someone is %s a call:\n%s",
2744
                                reinvite ? "updating" : "inviting us in",
2745
                                sip->sip_payload->pl_data);
2746
                        gboolean changed = FALSE;
2747
                        if(sdp) {
2748
                                janus_sip_sdp_process(session, sdp, FALSE, reinvite, &changed);
2749
                                /* Check if offer has neither audio nor video, fail with 488 */
2750
                                if(!session->media.has_audio && !session->media.has_video) {
2751
                                        nua_respond(nh, 488, sip_status_phrase(488), TAG_END());
2752
                                        janus_sdp_free(sdp);
2753
                                        break;
2754
                                }
2755
                                /* Also fail with 488 if there's no remote IP address that can be used for RTP */
2756
                                if(!session->media.remote_ip) {
2757
                                        nua_respond(nh, 488, sip_status_phrase(488), TAG_END());
2758
                                        janus_sdp_free(sdp);
2759
                                        break;
2760
                                }
2761
                        }
2762
                        if(reinvite) {
2763
                                /* No need to involve the browser: we reply ourselves */
2764
                                nua_respond(nh, 200, sip_status_phrase(200), TAG_END());
2765
                                janus_sdp_free(sdp);
2766
                                break;
2767
                        }
2768
                        /* Notify the browser about the call */
2769
                        json_t *jsep = NULL;
2770
                        if(sdp)
2771
                                jsep = json_pack("{ssss}", "type", "offer", "sdp", sip->sip_payload->pl_data);
2772
                        json_t *call = json_object();
2773
                        json_object_set_new(call, "sip", json_string("event"));
2774
                        json_t *calling = json_object();
2775
                        json_object_set_new(calling, "event", json_string("incomingcall"));
2776
                        json_object_set_new(calling, "username", json_string(session->callee));
2777
                        if(sip->sip_from && sip->sip_from->a_display) {
2778
                                json_object_set_new(calling, "displayname", json_string(sip->sip_from->a_display));
2779
                        }
2780
                        if(sdp && session->media.has_srtp_remote) {
2781
                                /* FIXME Maybe a true/false instead? */
2782
                                json_object_set_new(calling, "srtp", json_string(session->media.require_srtp ? "sdes_mandatory" : "sdes_optional"));
2783
                        }
2784
                        json_object_set_new(call, "result", calling);
2785
                        int ret = gateway->push_event(session->handle, &janus_sip_plugin, session->transaction, call, jsep);
2786
                        JANUS_LOG(LOG_VERB, "  >> Pushing event to peer: %d (%s)\n", ret, janus_get_api_error(ret));
2787
                        json_decref(call);
2788
                        if(jsep)
2789
                                json_decref(jsep);
2790
                        janus_sdp_free(sdp);
2791
                        /* Also notify event handlers */
2792
                        if(notify_events && gateway->events_is_enabled()) {
2793
                                json_t *info = json_object();
2794
                                json_object_set_new(info, "event", json_string("incomingcall"));
2795
                                if(session->callid)
2796
                                        json_object_set_new(info, "call-id", json_string(session->callid));
2797
                                json_object_set_new(info, "username", json_string(session->callee));
2798
                                if(sip->sip_from && sip->sip_from->a_display)
2799
                                        json_object_set_new(info, "displayname", json_string(sip->sip_from->a_display));
2800
                                gateway->notify_event(&janus_sip_plugin, session->handle, info);
2801
                        }
2802
                        /* Send a Ringing back */
2803
                        nua_respond(nh, 180, sip_status_phrase(180), TAG_END());
2804
                        session->stack->s_nh_i = nh;
2805
                        break;
2806
                }
2807
                case nua_i_info: {
2808
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2809
                        /* We expect a payload */
2810
                        if(!sip->sip_content_type || !sip->sip_content_type->c_type || !sip->sip_payload || !sip->sip_payload->pl_data) {
2811
                                nua_respond(nh, 488, sip_status_phrase(488), TAG_END());
2812
                                return;
2813
                        }
2814
                        const char *type = sip->sip_content_type->c_type;
2815
                        char *payload = sip->sip_payload->pl_data;
2816
                        /* Notify the application */
2817
                        json_t *info = json_object();
2818
                        json_object_set_new(info, "sip", json_string("event"));
2819
                        json_t *result = json_object();
2820
                        json_object_set_new(result, "event", json_string("info"));
2821
                        char *caller_text = url_as_string(session->stack->s_home, sip->sip_from->a_url);
2822
                        json_object_set_new(result, "sender", json_string(caller_text));
2823
                        su_free(session->stack->s_home, caller_text);
2824
                        if(sip->sip_from && sip->sip_from->a_display && strlen(sip->sip_from->a_display) > 0) {
2825
                                json_object_set_new(result, "displayname", json_string(sip->sip_from->a_display));
2826
                        }
2827
                        json_object_set_new(result, "type", json_string(type));
2828
                        json_object_set_new(result, "content", json_string(payload));
2829
                        json_object_set_new(info, "result", result);
2830
                        int ret = gateway->push_event(session->handle, &janus_sip_plugin, session->transaction, info, NULL);
2831
                        JANUS_LOG(LOG_VERB, "  >> Pushing event to peer: %d (%s)\n", ret, janus_get_api_error(ret));
2832
                        json_decref(info);
2833
                        /* Send a 200 back */
2834
                        nua_respond(nh, 200, sip_status_phrase(200), TAG_END());
2835
                        break;
2836
                }
2837
                case nua_i_message: {
2838
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2839
                        /* We expect a payload */
2840
                        if(!sip->sip_payload || !sip->sip_payload->pl_data) {
2841
                                nua_respond(nh, 488, sip_status_phrase(488), TAG_END());
2842
                                return;
2843
                        }
2844
                        char *payload = sip->sip_payload->pl_data;
2845
                        /* Notify the application */
2846
                        json_t *message = json_object();
2847
                        json_object_set_new(message, "sip", json_string("event"));
2848
                        json_t *result = json_object();
2849
                        json_object_set_new(result, "event", json_string("message"));
2850
                        char *caller_text = url_as_string(session->stack->s_home, sip->sip_from->a_url);
2851
                        json_object_set_new(result, "sender", json_string(caller_text));
2852
                        su_free(session->stack->s_home, caller_text);
2853
                        if(sip->sip_from && sip->sip_from->a_display && strlen(sip->sip_from->a_display) > 0) {
2854
                                json_object_set_new(result, "displayname", json_string(sip->sip_from->a_display));
2855
                        }
2856
                        json_object_set_new(result, "content", json_string(payload));
2857
                        json_object_set_new(message, "result", result);
2858
                        int ret = gateway->push_event(session->handle, &janus_sip_plugin, session->transaction, message, NULL);
2859
                        JANUS_LOG(LOG_VERB, "  >> Pushing event to peer: %d (%s)\n", ret, janus_get_api_error(ret));
2860
                        json_decref(message);
2861
                        /* Send a 200 back */
2862
                        nua_respond(nh, 200, sip_status_phrase(200), TAG_END());
2863
                        break;
2864
                }
2865
                case nua_i_options:
2866
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2867
                        /* FIXME Should we handle this message? for now we reply with a 405 Method Not Implemented */
2868
                        nua_respond(nh, 405, sip_status_phrase(405), TAG_END());
2869
                        break;
2870
        /* Responses */
2871
                case nua_r_get_params:
2872
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2873
                        break;
2874
                case nua_r_set_params:
2875
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2876
                        break;
2877
                case nua_r_notifier:
2878
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2879
                        break;
2880
                case nua_r_shutdown:
2881
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2882
                        if(status < 200 && !g_atomic_int_get(&stopping)) {
2883
                                /* shutdown in progress -> return */
2884
                                break;
2885
                        }
2886
                        if(ssip != NULL) {
2887
                                /* end the event loop. su_root_run() will return */
2888
                                su_root_break(ssip->s_root);
2889
                        }
2890
                        break;
2891
                case nua_r_terminate:
2892
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2893
                        break;
2894
        /* SIP responses */
2895
                case nua_r_bye:
2896
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2897
                        break;
2898
                case nua_r_cancel:
2899
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2900
                        break;
2901
                case nua_r_info:
2902
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2903
                        /* FIXME Should we notify the user, in case the SIP INFO returned an error? */
2904
                        break;
2905
                case nua_r_message:
2906
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2907
                        /* FIXME Should we notify the user, in case the SIP MESSAGE returned an error? */
2908
                        break;
2909
                case nua_r_invite: {
2910
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2911

    
2912
                        if(status < 200) {
2913
                                /* Not ready yet (FIXME May this be pranswer?? we don't handle it yet...) */
2914
                                break;
2915
                        } else if(status == 401 || status == 407) {
2916
                                char auth[256];
2917
                                const char* scheme;
2918
                                const char* realm;
2919
                                if(status == 401) {
2920
                                         /* Get scheme/realm from 401 error */
2921
                                        sip_www_authenticate_t const* www_auth = sip->sip_www_authenticate;
2922
                                        scheme = www_auth->au_scheme;
2923
                                        realm = msg_params_find(www_auth->au_params, "realm=");
2924
                                } else {
2925
                                         /* Get scheme/realm from 407 error, proxy-auth */
2926
                                        sip_proxy_authenticate_t const* proxy_auth = sip->sip_proxy_authenticate;
2927
                                        scheme = proxy_auth->au_scheme;
2928
                                        realm = msg_params_find(proxy_auth->au_params, "realm=");
2929
                                }
2930
                                memset(auth, 0, sizeof(auth));
2931
                                g_snprintf(auth, sizeof(auth), "%s%s:%s:%s:%s%s",
2932
                                        session->account.secret_type == janus_sip_secret_type_hashed ? "HA1+" : "",
2933
                                        scheme,
2934
                                        realm,
2935
                                        session->account.authuser ? session->account.authuser : "null",
2936
                                        session->account.secret_type == janus_sip_secret_type_hashed ? "HA1+" : "",
2937
                                        session->account.secret ? session->account.secret : "null");
2938
                                JANUS_LOG(LOG_VERB, "\t%s\n", auth);
2939
                                /* Authenticate */
2940
                                nua_authenticate(nh,
2941
                                        NUTAG_AUTH(auth),
2942
                                        TAG_END());
2943
                                break;
2944
                        } else if(status == 700) {
2945
                                JANUS_LOG(LOG_VERB, "Handling SDP answer in ACK\n");
2946
                        } else if(status >= 400 && status != 700) {
2947
                                break;
2948
                        }
2949
                        if(ssip == NULL) {
2950
                                JANUS_LOG(LOG_ERR, "\tInvalid SIP stack\n");
2951
                                nua_respond(nh, 500, sip_status_phrase(500), TAG_END());
2952
                                break;
2953
                        }
2954
                        char sdperror[100];
2955
                        janus_sdp *sdp = janus_sdp_parse(sip->sip_payload->pl_data, sdperror, sizeof(sdperror));
2956
                        if(!sdp) {
2957
                                JANUS_LOG(LOG_ERR, "\tError parsing SDP! %s\n", sdperror);
2958
                                nua_respond(nh, 488, sip_status_phrase(488), TAG_END());
2959
                                break;
2960
                        }
2961
                        /* Send an ACK, if needed */
2962
                        if(!session->media.autoack) {
2963
                                char *route = sip->sip_record_route ? url_as_string(session->stack->s_home, sip->sip_record_route->r_url) : NULL;
2964
                                JANUS_LOG(LOG_INFO, "Sending ACK (route=%s)\n", route ? route : "none");
2965
                                nua_ack(nh,
2966
                                        TAG_IF(route, NTATAG_DEFAULT_PROXY(route)),
2967
                                        TAG_END());
2968
                        }
2969
                        /* Parse SDP */
2970
                        JANUS_LOG(LOG_VERB, "Peer accepted our call:\n%s", sip->sip_payload->pl_data);
2971
                        session->status = janus_sip_call_status_incall;
2972
                        char *fixed_sdp = sip->sip_payload->pl_data;
2973
                        gboolean changed = FALSE;
2974
                        gboolean update = session->media.ready;
2975
                        janus_sip_sdp_process(session, sdp, TRUE, update, &changed);
2976
                        /* If we asked for SRTP and are not getting it, fail */
2977
                        if(session->media.require_srtp && !session->media.has_srtp_remote) {
2978
                                JANUS_LOG(LOG_ERR, "\tWe asked for mandatory SRTP but didn't get any in the reply!\n");
2979
                                janus_sdp_free(sdp);
2980
                                /* Hangup immediately */
2981
                                session->media.ready = FALSE;
2982
                                session->media.on_hold = FALSE;
2983
                                session->status = janus_sip_call_status_closing;
2984
                                nua_bye(nh, TAG_END());
2985
                                g_free(session->callee);
2986
                                session->callee = NULL;
2987
                                break;
2988
                        }
2989
                        if(!session->media.remote_ip) {
2990
                                /* No remote address parsed? Give up */
2991
                                JANUS_LOG(LOG_ERR, "\tNo remote IP address found for RTP, something's wrong with the SDP!\n");
2992
                                janus_sdp_free(sdp);
2993
                                /* Hangup immediately */
2994
                                session->media.ready = FALSE;
2995
                                session->media.on_hold = FALSE;
2996
                                session->status = janus_sip_call_status_closing;
2997
                                nua_bye(nh, TAG_END());
2998
                                g_free(session->callee);
2999
                                session->callee = NULL;
3000
                                break;
3001
                        }
3002
                        if(session->media.audio_pt > -1) {
3003
                                session->media.audio_pt_name = janus_get_codec_from_pt(fixed_sdp, session->media.audio_pt);
3004
                                JANUS_LOG(LOG_VERB, "Detected audio codec: %d (%s)\n", session->media.audio_pt, session->media.audio_pt_name);
3005
                        }
3006
                        if(session->media.video_pt > -1) {
3007
                                session->media.video_pt_name = janus_get_codec_from_pt(fixed_sdp, session->media.video_pt);
3008
                                JANUS_LOG(LOG_VERB, "Detected video codec: %d (%s)\n", session->media.video_pt, session->media.video_pt_name);
3009
                        }
3010
                        session->media.ready = TRUE;        /* FIXME Maybe we need a better way to signal this */
3011
                        if(update) {
3012
                                /* Don't push to the browser if this is in response to a hold/unhold we sent ourselves */
3013
                                JANUS_LOG(LOG_VERB, "This is an update to an existing call (possibly in response to hold/unhold)\n");
3014
                                break;
3015
                        }
3016
                        GError *error = NULL;
3017
                        char tname[16];
3018
                        g_snprintf(tname, sizeof(tname), "siprtp %s", session->account.username);
3019
                        g_thread_try_new(tname, janus_sip_relay_thread, session, &error);
3020
                        if(error != NULL) {
3021
                                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the RTP/RTCP thread...\n", error->code, error->message ? error->message : "??");
3022
                        }
3023
                        /* Send SDP to the browser */
3024
                        json_t *jsep = json_pack("{ssss}", "type", "answer", "sdp", fixed_sdp);
3025
                        json_t *call = json_object();
3026
                        json_object_set_new(call, "sip", json_string("event"));
3027
                        json_t *calling = json_object();
3028
                        json_object_set_new(calling, "event", json_string("accepted"));
3029
                        json_object_set_new(calling, "username", json_string(session->callee));
3030
                        json_object_set_new(call, "result", calling);
3031
                        int ret = gateway->push_event(session->handle, &janus_sip_plugin, session->transaction, call, jsep);
3032
                        JANUS_LOG(LOG_VERB, "  >> Pushing event to peer: %d (%s)\n", ret, janus_get_api_error(ret));
3033
                        json_decref(call);
3034
                        json_decref(jsep);
3035
                        janus_sdp_free(sdp);
3036
                        /* Also notify event handlers */
3037
                        if(notify_events && gateway->events_is_enabled()) {
3038
                                json_t *info = json_object();
3039
                                json_object_set_new(info, "event", json_string("accepted"));
3040
                                if(session->callid)
3041
                                        json_object_set_new(info, "call-id", json_string(session->callid));
3042
                                json_object_set_new(info, "username", json_string(session->callee));
3043
                                gateway->notify_event(&janus_sip_plugin, session->handle, info);
3044
                        }
3045
                        break;
3046
                }
3047
                case nua_r_register:
3048
                case nua_r_unregister: {
3049
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
3050
                        if(status == 200) {
3051
                                if(event == nua_r_register) {
3052
                                        if(session->account.registration_status < janus_sip_registration_status_registered)
3053
                                                session->account.registration_status = janus_sip_registration_status_registered;
3054
                                } else {
3055
                                        session->account.registration_status = janus_sip_registration_status_unregistered;
3056
                                }
3057
                                const char *event_name = (event == nua_r_register ? "registered" : "unregistered");
3058
                                JANUS_LOG(LOG_VERB, "Successfully %s\n", event_name);
3059
                                /* Notify the browser */
3060
                                json_t *reg = json_object();
3061
                                json_object_set_new(reg, "sip", json_string("event"));
3062
                                json_t *reging = json_object();
3063
                                json_object_set_new(reging, "event", json_string(event_name));
3064
                                json_object_set_new(reging, "username", json_string(session->account.username));
3065
                                if(event == nua_r_register)
3066
                                        json_object_set_new(reging, "register_sent", json_true());
3067
                                json_object_set_new(reg, "result", reging);
3068
                                int ret = gateway->push_event(session->handle, &janus_sip_plugin, session->transaction, reg, NULL);
3069
                                JANUS_LOG(LOG_VERB, "  >> Pushing event to peer: %d (%s)\n", ret, janus_get_api_error(ret));
3070
                                json_decref(reg);
3071
                                /* Also notify event handlers */
3072
                                if(notify_events && gateway->events_is_enabled()) {
3073
                                        json_t *info = json_object();
3074
                                        json_object_set_new(info, "event", json_string(event_name));
3075
                                        json_object_set_new(info, "identity", json_string(session->account.identity));
3076
                                        if(session->account.proxy)
3077
                                                json_object_set_new(info, "proxy", json_string(session->account.proxy));
3078
                                        gateway->notify_event(&janus_sip_plugin, session->handle, info);
3079
                                }
3080
                        } else if(status == 401) {
3081
                                /* Get scheme/realm from 401 error */
3082
                                sip_www_authenticate_t const* www_auth = sip->sip_www_authenticate;
3083
                                char const* scheme = www_auth->au_scheme;
3084
                                const char* realm = msg_params_find(www_auth->au_params, "realm=");
3085
                                char auth[256];
3086
                                memset(auth, 0, sizeof(auth));
3087
                                g_snprintf(auth, sizeof(auth), "%s%s:%s:%s:%s%s",
3088
                                        session->account.secret_type == janus_sip_secret_type_hashed ? "HA1+" : "",
3089
                                        scheme,
3090
                                        realm,
3091
                                        session->account.authuser ? session->account.authuser : "null",
3092
                                        session->account.secret_type == janus_sip_secret_type_hashed ? "HA1+" : "",
3093
                                        session->account.secret);
3094
                                JANUS_LOG(LOG_VERB, "\t%s\n", auth);
3095
                                /* Authenticate */
3096
                                nua_authenticate(nh,
3097
                                        NUTAG_AUTH(auth),
3098
                                        TAG_END());
3099
                        } else if(status >= 400) {
3100
                                /* Authentication failed? */
3101
                                session->account.registration_status = janus_sip_registration_status_failed;
3102
                                /* Tell the browser... */
3103
                                json_t *event = json_object();
3104
                                json_object_set_new(event, "sip", json_string("event"));
3105
                                json_t *result = json_object();
3106
                                json_object_set_new(result, "event", json_string("registration_failed"));
3107
                                json_object_set_new(result, "code", json_integer(status));
3108
                                json_object_set_new(result, "reason", json_string(phrase ? phrase : ""));
3109
                                json_object_set_new(event, "result", result);
3110
                                int ret = gateway->push_event(session->handle, &janus_sip_plugin, session->transaction, event, NULL);
3111
                                JANUS_LOG(LOG_VERB, "  >> Pushing event to peer: %d (%s)\n", ret, janus_get_api_error(ret));
3112
                                json_decref(event);
3113
                                /* Also notify event handlers */
3114
                                if(notify_events && gateway->events_is_enabled()) {
3115
                                        json_t *info = json_object();
3116
                                        json_object_set_new(info, "event", json_string("registration_failed"));
3117
                                        json_object_set_new(info, "code", json_integer(status));
3118
                                        if(phrase)
3119
                                                json_object_set_new(info, "reason", json_string(phrase ? phrase : ""));
3120
                                        gateway->notify_event(&janus_sip_plugin, session->handle, info);
3121
                                }
3122
                        }
3123
                        break;
3124
                }
3125
                default:
3126
                        /* unknown event -> print out error message */
3127
                        JANUS_LOG(LOG_ERR, "Unknown event %d (%s)\n", event, nua_event_name(event));
3128
                        break;
3129
        }
3130
}
3131

    
3132
void janus_sip_sdp_process(janus_sip_session *session, janus_sdp *sdp, gboolean answer, gboolean update, gboolean *changed) {
3133
        if(!session || !sdp)
3134
                return;
3135
        /* c= */
3136
        if(sdp->c_addr) {
3137
                if(update && strcmp(sdp->c_addr, session->media.remote_ip)) {
3138
                        /* This is an update and an address changed */
3139
                        if(changed)
3140
                                *changed = TRUE;
3141
                }
3142
                g_free(session->media.remote_ip);
3143
                session->media.remote_ip = g_strdup(sdp->c_addr);
3144
        }
3145
        GList *temp = sdp->m_lines;
3146
        while(temp) {
3147
                janus_sdp_mline *m = (janus_sdp_mline *)temp->data;
3148
                session->media.require_srtp = session->media.require_srtp || (m->proto && !strcasecmp(m->proto, "RTP/SAVP"));
3149
                if(m->type == JANUS_SDP_AUDIO) {
3150
                        if(m->port) {
3151
                                if(m->port != session->media.remote_audio_rtp_port) {
3152
                                        /* This is an update and an address changed */
3153
                                        if(changed)
3154
                                                *changed = TRUE;
3155
                                }
3156
                                session->media.has_audio = TRUE;
3157
                                session->media.remote_audio_rtp_port = m->port;
3158
                                session->media.remote_audio_rtcp_port = m->port+1;        /* FIXME We're assuming RTCP is on the next port */
3159
                                if(m->direction == JANUS_SDP_SENDONLY || m->direction == JANUS_SDP_INACTIVE)
3160
                                        session->media.audio_send = FALSE;
3161
                                else
3162
                                        session->media.audio_send = TRUE;
3163
                        } else {
3164
                                session->media.audio_send = FALSE;
3165
                        }
3166
                } else if(m->type == JANUS_SDP_VIDEO) {
3167
                        if(m->port) {
3168
                                if(m->port != session->media.remote_video_rtp_port) {
3169
                                        /* This is an update and an address changed */
3170
                                        if(changed)
3171
                                                *changed = TRUE;
3172
                                }
3173
                                session->media.has_video = TRUE;
3174
                                session->media.remote_video_rtp_port = m->port;
3175
                                session->media.remote_video_rtcp_port = m->port+1;        /* FIXME We're assuming RTCP is on the next port */
3176
                                if(m->direction == JANUS_SDP_SENDONLY || m->direction == JANUS_SDP_INACTIVE)
3177
                                        session->media.video_send = FALSE;
3178
                                else
3179
                                        session->media.video_send = TRUE;
3180
                        } else {
3181
                                session->media.video_send = FALSE;
3182
                        }
3183
                } else {
3184
                        JANUS_LOG(LOG_WARN, "Unsupported media line (not audio/video)\n");
3185
                        temp = temp->next;
3186
                        continue;
3187
                }
3188
                if(m->c_addr) {
3189
                        if(update && strcmp(m->c_addr, session->media.remote_ip)) {
3190
                                /* This is an update and an address changed */
3191
                                if(changed)
3192
                                        *changed = TRUE;
3193
                        }
3194
                        g_free(session->media.remote_ip);
3195
                        session->media.remote_ip = g_strdup(m->c_addr);
3196
                }
3197
                if(update) {
3198
                        /* FIXME This is a session update, we only accept changes in IP/ports */
3199
                        temp = temp->next;
3200
                        continue;
3201
                }
3202
                GList *tempA = m->attributes;
3203
                while(tempA) {
3204
                        janus_sdp_attribute *a = (janus_sdp_attribute *)tempA->data;
3205
                        if(a->name) {
3206
                                if(!strcasecmp(a->name, "crypto")) {
3207
                                        if(m->type == JANUS_SDP_AUDIO || m->type == JANUS_SDP_VIDEO) {
3208
                                                gint32 tag = 0;
3209
                                                int suite;
3210
                                                char crypto[81];
3211
                                                /* FIXME inline can be more complex than that, and we're currently only offering SHA1_80 */
3212
                                                int res = sscanf(a->value, "%"SCNi32" AES_CM_128_HMAC_SHA1_%2d inline:%80s",
3213
                                                        &tag, &suite, crypto);
3214
                                                if(res != 3) {
3215
                                                        JANUS_LOG(LOG_WARN, "Failed to parse crypto line, ignoring... %s\n", a->value);
3216
                                                } else {
3217
                                                        gboolean video = (m->type == JANUS_SDP_VIDEO);
3218
                                                        int current_suite = video ? session->media.video_srtp_suite_in : session->media.audio_srtp_suite_in;
3219
                                                        if(current_suite == 0) {
3220
                                                                if(video)
3221
                                                                        session->media.video_srtp_suite_in = suite;
3222
                                                                else
3223
                                                                        session->media.audio_srtp_suite_in = suite;
3224
                                                                janus_sip_srtp_set_remote(session, video, crypto, suite);
3225
                                                                session->media.has_srtp_remote = TRUE;
3226
                                                        } else {
3227
                                                                JANUS_LOG(LOG_WARN, "We already configured a %s crypto context (AES_CM_128_HMAC_SHA1_%d), skipping additional crypto line\n",
3228
                                                                        video ? "video" : "audio", current_suite);
3229
                                                        }
3230
                                                }
3231
                                        }
3232
                                }
3233
                        }
3234
                        tempA = tempA->next;
3235
                }
3236
                if(answer && (m->type == JANUS_SDP_AUDIO || m->type == JANUS_SDP_VIDEO)) {
3237
                        /* Check which codec was negotiated eventually */
3238
                        int pt = -1;
3239
                        if(m->ptypes)
3240
                                pt = GPOINTER_TO_INT(m->ptypes->data);
3241
                        if(pt > -1) {
3242
                                if(m->type == JANUS_SDP_AUDIO) {
3243
                                        session->media.audio_pt = pt;
3244
                                } else {
3245
                                        session->media.video_pt = pt;
3246
                                }
3247
                        }
3248
                }
3249
                temp = temp->next;
3250
        }
3251
        if(update && changed && *changed) {
3252
                /* Something changed: mark this on the session, so that the thread can update the sockets */
3253
                session->media.updated = TRUE;
3254
                if(session->media.pipefd[1] > 0) {
3255
                        int code = 1;
3256
                        ssize_t res = 0;
3257
                        do {
3258
                                res = write(session->media.pipefd[1], &code, sizeof(int));
3259
                        } while(res == -1 && errno == EINTR);
3260
                }
3261
        }
3262
}
3263

    
3264
char *janus_sip_sdp_manipulate(janus_sip_session *session, janus_sdp *sdp, gboolean answer) {
3265
        if(!session || !session->stack || !sdp)
3266
                return NULL;
3267
        /* Start replacing stuff */
3268
        JANUS_LOG(LOG_VERB, "Setting protocol to %s\n", session->media.require_srtp ? "RTP/SAVP" : "RTP/AVP");
3269
        GList *temp = sdp->m_lines;
3270
        while(temp) {
3271
                janus_sdp_mline *m = (janus_sdp_mline *)temp->data;
3272
                g_free(m->proto);
3273
                m->proto = g_strdup(session->media.require_srtp ? "RTP/SAVP" : "RTP/AVP");
3274
                if(m->type == JANUS_SDP_AUDIO) {
3275
                        m->port = session->media.local_audio_rtp_port;
3276
                        if(session->media.has_srtp_local) {
3277
                                char *crypto = NULL;
3278
                                session->media.audio_srtp_suite_out = 80;
3279
                                janus_sip_srtp_set_local(session, FALSE, &crypto);
3280
                                /* FIXME 32? 80? Both? */
3281
                                janus_sdp_attribute *a = janus_sdp_attribute_create("crypto", "1 AES_CM_128_HMAC_SHA1_80 inline:%s", crypto);
3282
                                g_free(crypto);
3283
                                m->attributes = g_list_append(m->attributes, a);
3284
                        }
3285
                } else if(m->type == JANUS_SDP_VIDEO) {
3286
                        m->port = session->media.local_video_rtp_port;
3287
                        if(session->media.has_srtp_local) {
3288
                                char *crypto = NULL;
3289
                                session->media.audio_srtp_suite_out = 80;
3290
                                janus_sip_srtp_set_local(session, TRUE, &crypto);
3291
                                /* FIXME 32? 80? Both? */
3292
                                janus_sdp_attribute *a = janus_sdp_attribute_create("crypto", "1 AES_CM_128_HMAC_SHA1_80 inline:%s", crypto);
3293
                                g_free(crypto);
3294
                                m->attributes = g_list_append(m->attributes, a);
3295
                        }
3296
                }
3297
                g_free(m->c_addr);
3298
                m->c_addr = g_strdup(local_ip);
3299
                if(answer && (m->type == JANUS_SDP_AUDIO || m->type == JANUS_SDP_VIDEO)) {
3300
                        /* Check which codec was negotiated eventually */
3301
                        int pt = -1;
3302
                        if(m->ptypes)
3303
                                pt = GPOINTER_TO_INT(m->ptypes->data);
3304
                        if(pt > -1) {
3305
                                if(m->type == JANUS_SDP_AUDIO) {
3306
                                        session->media.audio_pt = pt;
3307
                                } else {
3308
                                        session->media.video_pt = pt;
3309
                                }
3310
                        }
3311
                }
3312
                temp = temp->next;
3313
        }
3314
        /* Generate a SDP string out of our changes */
3315
        return janus_sdp_write(sdp);
3316
}
3317

    
3318
/* Bind local RTP/RTCP sockets */
3319
static int janus_sip_allocate_local_ports(janus_sip_session *session) {
3320
        if(session == NULL) {
3321
                JANUS_LOG(LOG_ERR, "Invalid session\n");
3322
                return -1;
3323
        }
3324
        /* Reset status */
3325
        if(session->media.audio_rtp_fd != -1) {
3326
                close(session->media.audio_rtp_fd);
3327
                session->media.audio_rtp_fd = -1;
3328
        }
3329
        if(session->media.audio_rtcp_fd != -1) {
3330
                close(session->media.audio_rtcp_fd);
3331
                session->media.audio_rtcp_fd = -1;
3332
        }
3333
        session->media.local_audio_rtp_port = 0;
3334
        session->media.local_audio_rtcp_port = 0;
3335
        session->media.audio_ssrc = 0;
3336
        if(session->media.video_rtp_fd != -1) {
3337
                close(session->media.video_rtp_fd);
3338
                session->media.video_rtp_fd = -1;
3339
        }
3340
        if(session->media.video_rtcp_fd != -1) {
3341
                close(session->media.video_rtcp_fd);
3342
                session->media.video_rtcp_fd = -1;
3343
        }
3344
        session->media.local_video_rtp_port = 0;
3345
        session->media.local_video_rtcp_port = 0;
3346
        session->media.video_ssrc = 0;
3347
        if(session->media.pipefd[0] > 0) {
3348
                close(session->media.pipefd[0]);
3349
                session->media.pipefd[0] = -1;
3350
        }
3351
        if(session->media.pipefd[1] > 0) {
3352
                close(session->media.pipefd[1]);
3353
                session->media.pipefd[1] = -1;
3354
        }
3355
        /* Start */
3356
        int attempts = 100;        /* FIXME Don't retry forever */
3357
        if(session->media.has_audio) {
3358
                JANUS_LOG(LOG_VERB, "Allocating audio ports:\n");
3359
                struct sockaddr_in audio_rtp_address, audio_rtcp_address;
3360
                while(session->media.local_audio_rtp_port == 0 || session->media.local_audio_rtcp_port == 0) {
3361
                        if(attempts == 0)        /* Too many failures */
3362
                                return -1;
3363
                        if(session->media.audio_rtp_fd == -1) {
3364
                                session->media.audio_rtp_fd = socket(AF_INET, SOCK_DGRAM, 0);
3365
                        }
3366
                        if(session->media.audio_rtcp_fd == -1) {
3367
                                session->media.audio_rtcp_fd = socket(AF_INET, SOCK_DGRAM, 0);
3368
                        }
3369
                        int rtp_port = g_random_int_range(10000, 60000);        /* FIXME Should this be configurable? */
3370
                        if(rtp_port % 2)
3371
                                rtp_port++;        /* Pick an even port for RTP */
3372
                        audio_rtp_address.sin_family = AF_INET;
3373
                        audio_rtp_address.sin_port = htons(rtp_port);
3374
                        inet_pton(AF_INET, local_ip, &audio_rtp_address.sin_addr.s_addr);
3375
                        if(bind(session->media.audio_rtp_fd, (struct sockaddr *)(&audio_rtp_address), sizeof(struct sockaddr)) < 0) {
3376
                                JANUS_LOG(LOG_ERR, "Bind failed for audio RTP (port %d), trying a different one...\n", rtp_port);
3377
                                attempts--;
3378
                                continue;
3379
                        }
3380
                        JANUS_LOG(LOG_VERB, "Audio RTP listener bound to port %d\n", rtp_port);
3381
                        int rtcp_port = rtp_port+1;
3382
                        audio_rtcp_address.sin_family = AF_INET;
3383
                        audio_rtcp_address.sin_port = htons(rtcp_port);
3384
                        inet_pton(AF_INET, local_ip, &audio_rtcp_address.sin_addr.s_addr);
3385
                        if(bind(session->media.audio_rtcp_fd, (struct sockaddr *)(&audio_rtcp_address), sizeof(struct sockaddr)) < 0) {
3386
                                JANUS_LOG(LOG_ERR, "Bind failed for audio RTCP (port %d), trying a different one...\n", rtcp_port);
3387
                                /* RTP socket is not valid anymore, reset it */
3388
                                close(session->media.audio_rtp_fd);
3389
                                session->media.audio_rtp_fd = -1;
3390
                                attempts--;
3391
                                continue;
3392
                        }
3393
                        JANUS_LOG(LOG_VERB, "Audio RTCP listener bound to port %d\n", rtcp_port);
3394
                        session->media.local_audio_rtp_port = rtp_port;
3395
                        session->media.local_audio_rtcp_port = rtcp_port;
3396
                }
3397
        }
3398
        if(session->media.has_video) {
3399
                JANUS_LOG(LOG_VERB, "Allocating video ports:\n");
3400
                struct sockaddr_in video_rtp_address, video_rtcp_address;
3401
                while(session->media.local_video_rtp_port == 0 || session->media.local_video_rtcp_port == 0) {
3402
                        if(attempts == 0)        /* Too many failures */
3403
                                return -1;
3404
                        if(session->media.video_rtp_fd == -1) {
3405
                                session->media.video_rtp_fd = socket(AF_INET, SOCK_DGRAM, 0);
3406
                        }
3407
                        if(session->media.video_rtcp_fd == -1) {
3408
                                session->media.video_rtcp_fd = socket(AF_INET, SOCK_DGRAM, 0);
3409
                        }
3410
                        int rtp_port = g_random_int_range(10000, 60000);        /* FIXME Should this be configurable? */
3411
                        if(rtp_port % 2)
3412
                                rtp_port++;        /* Pick an even port for RTP */
3413
                        video_rtp_address.sin_family = AF_INET;
3414
                        video_rtp_address.sin_port = htons(rtp_port);
3415
                        inet_pton(AF_INET, local_ip, &video_rtp_address.sin_addr.s_addr);
3416
                        if(bind(session->media.video_rtp_fd, (struct sockaddr *)(&video_rtp_address), sizeof(struct sockaddr)) < 0) {
3417
                                JANUS_LOG(LOG_ERR, "Bind failed for video RTP (port %d), trying a different one...\n", rtp_port);
3418
                                attempts--;
3419
                                continue;
3420
                        }
3421
                        JANUS_LOG(LOG_VERB, "Video RTP listener bound to port %d\n", rtp_port);
3422
                        int rtcp_port = rtp_port+1;
3423
                        video_rtcp_address.sin_family = AF_INET;
3424
                        video_rtcp_address.sin_port = htons(rtcp_port);
3425
                        inet_pton(AF_INET, local_ip, &video_rtcp_address.sin_addr.s_addr);
3426
                        if(bind(session->media.video_rtcp_fd, (struct sockaddr *)(&video_rtcp_address), sizeof(struct sockaddr)) < 0) {
3427
                                JANUS_LOG(LOG_ERR, "Bind failed for video RTCP (port %d), trying a different one...\n", rtcp_port);
3428
                                /* RTP socket is not valid anymore, reset it */
3429
                                close(session->media.video_rtp_fd);
3430
                                session->media.video_rtp_fd = -1;
3431
                                attempts--;
3432
                                continue;
3433
                        }
3434
                        JANUS_LOG(LOG_VERB, "Video RTCP listener bound to port %d\n", rtcp_port);
3435
                        session->media.local_video_rtp_port = rtp_port;
3436
                        session->media.local_video_rtcp_port = rtcp_port;
3437
                }
3438
        }
3439
        /* We need this to quickly interrupt the poll when it's time to update a session or wrap up */
3440
        pipe(session->media.pipefd);
3441
        return 0;
3442
}
3443

    
3444
/* Helper method to (re)connect RTP/RTCP sockets */
3445
static void janus_sip_connect_sockets(janus_sip_session *session, struct sockaddr_in *server_addr) {
3446
        if(!session || !server_addr)
3447
                return;
3448

    
3449
        if(session->media.updated) {
3450
                JANUS_LOG(LOG_VERB, "Updating session sockets\n");
3451
        }
3452

    
3453
        /* Connect peers (FIXME This pretty much sucks right now) */
3454
        if(session->media.remote_audio_rtp_port) {
3455
                server_addr->sin_port = htons(session->media.remote_audio_rtp_port);
3456
                if(connect(session->media.audio_rtp_fd, (struct sockaddr *)server_addr, sizeof(struct sockaddr)) == -1) {
3457
                        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);
3458
                        JANUS_LOG(LOG_ERR, "[SIP-%s]   -- %d (%s)\n", session->account.username, errno, strerror(errno));
3459
                }
3460
        }
3461
        if(session->media.remote_audio_rtcp_port) {
3462
                server_addr->sin_port = htons(session->media.remote_audio_rtcp_port);
3463
                if(connect(session->media.audio_rtcp_fd, (struct sockaddr *)server_addr, sizeof(struct sockaddr)) == -1) {
3464
                        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);
3465
                        JANUS_LOG(LOG_ERR, "[SIP-%s]   -- %d (%s)\n", session->account.username, errno, strerror(errno));
3466
                }
3467
        }
3468
        if(session->media.remote_video_rtp_port) {
3469
                server_addr->sin_port = htons(session->media.remote_video_rtp_port);
3470
                if(connect(session->media.video_rtp_fd, (struct sockaddr *)server_addr, sizeof(struct sockaddr)) == -1) {
3471
                        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);
3472
                        JANUS_LOG(LOG_ERR, "[SIP-%s]   -- %d (%s)\n", session->account.username, errno, strerror(errno));
3473
                }
3474
        }
3475
        if(session->media.remote_video_rtcp_port) {
3476
                server_addr->sin_port = htons(session->media.remote_video_rtcp_port);
3477
                if(connect(session->media.video_rtcp_fd, (struct sockaddr *)server_addr, sizeof(struct sockaddr)) == -1) {
3478
                        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);
3479
                        JANUS_LOG(LOG_ERR, "[SIP-%s]   -- %d (%s)\n", session->account.username, errno, strerror(errno));
3480
                }
3481
        }
3482

    
3483
}
3484

    
3485
/* Thread to relay RTP/RTCP frames coming from the SIP peer */
3486
static void *janus_sip_relay_thread(void *data) {
3487
        janus_sip_session *session = (janus_sip_session *)data;
3488
        if(!session || !session->account.username || !session->callee) {
3489
                g_thread_unref(g_thread_self());
3490
                return NULL;
3491
        }
3492
        JANUS_LOG(LOG_VERB, "Starting relay thread (%s <--> %s)\n", session->account.username, session->callee);
3493

    
3494
        gboolean have_server_ip = TRUE;
3495
        struct sockaddr_in server_addr;
3496
        memset(&server_addr, 0, sizeof(server_addr));
3497
        server_addr.sin_family = AF_INET;
3498
        if(inet_aton(session->media.remote_ip, &server_addr.sin_addr) == 0) {        /* Not a numeric IP... */
3499
                struct hostent *host = gethostbyname(session->media.remote_ip);        /* ...resolve name */
3500
                if(!host) {
3501
                        JANUS_LOG(LOG_ERR, "[SIP-%s] Couldn't get host (%s)\n", session->account.username, session->media.remote_ip);
3502
                        have_server_ip = FALSE;
3503
                } else {
3504
                        server_addr.sin_addr = *(struct in_addr *)host->h_addr_list;
3505
                }
3506
        }
3507
        if(have_server_ip)
3508
                janus_sip_connect_sockets(session, &server_addr);
3509

    
3510
        if(!session->callee) {
3511
                JANUS_LOG(LOG_VERB, "[SIP-%s] Leaving thread, no callee...\n", session->account.username);
3512
                g_thread_unref(g_thread_self());
3513
                return NULL;
3514
        }
3515
        /* File descriptors */
3516
        socklen_t addrlen;
3517
        struct sockaddr_in remote;
3518
        int resfd = 0, bytes = 0;
3519
        struct pollfd fds[5];
3520
        int pipe_fd = session->media.pipefd[0];
3521
        char buffer[1500];
3522
        memset(buffer, 0, 1500);
3523
        /* Loop */
3524
        int num = 0;
3525
        gboolean goon = TRUE;
3526
        int astep = 0, vstep = 0;
3527
        guint32 ats = 0, vts = 0;
3528
        while(goon && session != NULL && !session->destroyed &&
3529
                        session->status > janus_sip_call_status_idle &&
3530
                        session->status < janus_sip_call_status_closing) {        /* FIXME We need a per-call watchdog as well */
3531

    
3532
                if(session->media.updated) {
3533
                        /* Apparently there was a session update */
3534
                        if(session->media.remote_ip != NULL && (inet_aton(session->media.remote_ip, &server_addr.sin_addr) != 0)) {
3535
                                janus_sip_connect_sockets(session, &server_addr);
3536
                        } else {
3537
                                JANUS_LOG(LOG_ERR, "[SIP-%p] Couldn't update session details: missing or invalid remote IP address? (%s)\n",
3538
                                        session->account.username, session->media.remote_ip);
3539
                        }
3540
                        session->media.updated = FALSE;
3541
                }
3542

    
3543
                /* Prepare poll */
3544
                num = 0;
3545
                if(session->media.audio_rtp_fd != -1) {
3546
                        fds[num].fd = session->media.audio_rtp_fd;
3547
                        fds[num].events = POLLIN;
3548
                        fds[num].revents = 0;
3549
                        num++;
3550
                }
3551
                if(session->media.audio_rtcp_fd != -1) {
3552
                        fds[num].fd = session->media.audio_rtcp_fd;
3553
                        fds[num].events = POLLIN;
3554
                        fds[num].revents = 0;
3555
                        num++;
3556
                }
3557
                if(session->media.video_rtp_fd != -1) {
3558
                        fds[num].fd = session->media.video_rtp_fd;
3559
                        fds[num].events = POLLIN;
3560
                        fds[num].revents = 0;
3561
                        num++;
3562
                }
3563
                if(session->media.video_rtcp_fd != -1) {
3564
                        fds[num].fd = session->media.video_rtcp_fd;
3565
                        fds[num].events = POLLIN;
3566
                        fds[num].revents = 0;
3567
                        num++;
3568
                }
3569
                if(pipe_fd != -1) {
3570
                        fds[num].fd = pipe_fd;
3571
                        fds[num].events = POLLIN;
3572
                        fds[num].revents = 0;
3573
                        num++;
3574
                }
3575
                /* Wait for some data */
3576
                resfd = poll(fds, num, 1000);
3577
                if(resfd < 0) {
3578
                        JANUS_LOG(LOG_ERR, "[SIP-%s] Error polling...\n", session->account.username);
3579
                        JANUS_LOG(LOG_ERR, "[SIP-%s]   -- %d (%s)\n", session->account.username, errno, strerror(errno));
3580
                        break;
3581
                } else if(resfd == 0) {
3582
                        /* No data, keep going */
3583
                        continue;
3584
                }
3585
                if(session == NULL || session->destroyed ||
3586
                                session->status <= janus_sip_call_status_idle ||
3587
                                session->status >= janus_sip_call_status_closing)
3588
                        break;
3589
                int i = 0;
3590
                for(i=0; i<num; i++) {
3591
                        if(fds[i].revents & (POLLERR | POLLHUP)) {
3592
                                /* If we just updated the session, let's wait until things have calmed down */
3593
                                if(session->media.updated)
3594
                                        break;
3595
                                /* Check the socket error */
3596
                                int error = 0;
3597
                                socklen_t errlen = sizeof(error);
3598
                                getsockopt(fds[i].fd, SOL_SOCKET, SO_ERROR, (void *)&error, &errlen);
3599
                                if(error == 0) {
3600
                                        /* Maybe not a breaking error after all? */
3601
                                        continue;
3602
                                } else if(error == 111) {
3603
                                        /* ICMP error? If it's related to RTCP, let's just close the RTCP socket and move on */
3604
                                        if(fds[i].fd == session->media.audio_rtcp_fd) {
3605
                                                JANUS_LOG(LOG_WARN, "[SIP-%s] Got a '%s' on the audio RTCP socket, closing it\n",
3606
                                                        session->account.username, strerror(error));
3607
                                                close(session->media.audio_rtcp_fd);
3608
                                                session->media.audio_rtcp_fd = -1;
3609
                                        } else if(fds[i].fd == session->media.video_rtcp_fd) {
3610
                                                JANUS_LOG(LOG_WARN, "[SIP-%s] Got a '%s' on the video RTCP socket, closing it\n",
3611
                                                        session->account.username, strerror(error));
3612
                                                close(session->media.video_rtcp_fd);
3613
                                                session->media.video_rtcp_fd = -1;
3614
                                        }
3615
                                        /* FIXME Should we do the same with the RTP sockets as well? We may risk overreacting, there... */
3616
                                        continue;
3617
                                }
3618
                                JANUS_LOG(LOG_ERR, "[SIP-%s] Error polling %d (socket #%d): %s...\n", session->account.username,
3619
                                        fds[i].fd, i, fds[i].revents & POLLERR ? "POLLERR" : "POLLHUP");
3620
                                JANUS_LOG(LOG_ERR, "[SIP-%s]   -- %d (%s)\n", session->account.username, error, strerror(error));
3621
                                goon = FALSE;        /* Can we assume it's pretty much over, after a POLLERR? */
3622
                                /* FIXME Simulate a "hangup" coming from the browser */
3623
                                janus_sip_message *msg = g_malloc0(sizeof(janus_sip_message));
3624
                                msg->handle = session->handle;
3625
                                msg->message = json_pack("{ss}", "request", "hangup");
3626
                                msg->transaction = NULL;
3627
                                msg->jsep = NULL;
3628
                                g_async_queue_push(messages, msg);
3629
                                break;
3630
                        } else if(fds[i].revents & POLLIN) {
3631
                                if(pipe_fd != -1 && fds[i].fd == pipe_fd) {
3632
                                        /* Poll interrupted for a reason, go on */
3633
                                        int code = 0;
3634
                                        bytes = read(pipe_fd, &code, sizeof(int));
3635
                                        break;
3636
                                }
3637
                                /* Got an RTP/RTCP packet */
3638
                                if(session->media.audio_rtp_fd != -1 && fds[i].fd == session->media.audio_rtp_fd) {
3639
                                        /* Got something audio (RTP) */
3640
                                        addrlen = sizeof(remote);
3641
                                        bytes = recvfrom(session->media.audio_rtp_fd, buffer, 1500, 0, (struct sockaddr*)&remote, &addrlen);
3642
                                        rtp_header *header = (rtp_header *)buffer;
3643
                                        if(session->media.audio_ssrc_peer != ntohl(header->ssrc)) {
3644
                                                session->media.audio_ssrc_peer = ntohl(header->ssrc);
3645
                                                JANUS_LOG(LOG_VERB, "Got SIP peer audio SSRC: %"SCNu32"\n", session->media.audio_ssrc_peer);
3646
                                        }
3647
                                        /* Is this SRTP? */
3648
                                        if(session->media.has_srtp_remote) {
3649
                                                int buflen = bytes;
3650
                                                srtp_err_status_t res = srtp_unprotect(session->media.audio_srtp_in, buffer, &buflen);
3651
                                                if(res != srtp_err_status_ok && res != srtp_err_status_replay_fail && res != srtp_err_status_replay_old) {
3652
                                                        guint32 timestamp = ntohl(header->timestamp);
3653
                                                        guint16 seq = ntohs(header->seq_number);
3654
                                                        JANUS_LOG(LOG_ERR, "[SIP-%s] Audio SRTP unprotect error: %s (len=%d-->%d, ts=%"SCNu32", seq=%"SCNu16")\n",
3655
                                                                session->account.username, janus_srtp_error_str(res), bytes, buflen, timestamp, seq);
3656
                                                        continue;
3657
                                                }
3658
                                                bytes = buflen;
3659
                                        }
3660
                                        /* Check if the SSRC changed (e.g., after a re-INVITE or UPDATE) */
3661
                                        guint32 timestamp = ntohl(header->timestamp);
3662
                                        janus_rtp_header_update(header, &session->media.context, FALSE, astep ? astep : 960);
3663
                                        if(ats == 0) {
3664
                                                ats = timestamp;
3665
                                        } else if(astep == 0) {
3666
                                                astep = timestamp-ats;
3667
                                                if(astep < 0)
3668
                                                        astep = 0;
3669
                                        }
3670
                                        /* Save the frame if we're recording */
3671
                                        janus_recorder_save_frame(session->arc_peer, buffer, bytes);
3672
                                        /* Relay to browser */
3673
                                        gateway->relay_rtp(session->handle, 0, buffer, bytes);
3674
                                        continue;
3675
                                } else if(session->media.audio_rtcp_fd != -1 && fds[i].fd == session->media.audio_rtcp_fd) {
3676
                                        /* Got something audio (RTCP) */
3677
                                        addrlen = sizeof(remote);
3678
                                        bytes = recvfrom(session->media.audio_rtcp_fd, buffer, 1500, 0, (struct sockaddr*)&remote, &addrlen);
3679
                                        //~ JANUS_LOG(LOG_VERB, "************************\nGot %d bytes on the audio RTCP channel...\n", bytes);
3680
                                        /* Is this SRTCP? */
3681
                                        if(session->media.has_srtp_remote) {
3682
                                                int buflen = bytes;
3683
                                                srtp_err_status_t res = srtp_unprotect_rtcp(session->media.audio_srtp_in, buffer, &buflen);
3684
                                                if(res != srtp_err_status_ok && res != srtp_err_status_replay_fail && res != srtp_err_status_replay_old) {
3685
                                                        JANUS_LOG(LOG_ERR, "[SIP-%s] Audio SRTCP unprotect error: %s (len=%d-->%d)\n",
3686
                                                                session->account.username, janus_srtp_error_str(res), bytes, buflen);
3687
                                                        continue;
3688
                                                }
3689
                                                bytes = buflen;
3690
                                        }
3691
                                        /* Relay to browser */
3692
                                        gateway->relay_rtcp(session->handle, 0, buffer, bytes);
3693
                                        continue;
3694
                                } else if(session->media.video_rtp_fd != -1 && fds[i].fd == session->media.video_rtp_fd) {
3695
                                        /* Got something video (RTP) */
3696
                                        addrlen = sizeof(remote);
3697
                                        bytes = recvfrom(session->media.video_rtp_fd, buffer, 1500, 0, (struct sockaddr*)&remote, &addrlen);
3698
                                        //~ JANUS_LOG(LOG_VERB, "************************\nGot %d bytes on the video RTP channel...\n", bytes);
3699
                                        //~ rtp_header_t *rtp = (rtp_header_t *)buffer;
3700
                                        //~ JANUS_LOG(LOG_VERB, " ... parsed RTP packet (ssrc=%u, pt=%u, seq=%u, ts=%u)...\n",
3701
                                                //~ ntohl(rtp->ssrc), rtp->type, ntohs(rtp->seq_number), ntohl(rtp->timestamp));
3702
                                        rtp_header *header = (rtp_header *)buffer;
3703
                                        if(session->media.video_ssrc_peer != ntohl(header->ssrc)) {
3704
                                                session->media.video_ssrc_peer = ntohl(header->ssrc);
3705
                                                JANUS_LOG(LOG_VERB, "Got SIP peer video SSRC: %"SCNu32"\n", session->media.video_ssrc_peer);
3706
                                        }
3707
                                        /* Is this SRTP? */
3708
                                        if(session->media.has_srtp_remote) {
3709
                                                int buflen = bytes;
3710
                                                srtp_err_status_t res = srtp_unprotect(session->media.video_srtp_in, buffer, &buflen);
3711
                                                if(res != srtp_err_status_ok && res != srtp_err_status_replay_fail && res != srtp_err_status_replay_old) {
3712
                                                        guint32 timestamp = ntohl(header->timestamp);
3713
                                                        guint16 seq = ntohs(header->seq_number);
3714
                                                        JANUS_LOG(LOG_ERR, "[SIP-%s] Video SRTP unprotect error: %s (len=%d-->%d, ts=%"SCNu32", seq=%"SCNu16")\n",
3715
                                                                session->account.username, janus_srtp_error_str(res), bytes, buflen, timestamp, seq);
3716
                                                        continue;
3717
                                                }
3718
                                                bytes = buflen;
3719
                                        }
3720
                                        /* Check if the SSRC changed (e.g., after a re-INVITE or UPDATE) */
3721
                                        janus_rtp_header_update(header, &session->media.context, TRUE, vstep ? vstep : 4500);
3722
                                        guint32 timestamp = ntohl(header->timestamp);
3723
                                        if(vts == 0) {
3724
                                                vts = timestamp;
3725
                                        } else if(vstep == 0) {
3726
                                                vstep = timestamp-vts;
3727
                                                if(vstep < 0)
3728
                                                        vstep = 0;
3729
                                        }
3730
                                        /* Save the frame if we're recording */
3731
                                        janus_recorder_save_frame(session->vrc_peer, buffer, bytes);
3732
                                        /* Relay to browser */
3733
                                        gateway->relay_rtp(session->handle, 1, buffer, bytes);
3734
                                        continue;
3735
                                } else if(session->media.video_rtcp_fd != -1 && fds[i].fd == session->media.video_rtcp_fd) {
3736
                                        /* Got something video (RTCP) */
3737
                                        addrlen = sizeof(remote);
3738
                                        bytes = recvfrom(session->media.video_rtcp_fd, buffer, 1500, 0, (struct sockaddr*)&remote, &addrlen);
3739
                                        //~ JANUS_LOG(LOG_VERB, "************************\nGot %d bytes on the video RTCP channel...\n", bytes);
3740
                                        /* Is this SRTCP? */
3741
                                        if(session->media.has_srtp_remote) {
3742
                                                int buflen = bytes;
3743
                                                srtp_err_status_t res = srtp_unprotect_rtcp(session->media.video_srtp_in, buffer, &buflen);
3744
                                                if(res != srtp_err_status_ok && res != srtp_err_status_replay_fail && res != srtp_err_status_replay_old) {
3745
                                                        JANUS_LOG(LOG_ERR, "[SIP-%s] Video SRTP unprotect error: %s (len=%d-->%d)\n",
3746
                                                                session->account.username, janus_srtp_error_str(res), bytes, buflen);
3747
                                                        continue;
3748
                                                }
3749
                                                bytes = buflen;
3750
                                        }
3751
                                        /* Relay to browser */
3752
                                        gateway->relay_rtcp(session->handle, 1, buffer, bytes);
3753
                                        continue;
3754
                                }
3755
                        }
3756
                }
3757
        }
3758
        if(session->media.audio_rtp_fd != -1) {
3759
                close(session->media.audio_rtp_fd);
3760
                session->media.audio_rtp_fd = -1;
3761
        }
3762
        if(session->media.audio_rtcp_fd != -1) {
3763
                close(session->media.audio_rtcp_fd);
3764
                session->media.audio_rtcp_fd = -1;
3765
        }
3766
        session->media.local_audio_rtp_port = 0;
3767
        session->media.local_audio_rtcp_port = 0;
3768
        session->media.audio_ssrc = 0;
3769
        if(session->media.video_rtp_fd != -1) {
3770
                close(session->media.video_rtp_fd);
3771
                session->media.video_rtp_fd = -1;
3772
        }
3773
        if(session->media.video_rtcp_fd != -1) {
3774
                close(session->media.video_rtcp_fd);
3775
                session->media.video_rtcp_fd = -1;
3776
        }
3777
        session->media.local_video_rtp_port = 0;
3778
        session->media.local_video_rtcp_port = 0;
3779
        session->media.video_ssrc = 0;
3780
        if(session->media.pipefd[0] > 0) {
3781
                close(session->media.pipefd[0]);
3782
                session->media.pipefd[0] = -1;
3783
        }
3784
        if(session->media.pipefd[1] > 0) {
3785
                close(session->media.pipefd[1]);
3786
                session->media.pipefd[1] = -1;
3787
        }
3788
        /* Clean up SRTP stuff, if needed */
3789
        janus_sip_srtp_cleanup(session);
3790
        /* Done */
3791
        JANUS_LOG(LOG_VERB, "Leaving SIP relay thread\n");
3792
        g_thread_unref(g_thread_self());
3793
        return NULL;
3794
}
3795

    
3796

    
3797
/* Sofia Event thread */
3798
gpointer janus_sip_sofia_thread(gpointer user_data) {
3799
        janus_sip_session *session = (janus_sip_session *)user_data;
3800
        if(session == NULL || session->account.username == NULL) {
3801
                g_thread_unref(g_thread_self());
3802
                return NULL;
3803
        }
3804
        JANUS_LOG(LOG_VERB, "Joining sofia loop thread (%s)...\n", session->account.username);
3805
        session->stack = g_malloc0(sizeof(ssip_t));
3806
        session->stack->session = session;
3807
        session->stack->s_nua = NULL;
3808
        session->stack->s_nh_r = NULL;
3809
        session->stack->s_nh_i = NULL;
3810
        session->stack->s_root = su_root_create(session->stack);
3811
        su_home_init(session->stack->s_home);
3812
        JANUS_LOG(LOG_VERB, "Setting up sofia stack (sip:%s@%s)\n", session->account.username, local_ip);
3813
        char sip_url[128];
3814
        char sips_url[128];
3815
        char *ipv6;
3816
        ipv6 = strstr(local_ip, ":");
3817
        g_snprintf(sip_url, sizeof(sip_url), "sip:%s%s%s:*", ipv6 ? "[" : "", local_ip, ipv6 ? "]" : "");
3818
        g_snprintf(sips_url, sizeof(sips_url), "sips:%s%s%s:*", ipv6 ? "[" : "", local_ip, ipv6 ? "]" : "");
3819
        char outbound_options[256] = "use-rport no-validate";
3820
        if(keepalive_interval > 0)
3821
                g_strlcat(outbound_options, " options-keepalive", sizeof(outbound_options));
3822
        if(!behind_nat)
3823
                g_strlcat(outbound_options, " no-natify", sizeof(outbound_options));
3824
        session->stack->s_nua = nua_create(session->stack->s_root,
3825
                                janus_sip_sofia_callback,
3826
                                session,
3827
                                SIPTAG_ALLOW_STR("INVITE, ACK, BYE, CANCEL, OPTIONS, UPDATE, MESSAGE, INFO"),
3828
                                NUTAG_M_USERNAME(session->account.username),
3829
                                NUTAG_URL(sip_url),
3830
                                TAG_IF(session->account.sips, NUTAG_SIPS_URL(sips_url)),
3831
                                SIPTAG_USER_AGENT_STR(session->account.user_agent ? session->account.user_agent : user_agent),
3832
                                NUTAG_KEEPALIVE(keepalive_interval * 1000),        /* Sofia expects it in milliseconds */
3833
                                NUTAG_OUTBOUND(outbound_options),
3834
                                SIPTAG_SUPPORTED(NULL),
3835
                                TAG_NULL());
3836
        su_root_run(session->stack->s_root);
3837
        /* When we get here, we're done */
3838
        nua_destroy(session->stack->s_nua);
3839
        su_root_destroy(session->stack->s_root);
3840
        session->stack->s_root = NULL;
3841
        su_home_deinit(session->stack->s_home);
3842
        su_home_unref(session->stack->s_home);
3843
        if (session->stack) {
3844
                g_free(session->stack);
3845
                session->stack = NULL;
3846
        }
3847
        //~ stop = 1;
3848
        JANUS_LOG(LOG_VERB, "Leaving sofia loop thread...\n");
3849
        g_thread_unref(g_thread_self());
3850
        /* Cleaning up and removing the session is done in a lazy way */
3851
        janus_mutex_lock(&sessions_mutex);
3852
        old_sessions = g_list_append(old_sessions, session);
3853
        janus_mutex_unlock(&sessions_mutex);
3854
        return NULL;
3855
}