Statistics
| Branch: | Revision:

janus-gateway / plugins / janus_sipre.c @ b2bea585

History | View | Annotate | Download (151 KB)

1
/*! \file   janus_sipre.c
2
 * \author Lorenzo Miniero <lorenzo@meetecho.com>
3
 * \copyright GNU General Public License v3
4
 * \brief  Janus SIPre plugin (libre)
5
 * \details  This is basically a clone of the SIPre plugin, with the key
6
 * difference being that it uses \c libre (http://creytiv.com/re.html)
7
 * instead of Sofia SIP for its internal stack. As such, it provides an
8
 * alternative for those who don't want to, or can't, use the Sofia-based
9
 * SIP plugin. The API it exposes is exactly the same, meaning it should
10
 * be pretty straightforward to switch from one plugin to another on the
11
 * client side. The configuration file looks exactly the same as well.
12
 *
13
 * \section sipapi SIPre Plugin API
14
 *
15
 * All requests you can send in the SIPre Plugin API are asynchronous,
16
 * which means all responses (successes and errors) will be delivered
17
 * as events with the same transaction.
18
 *
19
 * The supported requests are \c register , \c call , \c accept, \c hold , \c unhold and
20
 * \c hangup . \c register can be used, as the name suggests, to register
21
 * a username at a SIPre registrar to call and be called; \c call is used
22
 * to send an INVITE to a different SIPre URI through the plugin, while
23
 * \c accept is used to accept the call in case one is invited instead
24
 * of inviting; ; \c hold and \c unhold can be used respectively to put a
25
 * call on-hold and to resume it; finally, \c hangup can be used to terminate the
26
 * communication at any time, either to hangup (BYE) an ongoing call or
27
 * to cancel/decline (CANCEL/BYE) a call that hasn't started yet.
28
 *
29
 * Actual API docs: TBD.
30
 *
31
 * \ingroup plugins
32
 * \ref plugins
33
 */
34

    
35
#include "plugin.h"
36

    
37
#include <arpa/inet.h>
38
#include <net/if.h>
39
#include <sys/socket.h>
40
#include <netdb.h>
41
#include <poll.h>
42

    
43
#include <jansson.h>
44

    
45
#include <re_types.h>
46
#include <re_fmt.h>
47
#include <re_mbuf.h>
48
#include <re_msg.h>
49
#include <re_list.h>
50
#include <re_sa.h>
51
#include <re_main.h>
52
#include <re_mem.h>
53
#include <re_mqueue.h>
54
#include <re_sdp.h>
55
#include <re_uri.h>
56
#include <re_sip.h>
57
#include <re_sipreg.h>
58
#include <re_sipsess.h>
59
#include <re_srtp.h>
60
#include <re_tmr.h>
61
#include <re_tls.h>
62

    
63
#include "../debug.h"
64
#include "../apierror.h"
65
#include "../config.h"
66
#include "../mutex.h"
67
#include "../record.h"
68
#include "../rtp.h"
69
#include "../rtcp.h"
70
#include "../sdp-utils.h"
71
#include "../utils.h"
72
#include "../ip-utils.h"
73

    
74

    
75
/* Plugin information */
76
#define JANUS_SIPRE_VERSION                        1
77
#define JANUS_SIPRE_VERSION_STRING        "0.0.1"
78
#define JANUS_SIPRE_DESCRIPTION                "This is a simple SIP plugin for Janus (based on libre instead of Sofia), allowing WebRTC peers to register at a SIP server and call SIP user agents through the gateway."
79
#define JANUS_SIPRE_NAME                        "JANUS SIPre plugin"
80
#define JANUS_SIPRE_AUTHOR                        "Meetecho s.r.l."
81
#define JANUS_SIPRE_PACKAGE                        "janus.plugin.sipre"
82

    
83
/* Plugin methods */
84
janus_plugin *create(void);
85
int janus_sipre_init(janus_callbacks *callback, const char *config_path);
86
void janus_sipre_destroy(void);
87
int janus_sipre_get_api_compatibility(void);
88
int janus_sipre_get_version(void);
89
const char *janus_sipre_get_version_string(void);
90
const char *janus_sipre_get_description(void);
91
const char *janus_sipre_get_name(void);
92
const char *janus_sipre_get_author(void);
93
const char *janus_sipre_get_package(void);
94
void janus_sipre_create_session(janus_plugin_session *handle, int *error);
95
struct janus_plugin_result *janus_sipre_handle_message(janus_plugin_session *handle, char *transaction, json_t *message, json_t *jsep);
96
void janus_sipre_setup_media(janus_plugin_session *handle);
97
void janus_sipre_incoming_rtp(janus_plugin_session *handle, int video, char *buf, int len);
98
void janus_sipre_incoming_rtcp(janus_plugin_session *handle, int video, char *buf, int len);
99
void janus_sipre_hangup_media(janus_plugin_session *handle);
100
void janus_sipre_destroy_session(janus_plugin_session *handle, int *error);
101
json_t *janus_sipre_query_session(janus_plugin_session *handle);
102

    
103
/* Plugin setup */
104
static janus_plugin janus_sipre_plugin =
105
        JANUS_PLUGIN_INIT (
106
                .init = janus_sipre_init,
107
                .destroy = janus_sipre_destroy,
108

    
109
                .get_api_compatibility = janus_sipre_get_api_compatibility,
110
                .get_version = janus_sipre_get_version,
111
                .get_version_string = janus_sipre_get_version_string,
112
                .get_description = janus_sipre_get_description,
113
                .get_name = janus_sipre_get_name,
114
                .get_author = janus_sipre_get_author,
115
                .get_package = janus_sipre_get_package,
116

    
117
                .create_session = janus_sipre_create_session,
118
                .handle_message = janus_sipre_handle_message,
119
                .setup_media = janus_sipre_setup_media,
120
                .incoming_rtp = janus_sipre_incoming_rtp,
121
                .incoming_rtcp = janus_sipre_incoming_rtcp,
122
                .hangup_media = janus_sipre_hangup_media,
123
                .destroy_session = janus_sipre_destroy_session,
124
                .query_session = janus_sipre_query_session,
125
        );
126

    
127
/* Plugin creator */
128
janus_plugin *create(void) {
129
        JANUS_LOG(LOG_VERB, "%s created!\n", JANUS_SIPRE_NAME);
130
        return &janus_sipre_plugin;
131
}
132

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

    
172
/* Useful stuff */
173
static volatile gint initialized = 0, stopping = 0;
174
static gboolean notify_events = TRUE;
175
static janus_callbacks *gateway = NULL;
176

    
177
static char *local_ip = NULL;
178
static int keepalive_interval = 120;
179
static gboolean behind_nat = FALSE;
180
static char *user_agent;
181
#define JANUS_DEFAULT_REGISTER_TTL        3600
182
static uint32_t register_ttl = JANUS_DEFAULT_REGISTER_TTL;
183

    
184
static GThread *handler_thread;
185
static GThread *watchdog;
186
static void *janus_sipre_handler(void *data);
187

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

    
197
static void janus_sipre_message_free(janus_sipre_message *msg) {
198
        if(!msg || msg == &exit_message)
199
                return;
200

    
201
        msg->handle = NULL;
202

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

    
212
        g_free(msg);
213
}
214

    
215
/* libre SIP stack */
216
static volatile int libre_inited = 0;
217
GThread *sipstack_thread = NULL;
218

    
219
/* Message queue */
220
static struct mqueue *mq = NULL;
221
void janus_sipre_mqueue_handler(int id, void *data, void *arg);
222
typedef enum janus_sipre_mqueue_event {
223
        janus_sipre_mqueue_event_do_init,
224
        janus_sipre_mqueue_event_do_register,
225
        janus_sipre_mqueue_event_do_call,
226
        janus_sipre_mqueue_event_do_accept,
227
        janus_sipre_mqueue_event_do_rcode,
228
        janus_sipre_mqueue_event_do_update,
229
        janus_sipre_mqueue_event_do_sipinfo,
230
        janus_sipre_mqueue_event_do_bye,
231
        janus_sipre_mqueue_event_do_destroy,
232
        /* TODO Add other events here */
233
        janus_sipre_mqueue_event_do_exit
234
} janus_sipre_mqueue_event;
235
static const char *janus_sipre_mqueue_event_string(janus_sipre_mqueue_event event) {
236
        switch(event) {
237
                case janus_sipre_mqueue_event_do_init:
238
                        return "init";
239
                case janus_sipre_mqueue_event_do_register:
240
                        return "register";
241
                case janus_sipre_mqueue_event_do_call:
242
                        return "call";
243
                case janus_sipre_mqueue_event_do_accept:
244
                        return "accept";
245
                case janus_sipre_mqueue_event_do_rcode:
246
                        return "rcode";
247
                case janus_sipre_mqueue_event_do_update:
248
                        return "update";
249
                case janus_sipre_mqueue_event_do_sipinfo:
250
                        return "sipinfo";
251
                case janus_sipre_mqueue_event_do_bye:
252
                        return "bye";
253
                case janus_sipre_mqueue_event_do_destroy:
254
                        return "destroy";
255
                case janus_sipre_mqueue_event_do_exit:
256
                        return "exit";
257
                default:
258
                        return "unknown";
259
        }
260
}
261
typedef struct janus_sipre_mqueue_payload {
262
        void *session;                                /* The session this event refers to */
263
        const struct sip_msg *msg;        /* The SIP message this refers to, if any */
264
        int rcode;                                        /* The error code to send back, if any */
265
        void *data;                                        /* Payload specific data */
266
} janus_sipre_mqueue_payload;
267
static janus_sipre_mqueue_payload *janus_sipre_mqueue_payload_create(void *session, const struct sip_msg *msg, int rcode, void *data) {
268
        janus_sipre_mqueue_payload *payload = g_malloc0(sizeof(janus_sipre_mqueue_payload));
269
        payload->session = session;
270
        payload->msg = msg;
271
        payload->rcode = rcode;
272
        payload->data = data;
273
        return payload;
274
}
275

    
276
/* Helper to quickly get the reason associated to response codes */
277
static const char *janus_sipre_error_reason(int rcode) {
278
        switch(rcode) {
279
                case 100: return "Trying";
280
                case 180: return "Ringing";
281
                case 181: return "Call is Being Forwarded";
282
                case 182: return "Queued";
283
                case 183: return "Session in Progress";
284
                case 199: return "Early Dialog Terminated";
285
                case 200: return "OK";
286
                case 202: return "Accepted";
287
                case 204: return "No Notification";
288
                case 300: return "Multiple Choices";
289
                case 301: return "Moved Permanently";
290
                case 302: return "Moved Temporarily";
291
                case 305: return "Use Proxy";
292
                case 380: return "Alternative Service";
293
                case 400: return "Bad Request";
294
                case 401: return "Unauthorized";
295
                case 402: return "Payment Required";
296
                case 403: return "Forbidden";
297
                case 404: return "Not Found";
298
                case 405: return "Method Not Allowed";
299
                case 406: return "Not Acceptable";
300
                case 407: return "Proxy Authentication Required";
301
                case 408: return "Request Timeout";
302
                case 409: return "Conflict";
303
                case 410: return "Gone";
304
                case 411: return "Length Required";
305
                case 412: return "Conditional Request Failed";
306
                case 413: return "Request Entity Too Large";
307
                case 414: return "Request-URI Too Long";
308
                case 415: return "Unsupported Media Type";
309
                case 416: return "Unsupported URI Scheme";
310
                case 417: return "Unknown Resource-Priority";
311
                case 420: return "Bad Extension";
312
                case 421: return "Extension Required";
313
                case 422: return "Session Interval Too Small";
314
                case 423: return "Interval Too Brief";
315
                case 424: return "Bad Location Information";
316
                case 428: return "Use Identity Header";
317
                case 429: return "Provide Referrer Identity";
318
                case 430: return "Flow Failed";
319
                case 433: return "Anonymity Disallowed";
320
                case 436: return "Bad Identity-Info";
321
                case 437: return "Unsupported Certificate";
322
                case 438: return "Invalid Identity Header";
323
                case 439: return "First Hop Lacks Outbound Support";
324
                case 470: return "Consent Needed";
325
                case 480: return "Temporarily Unavailable";
326
                case 481: return "Call/Transaction Does Not Exist";
327
                case 482: return "Loop Detected.";
328
                case 483: return "Too Many Hops";
329
                case 484: return "Address Incomplete";
330
                case 485: return "Ambiguous";
331
                case 486: return "Busy Here";
332
                case 487: return "Request Terminated";
333
                case 488: return "Not Acceptable Here";
334
                case 489: return "Bad Event";
335
                case 491: return "Request Pending";
336
                case 493: return "Undecipherable";
337
                case 494: return "Security Agreement Required";
338
                case 500: return "Server Internal Error";
339
                case 501: return "Not Implemented";
340
                case 502: return "Bad Gateway";
341
                case 503: return "Service Unavailable";
342
                case 504: return "Server Time-out";
343
                case 505: return "Version Not Supported";
344
                case 513: return "Message Too Large";
345
                case 580: return "Precondition Failure";
346
                case 600: return "Busy Everywhere";
347
                case 603: return "Decline";
348
                case 604: return "Does Not Exist Anywhere";
349
                case 606: return "Not Acceptable";
350
                default: return "Unknown Error";
351
        }
352
}
353

    
354
/* Registration info */
355
typedef enum {
356
        janus_sipre_registration_status_disabled = -2,
357
        janus_sipre_registration_status_failed = -1,
358
        janus_sipre_registration_status_unregistered = 0,
359
        janus_sipre_registration_status_registering,
360
        janus_sipre_registration_status_registered,
361
        janus_sipre_registration_status_unregistering,
362
} janus_sipre_registration_status;
363

    
364
static const char *janus_sipre_registration_status_string(janus_sipre_registration_status status) {
365
        switch(status) {
366
                case janus_sipre_registration_status_disabled:
367
                        return "disabled";
368
                case janus_sipre_registration_status_failed:
369
                        return "failed";
370
                case janus_sipre_registration_status_unregistered:
371
                        return "unregistered";
372
                case janus_sipre_registration_status_registering:
373
                        return "registering";
374
                case janus_sipre_registration_status_registered:
375
                        return "registered";
376
                case janus_sipre_registration_status_unregistering:
377
                        return "unregistering";
378
                default:
379
                        return "unknown";
380
        }
381
}
382

    
383

    
384
typedef enum {
385
        janus_sipre_call_status_idle = 0,
386
        janus_sipre_call_status_inviting,
387
        janus_sipre_call_status_invited,
388
        janus_sipre_call_status_incall,
389
        janus_sipre_call_status_closing,
390
} janus_sipre_call_status;
391

    
392
static const char *janus_sipre_call_status_string(janus_sipre_call_status status) {
393
        switch(status) {
394
                case janus_sipre_call_status_idle:
395
                        return "idle";
396
                case janus_sipre_call_status_inviting:
397
                        return "inviting";
398
                case janus_sipre_call_status_invited:
399
                        return "invited";
400
                case janus_sipre_call_status_incall:
401
                        return "incall";
402
                case janus_sipre_call_status_closing:
403
                        return "closing";
404
                default:
405
                        return "unknown";
406
        }
407
}
408

    
409

    
410
typedef enum {
411
        janus_sipre_secret_type_plaintext = 1,
412
        janus_sipre_secret_type_hashed = 2,
413
        janus_sipre_secret_type_unknown
414
} janus_sipre_secret_type;
415

    
416
typedef struct janus_sipre_account {
417
        char *identity;
418
        char *user_agent;                /* Used to override the general UA string */
419
        gboolean sips;
420
        char *username;
421
        char *display_name;                /* Used for outgoing calls in the From header */
422
        char *authuser;                        /**< username to use for authentication */
423
        char *secret;
424
        janus_sipre_secret_type secret_type;
425
        int sip_port;
426
        char *proxy;
427
        janus_sipre_registration_status registration_status;
428
} janus_sipre_account;
429

    
430
typedef struct janus_sipre_stack {
431
        struct sip *sipstack;                                /* SIP stack */
432
        struct tls *tls;                                        /* TLS transport, if needed */
433
        struct sipsess *sess;                                /* SIP session */
434
        struct sipsess_sock *sess_sock;                /* SIP session socket */
435
        struct sipreg *reg;                                        /* SIP registration */
436
        uint32_t expires;                                        /* Registration interval (seconds) */
437
        const struct sip_msg *invite;                /* Current INVITE */
438
        void *session;                                                /* Opaque pointer to the plugin session */
439
} janus_sipre_stack;
440

    
441
typedef struct janus_sipre_media {
442
        char *remote_ip;
443
        gboolean ready;
444
        gboolean autoack;
445
        gboolean require_srtp, has_srtp_local, has_srtp_remote;
446
        gboolean on_hold;
447
        gboolean has_audio;
448
        int audio_rtp_fd, audio_rtcp_fd;
449
        int local_audio_rtp_port, remote_audio_rtp_port;
450
        int local_audio_rtcp_port, remote_audio_rtcp_port;
451
        guint32 audio_ssrc, audio_ssrc_peer;
452
        int audio_pt;
453
        const char *audio_pt_name;
454
        srtp_t audio_srtp_in, audio_srtp_out;
455
        srtp_policy_t audio_remote_policy, audio_local_policy;
456
        int audio_srtp_suite_in, audio_srtp_suite_out;
457
        gboolean audio_send;
458
        janus_sdp_mdirection pre_hold_audio_dir;
459
        gboolean has_video;
460
        int video_rtp_fd, video_rtcp_fd;
461
        int local_video_rtp_port, remote_video_rtp_port;
462
        int local_video_rtcp_port, remote_video_rtcp_port;
463
        guint32 video_ssrc, video_ssrc_peer;
464
        int video_pt;
465
        const char *video_pt_name;
466
        srtp_t video_srtp_in, video_srtp_out;
467
        srtp_policy_t video_remote_policy, video_local_policy;
468
        int video_srtp_suite_in, video_srtp_suite_out;
469
        gboolean video_send;
470
        janus_sdp_mdirection pre_hold_video_dir;
471
        janus_rtp_switching_context context;
472
        int pipefd[2];
473
        gboolean updated;
474
} janus_sipre_media;
475

    
476
typedef struct janus_sipre_session {
477
        janus_plugin_session *handle;
478
        janus_sipre_stack stack;
479
        janus_sipre_account account;
480
        janus_sipre_call_status status;
481
        janus_sipre_media media;
482
        char *transaction;
483
        char *callee;
484
        char *callid;
485
        char *temp_sdp;
486
        janus_sdp *sdp;                                /* The SDP this user sent */
487
        janus_recorder *arc;                /* The Janus recorder instance for this user's audio, if enabled */
488
        janus_recorder *arc_peer;        /* The Janus recorder instance for the peer's audio, if enabled */
489
        janus_recorder *vrc;                /* The Janus recorder instance for this user's video, if enabled */
490
        janus_recorder *vrc_peer;        /* The Janus recorder instance for the peer's video, if enabled */
491
        janus_mutex rec_mutex;                /* Mutex to protect the recorders from race conditions */
492
        volatile gint hangingup;
493
        gint64 destroyed;        /* Time at which this session was marked as destroyed */
494
        janus_mutex mutex;
495
} janus_sipre_session;
496
static GHashTable *sessions;
497
static GList *old_sessions;
498
static GHashTable *identities;
499
static GHashTable *callids;
500
static janus_mutex sessions_mutex;
501

    
502

    
503
/* SRTP stuff (in case we need SDES) */
504
static int janus_sipre_srtp_set_local(janus_sipre_session *session, gboolean video, char **crypto) {
505
        if(session == NULL)
506
                return -1;
507
        /* Generate key/salt */
508
        uint8_t *key = g_malloc0(SRTP_MASTER_LENGTH);
509
        srtp_crypto_get_random(key, SRTP_MASTER_LENGTH);
510
        /* Set SRTP policies */
511
        srtp_policy_t *policy = video ? &session->media.video_local_policy : &session->media.audio_local_policy;
512
        srtp_crypto_policy_set_rtp_default(&(policy->rtp));
513
        srtp_crypto_policy_set_rtcp_default(&(policy->rtcp));
514
        policy->ssrc.type = ssrc_any_inbound;
515
        policy->key = key;
516
        policy->next = NULL;
517
        /* Create SRTP context */
518
        srtp_err_status_t res = srtp_create(video ? &session->media.video_srtp_out : &session->media.audio_srtp_out, policy);
519
        if(res != srtp_err_status_ok) {
520
                /* Something went wrong... */
521
                JANUS_LOG(LOG_ERR, "Oops, error creating outbound SRTP session: %d (%s)\n", res, janus_srtp_error_str(res));
522
                g_free(key);
523
                policy->key = NULL;
524
                return -2;
525
        }
526
        /* Base64 encode the salt */
527
        *crypto = g_base64_encode(key, SRTP_MASTER_LENGTH);
528
        if((video && session->media.video_srtp_out) || (!video && session->media.audio_srtp_out)) {
529
                JANUS_LOG(LOG_VERB, "%s outbound SRTP session created\n", video ? "Video" : "Audio");
530
        }
531
        return 0;
532
}
533
static int janus_sipre_srtp_set_remote(janus_sipre_session *session, gboolean video, const char *crypto, int suite) {
534
        if(session == NULL || crypto == NULL)
535
                return -1;
536
        /* Base64 decode the crypto string and set it as the remote SRTP context */
537
        gsize len = 0;
538
        guchar *decoded = g_base64_decode(crypto, &len);
539
        if(len < SRTP_MASTER_LENGTH) {
540
                /* FIXME Can this happen? */
541
                g_free(decoded);
542
                return -2;
543
        }
544
        /* Set SRTP policies */
545
        srtp_policy_t *policy = video ? &session->media.video_remote_policy : &session->media.audio_remote_policy;
546
        srtp_crypto_policy_set_rtp_default(&(policy->rtp));
547
        srtp_crypto_policy_set_rtcp_default(&(policy->rtcp));
548
        if(suite == 32) {
549
                srtp_crypto_policy_set_aes_cm_128_hmac_sha1_32(&(policy->rtp));
550
                srtp_crypto_policy_set_aes_cm_128_hmac_sha1_32(&(policy->rtcp));
551
        } else if(suite == 80) {
552
                srtp_crypto_policy_set_aes_cm_128_hmac_sha1_80(&(policy->rtp));
553
                srtp_crypto_policy_set_aes_cm_128_hmac_sha1_80(&(policy->rtcp));
554
        }
555
        policy->ssrc.type = ssrc_any_inbound;
556
        policy->key = decoded;
557
        policy->next = NULL;
558
        /* Create SRTP context */
559
        srtp_err_status_t res = srtp_create(video ? &session->media.video_srtp_in : &session->media.audio_srtp_in, policy);
560
        if(res != srtp_err_status_ok) {
561
                /* Something went wrong... */
562
                JANUS_LOG(LOG_ERR, "Oops, error creating inbound SRTP session: %d (%s)\n", res, janus_srtp_error_str(res));
563
                g_free(decoded);
564
                policy->key = NULL;
565
                return -2;
566
        }
567
        if((video && session->media.video_srtp_in) || (!video && session->media.audio_srtp_in)) {
568
                JANUS_LOG(LOG_VERB, "%s inbound SRTP session created\n", video ? "Video" : "Audio");
569
        }
570
        return 0;
571
}
572
static void janus_sipre_srtp_cleanup(janus_sipre_session *session) {
573
        if(session == NULL)
574
                return;
575
        session->media.autoack = TRUE;
576
        session->media.require_srtp = FALSE;
577
        session->media.has_srtp_local = FALSE;
578
        session->media.has_srtp_remote = FALSE;
579
        /* Audio */
580
        if(session->media.audio_srtp_out)
581
                srtp_dealloc(session->media.audio_srtp_out);
582
        session->media.audio_srtp_out = NULL;
583
        g_free(session->media.audio_local_policy.key);
584
        session->media.audio_local_policy.key = NULL;
585
        session->media.audio_srtp_suite_out = 0;
586
        if(session->media.audio_srtp_in)
587
                srtp_dealloc(session->media.audio_srtp_in);
588
        session->media.audio_srtp_in = NULL;
589
        g_free(session->media.audio_remote_policy.key);
590
        session->media.audio_remote_policy.key = NULL;
591
        session->media.audio_srtp_suite_in = 0;
592
        /* Video */
593
        if(session->media.video_srtp_out)
594
                srtp_dealloc(session->media.video_srtp_out);
595
        session->media.video_srtp_out = NULL;
596
        g_free(session->media.video_local_policy.key);
597
        session->media.video_local_policy.key = NULL;
598
        session->media.video_srtp_suite_out = 0;
599
        if(session->media.video_srtp_in)
600
                srtp_dealloc(session->media.video_srtp_in);
601
        session->media.video_srtp_in = NULL;
602
        g_free(session->media.video_remote_policy.key);
603
        session->media.video_remote_policy.key = NULL;
604
        session->media.video_srtp_suite_in = 0;
605
}
606

    
607

    
608
/* libre event thread */
609
gpointer janus_sipre_stack_thread(gpointer user_data);
610
/* libre callbacks */
611
int janus_sipre_cb_auth(char **user, char **pass, const char *realm, void *arg);
612
void janus_sipre_cb_register(int err, const struct sip_msg *msg, void *arg);
613
void janus_sipre_cb_progress(const struct sip_msg *msg, void *arg);
614
void janus_sipre_cb_incoming(const struct sip_msg *msg, void *arg);
615
int janus_sipre_cb_offer(struct mbuf **mbp, const struct sip_msg *msg, void *arg);
616
int janus_sipre_cb_answer(const struct sip_msg *msg, void *arg);
617
void janus_sipre_cb_established(const struct sip_msg *msg, void *arg);
618
void janus_sipre_cb_closed(int err, const struct sip_msg *msg, void *arg);
619
void janus_sipre_cb_exit(void *arg);
620

    
621
/* URI parsing utilities */
622
static int janus_sipre_parse_uri(const char *uri) {
623
        if(uri == NULL)
624
                return -1;
625
        struct sip_addr addr;
626
        struct pl pluri;
627
        pl_set_str(&pluri, uri);
628
        if(sip_addr_decode(&addr, &pluri) != 0)
629
                return -1;
630
        return 0;
631
}
632
static char *janus_sipre_get_uri_username(const char *uri) {
633
        if(uri == NULL)
634
                return NULL;
635
        struct sip_addr addr;
636
        struct pl pluri;
637
        pl_set_str(&pluri, uri);
638
        if(sip_addr_decode(&addr, &pluri) != 0)
639
                return NULL;
640
        char *at = strchr(addr.uri.user.p, '@');
641
        if(at != NULL)
642
                *(at) = '\0';
643
        char *username = g_strdup(addr.uri.user.p);
644
        if(at != NULL)
645
                *(at) = '@';
646
        return username;
647
}
648
static char *janus_sipre_get_uri_host(const char *uri) {
649
        if(uri == NULL)
650
                return NULL;
651
        struct sip_addr addr;
652
        struct pl pluri;
653
        pl_set_str(&pluri, uri);
654
        if(sip_addr_decode(&addr, &pluri) != 0)
655
                return NULL;
656
        return g_strdup(addr.uri.host.p);
657
}
658
static uint16_t janus_sipre_get_uri_port(const char *uri) {
659
        if(uri == NULL)
660
                return 0;
661
        struct sip_addr addr;
662
        struct pl pluri;
663
        pl_set_str(&pluri, uri);
664
        if(sip_addr_decode(&addr, &pluri) != 0)
665
                return 0;
666
        return addr.uri.port;
667
}
668

    
669

    
670
/* SDP parsing and manipulation */
671
void janus_sipre_sdp_process(janus_sipre_session *session, janus_sdp *sdp, gboolean answer, gboolean update, gboolean *changed);
672
char *janus_sipre_sdp_manipulate(janus_sipre_session *session, janus_sdp *sdp, gboolean answer);
673
/* Media */
674
static int janus_sipre_allocate_local_ports(janus_sipre_session *session);
675
static void *janus_sipre_relay_thread(void *data);
676

    
677

    
678
/* Error codes */
679
#define JANUS_SIPRE_ERROR_UNKNOWN_ERROR                499
680
#define JANUS_SIPRE_ERROR_NO_MESSAGE                        440
681
#define JANUS_SIPRE_ERROR_INVALID_JSON                441
682
#define JANUS_SIPRE_ERROR_INVALID_REQUEST                442
683
#define JANUS_SIPRE_ERROR_MISSING_ELEMENT                443
684
#define JANUS_SIPRE_ERROR_INVALID_ELEMENT                444
685
#define JANUS_SIPRE_ERROR_ALREADY_REGISTERED        445
686
#define JANUS_SIPRE_ERROR_INVALID_ADDRESS                446
687
#define JANUS_SIPRE_ERROR_WRONG_STATE                        447
688
#define JANUS_SIPRE_ERROR_MISSING_SDP                        448
689
#define JANUS_SIPRE_ERROR_LIBRE_ERROR                449
690
#define JANUS_SIPRE_ERROR_IO_ERROR                        450
691
#define JANUS_SIPRE_ERROR_RECORDING_ERROR                451
692
#define JANUS_SIPRE_ERROR_TOO_STRICT                        452
693

    
694

    
695
/* SIPre watchdog/garbage collector (sort of) */
696
static void *janus_sipre_watchdog(void *data) {
697
        JANUS_LOG(LOG_INFO, "SIPre watchdog started\n");
698
        gint64 now = 0;
699
        while(g_atomic_int_get(&initialized) && !g_atomic_int_get(&stopping)) {
700
                janus_mutex_lock(&sessions_mutex);
701
                /* Iterate on all the sessions */
702
                now = janus_get_monotonic_time();
703
                if(old_sessions != NULL) {
704
                        GList *sl = old_sessions;
705
                        JANUS_LOG(LOG_HUGE, "Checking %d old SIPre sessions...\n", g_list_length(old_sessions));
706
                        while(sl) {
707
                                janus_sipre_session *session = (janus_sipre_session *)sl->data;
708
                                if(!session) {
709
                                        sl = sl->next;
710
                                        continue;
711
                                }
712
                                if(now-session->destroyed >= 5*G_USEC_PER_SEC) {
713
                                        /* We're lazy and actually get rid of the stuff only after a few seconds */
714
                                        JANUS_LOG(LOG_VERB, "Freeing old SIPre session\n");
715
                                        GList *rm = sl->next;
716
                                        old_sessions = g_list_delete_link(old_sessions, sl);
717
                                        sl = rm;
718
                                        if(session->account.identity) {
719
                                            g_hash_table_remove(identities, session->account.identity);
720
                                            g_free(session->account.identity);
721
                                            session->account.identity = NULL;
722
                                        }
723
                                        session->account.sips = TRUE;
724
                                        if(session->account.proxy) {
725
                                            g_free(session->account.proxy);
726
                                            session->account.proxy = NULL;
727
                                        }
728
                                        if(session->account.secret) {
729
                                            g_free(session->account.secret);
730
                                            session->account.secret = NULL;
731
                                        }
732
                                        if(session->account.username) {
733
                                            g_free(session->account.username);
734
                                            session->account.username = NULL;
735
                                        }
736
                                        if(session->account.display_name) {
737
                                            g_free(session->account.display_name);
738
                                            session->account.display_name = NULL;
739
                                        }
740
                                        if(session->account.user_agent) {
741
                                            g_free(session->account.user_agent);
742
                                            session->account.user_agent = NULL;
743
                                        }
744
                                        if(session->account.authuser) {
745
                                            g_free(session->account.authuser);
746
                                            session->account.authuser = NULL;
747
                                        }
748
                                        if(session->callee) {
749
                                            g_free(session->callee);
750
                                            session->callee = NULL;
751
                                        }
752
                                        if(session->callid) {
753
                                            g_hash_table_remove(callids, session->callid);
754
                                            g_free(session->callid);
755
                                            session->callid = NULL;
756
                                        }
757
                                        if(session->sdp) {
758
                                            janus_sdp_free(session->sdp);
759
                                            session->sdp = NULL;
760
                                        }
761
                                        if(session->transaction) {
762
                                            g_free(session->transaction);
763
                                            session->transaction = NULL;
764
                                        }
765
                                        if(session->media.remote_ip) {
766
                                            g_free(session->media.remote_ip);
767
                                            session->media.remote_ip = NULL;
768
                                        }
769
                                        janus_sipre_srtp_cleanup(session);
770
                                        session->handle = NULL;
771
                                        g_free(session);
772
                                        session = NULL;
773
                                        continue;
774
                                }
775
                                sl = sl->next;
776
                        }
777
                }
778
                janus_mutex_unlock(&sessions_mutex);
779
                g_usleep(500000);
780
        }
781
        JANUS_LOG(LOG_INFO, "SIPre watchdog stopped\n");
782
        return NULL;
783
}
784

    
785

    
786
/* Random string helper (for call-ids) */
787
static char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
788
static void janus_sipre_random_string(int length, char *buffer) {
789
        if(length > 0 && buffer) {
790
                int l = (int)(sizeof(charset)-1);
791
                int i=0;
792
                for(i=0; i<length; i++) {
793
                        int key = rand() % l;
794
                        buffer[i] = charset[key];
795
                }
796
                buffer[length-1] = '\0';
797
        }
798
}
799

    
800

    
801
#ifdef HAVE_LIBRE_SIPTRACE
802
/* libre SIP logger function: when the Event Handlers mechanism is enabled,
803
 * we use this to intercept SIP messages sent and received by the stack */
804
static void janus_sipre_msg_logger(bool tx, enum sip_transp tp, const struct sa *src, const struct sa *dst,
805
                const uint8_t *pkt, size_t len, void *arg) {
806
        /* Access the session this message refers to */
807
        janus_sipre_session *session = (janus_sipre_session *)arg;
808
        /* Print the SIP message */
809
        char sip_msg[2048];
810
        g_snprintf(sip_msg, sizeof(sip_msg), "%.*s", (int)len, (char *)pkt);
811
        /* Shoot the event */
812
        json_t *info = json_object();
813
        json_object_set_new(info, "event", json_string(tx ? "sip-out" : "sip-in"));
814
        json_object_set_new(info, "sip", json_string(sip_msg));
815
        gateway->notify_event(&janus_sipre_plugin, session->handle, info);
816
}
817
#endif
818

    
819

    
820
/* Plugin implementation */
821
int janus_sipre_init(janus_callbacks *callback, const char *config_path) {
822
        if(g_atomic_int_get(&stopping)) {
823
                /* Still stopping from before */
824
                return -1;
825
        }
826
        if(callback == NULL || config_path == NULL) {
827
                /* Invalid arguments */
828
                return -1;
829
        }
830

    
831
        /* Read configuration */
832
        char filename[255];
833
        g_snprintf(filename, 255, "%s/%s.cfg", config_path, JANUS_SIPRE_PACKAGE);
834
        JANUS_LOG(LOG_VERB, "Configuration file: %s\n", filename);
835
        janus_config *config = janus_config_parse(filename);
836
        if(config != NULL) {
837
                janus_config_print(config);
838

    
839
                janus_config_item *item = janus_config_get_item_drilldown(config, "general", "local_ip");
840
                if(item && item->value) {
841
                        /* Verify that the address is valid */
842
                        struct ifaddrs *ifas = NULL;
843
                        janus_network_address iface;
844
                        janus_network_address_string_buffer ibuf;
845
                        if(getifaddrs(&ifas) || ifas == NULL) {
846
                                JANUS_LOG(LOG_ERR, "Unable to acquire list of network devices/interfaces; some configurations may not work as expected...\n");
847
                        } else {
848
                                if(janus_network_lookup_interface(ifas, item->value, &iface) != 0) {
849
                                        JANUS_LOG(LOG_WARN, "Error setting local IP address to %s, falling back to detecting IP address...\n", item->value);
850
                                } else {
851
                                        if(janus_network_address_to_string_buffer(&iface, &ibuf) != 0 || janus_network_address_string_buffer_is_null(&ibuf)) {
852
                                                JANUS_LOG(LOG_WARN, "Error getting local IP address from %s, falling back to detecting IP address...\n", item->value);
853
                                        } else {
854
                                                local_ip = g_strdup(janus_network_address_string_from_buffer(&ibuf));
855
                                        }
856
                                }
857
                        }
858
                }
859

    
860
                item = janus_config_get_item_drilldown(config, "general", "keepalive_interval");
861
                if(item && item->value) {
862
                        keepalive_interval = atoi(item->value);
863
                }
864
                JANUS_LOG(LOG_VERB, "SIPre keep-alive interval set to %d seconds\n", keepalive_interval);
865

    
866
                item = janus_config_get_item_drilldown(config, "general", "register_ttl");
867
                if(item && item->value) {
868
                        register_ttl = atol(item->value);
869
                }
870
                JANUS_LOG(LOG_VERB, "SIPre registration TTL set to %d seconds\n", register_ttl);
871

    
872
                item = janus_config_get_item_drilldown(config, "general", "behind_nat");
873
                if(item && item->value) {
874
                        behind_nat = janus_is_true(item->value);
875
                }
876

    
877
                item = janus_config_get_item_drilldown(config, "general", "user_agent");
878
                if(item && item->value) {
879
                        user_agent = g_strdup(item->value);
880
                } else {
881
                        user_agent = g_strdup("Janus WebRTC Gateway SIPre Plugin "JANUS_SIPRE_VERSION_STRING);
882
                }
883
                JANUS_LOG(LOG_VERB, "SIPre User-Agent set to %s\n", user_agent);
884

    
885
                item = janus_config_get_item_drilldown(config, "general", "events");
886
                if(item != NULL && item->value != NULL) {
887
                        notify_events = janus_is_true(item->value);
888
                }
889
                if(!notify_events && callback->events_is_enabled()) {
890
                        JANUS_LOG(LOG_WARN, "Notification of events to handlers disabled for %s\n", JANUS_SIPRE_NAME);
891
                }
892

    
893
                janus_config_destroy(config);
894
        }
895
        config = NULL;
896

    
897
        if(local_ip == NULL) {
898
                local_ip = janus_network_detect_local_ip_as_string(janus_network_query_options_any_ip);
899
                if(local_ip == NULL) {
900
                        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");
901
                        local_ip = g_strdup("127.0.0.1");
902
                }
903
        }
904
        JANUS_LOG(LOG_VERB, "Local IP set to %s\n", local_ip);
905

    
906
#ifdef HAVE_SRTP_2
907
        /* Init randomizer (for randum numbers in SRTP) */
908
        RAND_poll();
909
#endif
910

    
911
        sessions = g_hash_table_new(NULL, NULL);
912
        callids = g_hash_table_new(g_str_hash, g_str_equal);
913
        identities = g_hash_table_new(g_str_hash, g_str_equal);
914
        janus_mutex_init(&sessions_mutex);
915
        messages = g_async_queue_new_full((GDestroyNotify) janus_sipre_message_free);
916
        /* This is the callback we'll need to invoke to contact the gateway */
917
        gateway = callback;
918

    
919
        g_atomic_int_set(&initialized, 1);
920

    
921
        GError *error = NULL;
922
        /* Start the sessions watchdog */
923
        watchdog = g_thread_try_new("sipre watchdog", &janus_sipre_watchdog, NULL, &error);
924
        if(error != NULL) {
925
                g_atomic_int_set(&initialized, 0);
926
                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the SIPre watchdog thread...\n", error->code, error->message ? error->message : "??");
927
                return -1;
928
        }
929
        /* Launch the thread that will handle incoming API messages */
930
        handler_thread = g_thread_try_new("sipre handler", janus_sipre_handler, NULL, &error);
931
        if(error != NULL) {
932
                g_atomic_int_set(&initialized, 0);
933
                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the SIPre handler thread...\n", error->code, error->message ? error->message : "??");
934
                return -1;
935
        }
936
        /* Launch the thread that will handle the libre initialization and event loop */
937
        g_atomic_int_set(&libre_inited, 0);
938
        sipstack_thread = g_thread_try_new("sipre loop", janus_sipre_stack_thread, NULL, &error);
939
        if(error != NULL) {
940
                g_atomic_int_set(&initialized, 0);
941
                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the SIPre loop thread...\n", error->code, error->message ? error->message : "??");
942
                return -1;
943
        }
944
        /* Let's wait for the libre initialization to complete */
945
        while(g_atomic_int_get(&libre_inited) == 0)
946
                g_usleep(100000);
947
        if(g_atomic_int_get(&libre_inited) == -1) {
948
                g_atomic_int_set(&initialized, 0);
949
                JANUS_LOG(LOG_ERR, "Got error trying to initialize libre...\n");
950
                return -1;
951
        }
952

    
953
#ifndef HAVE_LIBRE_SIPTRACE
954
        JANUS_LOG(LOG_WARN, "sip_set_trace() was not found in libre... "
955
                "The tracing of SIP incoming/outgoing SIP messages when using the SIPre plugin will not be available to Event Handlers. "
956
                "In case you're interested in that, apply this patch on your libre installation and recompile the plugin: "
957
                "https://raw.githubusercontent.com/alfredh/patches/master/re-sip-trace.patch\n");
958
#endif
959

    
960
        JANUS_LOG(LOG_INFO, "%s initialized!\n", JANUS_SIPRE_NAME);
961
        return 0;
962
}
963

    
964
void janus_sipre_destroy(void) {
965
        if(!g_atomic_int_get(&initialized))
966
                return;
967
        g_atomic_int_set(&stopping, 1);
968

    
969
        g_async_queue_push(messages, &exit_message);
970
        if(handler_thread != NULL) {
971
                g_thread_join(handler_thread);
972
                handler_thread = NULL;
973
        }
974

    
975
        /* Break the libre loop */
976
        mqueue_push(mq, janus_sipre_mqueue_event_do_exit, NULL);
977
        if(sipstack_thread != NULL) {
978
                g_thread_join(sipstack_thread);
979
                sipstack_thread = NULL;
980
        }
981
        if(watchdog != NULL) {
982
                g_thread_join(watchdog);
983
                watchdog = NULL;
984
        }
985
        /* FIXME We should destroy the sessions cleanly */
986
        janus_mutex_lock(&sessions_mutex);
987
        g_hash_table_destroy(sessions);
988
        g_hash_table_destroy(callids);
989
        g_hash_table_destroy(identities);
990
        sessions = NULL;
991
        callids = NULL;
992
        identities = NULL;
993
        janus_mutex_unlock(&sessions_mutex);
994
        g_async_queue_unref(messages);
995
        messages = NULL;
996
        g_atomic_int_set(&initialized, 0);
997
        g_atomic_int_set(&stopping, 0);
998

    
999
        g_free(local_ip);
1000

    
1001
        JANUS_LOG(LOG_INFO, "%s destroyed!\n", JANUS_SIPRE_NAME);
1002
}
1003

    
1004
int janus_sipre_get_api_compatibility(void) {
1005
        /* Important! This is what your plugin MUST always return: don't lie here or bad things will happen */
1006
        return JANUS_PLUGIN_API_VERSION;
1007
}
1008

    
1009
int janus_sipre_get_version(void) {
1010
        return JANUS_SIPRE_VERSION;
1011
}
1012

    
1013
const char *janus_sipre_get_version_string(void) {
1014
        return JANUS_SIPRE_VERSION_STRING;
1015
}
1016

    
1017
const char *janus_sipre_get_description(void) {
1018
        return JANUS_SIPRE_DESCRIPTION;
1019
}
1020

    
1021
const char *janus_sipre_get_name(void) {
1022
        return JANUS_SIPRE_NAME;
1023
}
1024

    
1025
const char *janus_sipre_get_author(void) {
1026
        return JANUS_SIPRE_AUTHOR;
1027
}
1028

    
1029
const char *janus_sipre_get_package(void) {
1030
        return JANUS_SIPRE_PACKAGE;
1031
}
1032

    
1033
void janus_sipre_create_session(janus_plugin_session *handle, int *error) {
1034
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
1035
                *error = -1;
1036
                return;
1037
        }
1038
        janus_sipre_session *session = g_malloc0(sizeof(janus_sipre_session));
1039
        session->handle = handle;
1040
        session->account.identity = NULL;
1041
        session->account.sips = TRUE;
1042
        session->account.username = NULL;
1043
        session->account.display_name = NULL;
1044
        session->account.user_agent = NULL;
1045
        session->account.authuser = NULL;
1046
        session->account.secret = NULL;
1047
        session->account.secret_type = janus_sipre_secret_type_unknown;
1048
        session->account.sip_port = 0;
1049
        session->account.proxy = NULL;
1050
        session->account.registration_status = janus_sipre_registration_status_unregistered;
1051
        session->status = janus_sipre_call_status_idle;
1052
        memset(&session->stack, 0, sizeof(janus_sipre_stack));
1053
        session->transaction = NULL;
1054
        session->callee = NULL;
1055
        session->callid = NULL;
1056
        session->sdp = NULL;
1057
        session->media.remote_ip = NULL;
1058
        session->media.ready = FALSE;
1059
        session->media.autoack = TRUE;
1060
        session->media.require_srtp = FALSE;
1061
        session->media.has_srtp_local = FALSE;
1062
        session->media.has_srtp_remote = FALSE;
1063
        session->media.on_hold = FALSE;
1064
        session->media.has_audio = FALSE;
1065
        session->media.audio_rtp_fd = -1;
1066
        session->media.audio_rtcp_fd= -1;
1067
        session->media.local_audio_rtp_port = 0;
1068
        session->media.remote_audio_rtp_port = 0;
1069
        session->media.local_audio_rtcp_port = 0;
1070
        session->media.remote_audio_rtcp_port = 0;
1071
        session->media.audio_ssrc = 0;
1072
        session->media.audio_ssrc_peer = 0;
1073
        session->media.audio_pt = -1;
1074
        session->media.audio_pt_name = NULL;
1075
        session->media.audio_srtp_suite_in = 0;
1076
        session->media.audio_srtp_suite_out = 0;
1077
        session->media.audio_send = TRUE;
1078
        session->media.pre_hold_audio_dir = JANUS_SDP_DEFAULT;
1079
        session->media.has_video = FALSE;
1080
        session->media.video_rtp_fd = -1;
1081
        session->media.video_rtcp_fd= -1;
1082
        session->media.local_video_rtp_port = 0;
1083
        session->media.remote_video_rtp_port = 0;
1084
        session->media.local_video_rtcp_port = 0;
1085
        session->media.remote_video_rtcp_port = 0;
1086
        session->media.video_ssrc = 0;
1087
        session->media.video_ssrc_peer = 0;
1088
        session->media.video_pt = -1;
1089
        session->media.video_pt_name = NULL;
1090
        session->media.video_srtp_suite_in = 0;
1091
        session->media.video_srtp_suite_out = 0;
1092
        session->media.video_send = TRUE;
1093
        session->media.pre_hold_video_dir = JANUS_SDP_DEFAULT;
1094
        /* Initialize the RTP context */
1095
        janus_rtp_switching_context_reset(&session->media.context);
1096
        session->media.pipefd[0] = -1;
1097
        session->media.pipefd[1] = -1;
1098
        session->media.updated = FALSE;
1099
        janus_mutex_init(&session->rec_mutex);
1100
        session->destroyed = 0;
1101
        g_atomic_int_set(&session->hangingup, 0);
1102
        janus_mutex_init(&session->mutex);
1103
        handle->plugin_handle = session;
1104

    
1105
        mqueue_push(mq, janus_sipre_mqueue_event_do_init, janus_sipre_mqueue_payload_create(session, NULL, 0, NULL));
1106

    
1107
        janus_mutex_lock(&sessions_mutex);
1108
        g_hash_table_insert(sessions, handle, session);
1109
        janus_mutex_unlock(&sessions_mutex);
1110

    
1111

    
1112
        return;
1113
}
1114

    
1115
void janus_sipre_destroy_session(janus_plugin_session *handle, int *error) {
1116
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
1117
                *error = -1;
1118
                return;
1119
        }
1120
        janus_sipre_session *session = (janus_sipre_session *)handle->plugin_handle;
1121
        if(!session) {
1122
                JANUS_LOG(LOG_ERR, "No SIPre session associated with this handle...\n");
1123
                *error = -2;
1124
                return;
1125
        }
1126
        janus_mutex_lock(&sessions_mutex);
1127
        if(!session->destroyed) {
1128
                g_hash_table_remove(sessions, handle);
1129
                janus_sipre_hangup_media(handle);
1130
                session->destroyed = janus_get_monotonic_time();
1131
                JANUS_LOG(LOG_VERB, "Destroying SIPre session (%s)...\n", session->account.username ? session->account.username : "unregistered user");
1132
                /* Destroy re-related stuff for this SIP session */
1133
                mqueue_push(mq, janus_sipre_mqueue_event_do_destroy, janus_sipre_mqueue_payload_create(session, NULL, 0, NULL));
1134
                /* Cleaning up and removing the session is done in a lazy way */
1135
                old_sessions = g_list_append(old_sessions, session);
1136
        }
1137
        janus_mutex_unlock(&sessions_mutex);
1138
        return;
1139
}
1140

    
1141
json_t *janus_sipre_query_session(janus_plugin_session *handle) {
1142
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
1143
                return NULL;
1144
        }
1145
        janus_sipre_session *session = (janus_sipre_session *)handle->plugin_handle;
1146
        if(!session) {
1147
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1148
                return NULL;
1149
        }
1150
        /* Provide some generic info, e.g., if we're in a call and with whom */
1151
        json_t *info = json_object();
1152
        json_object_set_new(info, "username", session->account.username ? json_string(session->account.username) : NULL);
1153
        json_object_set_new(info, "display_name", session->account.display_name ? json_string(session->account.display_name) : NULL);
1154
        json_object_set_new(info, "user_agent", session->account.user_agent ? json_string(session->account.user_agent) : NULL);
1155
        json_object_set_new(info, "identity", session->account.identity ? json_string(session->account.identity) : NULL);
1156
        json_object_set_new(info, "registration_status", json_string(janus_sipre_registration_status_string(session->account.registration_status)));
1157
        json_object_set_new(info, "call_status", json_string(janus_sipre_call_status_string(session->status)));
1158
        if(session->callee) {
1159
                json_object_set_new(info, "callee", json_string(session->callee ? session->callee : "??"));
1160
                json_object_set_new(info, "auto-ack", json_string(session->media.autoack ? "yes" : "no"));
1161
                json_object_set_new(info, "srtp-required", json_string(session->media.require_srtp ? "yes" : "no"));
1162
                json_object_set_new(info, "sdes-local", json_string(session->media.has_srtp_local ? "yes" : "no"));
1163
                json_object_set_new(info, "sdes-remote", json_string(session->media.has_srtp_remote ? "yes" : "no"));
1164
        }
1165
        if(session->arc || session->vrc || session->arc_peer || session->vrc_peer) {
1166
                json_t *recording = json_object();
1167
                if(session->arc && session->arc->filename)
1168
                        json_object_set_new(recording, "audio", json_string(session->arc->filename));
1169
                if(session->vrc && session->vrc->filename)
1170
                        json_object_set_new(recording, "video", json_string(session->vrc->filename));
1171
                if(session->arc_peer && session->arc_peer->filename)
1172
                        json_object_set_new(recording, "audio-peer", json_string(session->arc_peer->filename));
1173
                if(session->vrc_peer && session->vrc_peer->filename)
1174
                        json_object_set_new(recording, "video-peer", json_string(session->vrc_peer->filename));
1175
                json_object_set_new(info, "recording", recording);
1176
        }
1177
        json_object_set_new(info, "destroyed", json_integer(session->destroyed));
1178
        return info;
1179
}
1180

    
1181
struct janus_plugin_result *janus_sipre_handle_message(janus_plugin_session *handle, char *transaction, json_t *message, json_t *jsep) {
1182
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
1183
                return janus_plugin_result_new(JANUS_PLUGIN_ERROR, g_atomic_int_get(&stopping) ? "Shutting down" : "Plugin not initialized", NULL);
1184
        janus_sipre_message *msg = g_malloc0(sizeof(janus_sipre_message));
1185
        msg->handle = handle;
1186
        msg->transaction = transaction;
1187
        msg->message = message;
1188
        msg->jsep = jsep;
1189
        g_async_queue_push(messages, msg);
1190

    
1191
        /* All the requests to this plugin are handled asynchronously */
1192
        return janus_plugin_result_new(JANUS_PLUGIN_OK_WAIT, NULL, NULL);
1193
}
1194

    
1195
void janus_sipre_setup_media(janus_plugin_session *handle) {
1196
        JANUS_LOG(LOG_INFO, "WebRTC media is now available\n");
1197
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
1198
                return;
1199
        janus_sipre_session *session = (janus_sipre_session *)handle->plugin_handle;
1200
        if(!session) {
1201
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1202
                return;
1203
        }
1204
        if(session->destroyed)
1205
                return;
1206
        g_atomic_int_set(&session->hangingup, 0);
1207
        /* TODO Only relay RTP/RTCP when we get this event */
1208
}
1209

    
1210
void janus_sipre_incoming_rtp(janus_plugin_session *handle, int video, char *buf, int len) {
1211
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
1212
                return;
1213
        if(gateway) {
1214
                /* Honour the audio/video active flags */
1215
                janus_sipre_session *session = (janus_sipre_session *)handle->plugin_handle;
1216
                if(!session || session->destroyed) {
1217
                        JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1218
                        return;
1219
                }
1220
                /* Forward to our SIPre peer */
1221
                if((video && !session->media.video_send) || (!video && !session->media.audio_send)) {
1222
                        /* Dropping packet, peer doesn't want to receive it */
1223
                        return;
1224
                }
1225
                if((video && session->media.video_ssrc == 0) || (!video && session->media.audio_ssrc == 0)) {
1226
                        rtp_header *header = (rtp_header *)buf;
1227
                        if(video) {
1228
                                session->media.video_ssrc = ntohl(header->ssrc);
1229
                        } else {
1230
                                session->media.audio_ssrc = ntohl(header->ssrc);
1231
                        }
1232
                        JANUS_LOG(LOG_VERB, "[SIPre-%s] Got SIPre %s SSRC: %"SCNu32"\n",
1233
                                session->account.username ? session->account.username : "unknown",
1234
                                video ? "video" : "audio",
1235
                                video ? session->media.video_ssrc : session->media.audio_ssrc);
1236
                }
1237
                if((video && session->media.has_video && session->media.video_rtp_fd) ||
1238
                                (!video && session->media.has_audio && session->media.audio_rtp_fd)) {
1239
                        /* Save the frame if we're recording */
1240
                        janus_recorder_save_frame(video ? session->vrc : session->arc, buf, len);
1241
                        /* Is SRTP involved? */
1242
                        if(session->media.has_srtp_local) {
1243
                                char sbuf[2048];
1244
                                memcpy(&sbuf, buf, len);
1245
                                int protected = len;
1246
                                int res = srtp_protect(
1247
                                        (video ? session->media.video_srtp_out : session->media.audio_srtp_out),
1248
                                        &sbuf, &protected);
1249
                                if(res != srtp_err_status_ok) {
1250
                                        rtp_header *header = (rtp_header *)&sbuf;
1251
                                        guint32 timestamp = ntohl(header->timestamp);
1252
                                        guint16 seq = ntohs(header->seq_number);
1253
                                        JANUS_LOG(LOG_ERR, "[SIPre-%s] %s SRTP protect error... %s (len=%d-->%d, ts=%"SCNu32", seq=%"SCNu16")...\n",
1254
                                                session->account.username ? session->account.username : "unknown",
1255
                                                video ? "Video" : "Audio", janus_srtp_error_str(res), len, protected, timestamp, seq);
1256
                                } else {
1257
                                        /* Forward the frame to the peer */
1258
                                        send((video ? session->media.video_rtp_fd : session->media.audio_rtp_fd), sbuf, protected, 0);
1259
                                }
1260
                        } else {
1261
                                /* Forward the frame to the peer */
1262
                                send((video ? session->media.video_rtp_fd : session->media.audio_rtp_fd), buf, len, 0);
1263
                        }
1264
                }
1265
        }
1266
}
1267

    
1268
void janus_sipre_incoming_rtcp(janus_plugin_session *handle, int video, char *buf, int len) {
1269
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
1270
                return;
1271
        if(gateway) {
1272
                janus_sipre_session *session = (janus_sipre_session *)handle->plugin_handle;
1273
                if(!session || session->destroyed) {
1274
                        JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1275
                        return;
1276
                }
1277
                /* Forward to our SIPre peer */
1278
                if((video && session->media.has_video && session->media.video_rtcp_fd) ||
1279
                                (!video && session->media.has_audio && session->media.audio_rtcp_fd)) {
1280
                        /* Fix SSRCs as the gateway does */
1281
                        JANUS_LOG(LOG_HUGE, "[SIPre-%s] Fixing %s SSRCs (local %u, peer %u)\n",
1282
                                session->account.username ? session->account.username : "unknown",
1283
                                video ? "video" : "audio",
1284
                                (video ? session->media.video_ssrc : session->media.audio_ssrc),
1285
                                (video ? session->media.video_ssrc_peer : session->media.audio_ssrc_peer));
1286
                        janus_rtcp_fix_ssrc(NULL, (char *)buf, len, video,
1287
                                (video ? session->media.video_ssrc : session->media.audio_ssrc),
1288
                                (video ? session->media.video_ssrc_peer : session->media.audio_ssrc_peer));
1289
                        /* Is SRTP involved? */
1290
                        if(session->media.has_srtp_local) {
1291
                                char sbuf[2048];
1292
                                memcpy(&sbuf, buf, len);
1293
                                int protected = len;
1294
                                int res = srtp_protect_rtcp(
1295
                                        (video ? session->media.video_srtp_out : session->media.audio_srtp_out),
1296
                                        &sbuf, &protected);
1297
                                if(res != srtp_err_status_ok) {
1298
                                        JANUS_LOG(LOG_ERR, "[SIPre-%s] %s SRTCP protect error... %s (len=%d-->%d)...\n",
1299
                                                session->account.username ? session->account.username : "unknown",
1300
                                                video ? "Video" : "Audio",
1301
                                                janus_srtp_error_str(res), len, protected);
1302
                                } else {
1303
                                        /* Forward the message to the peer */
1304
                                        send((video ? session->media.video_rtcp_fd : session->media.audio_rtcp_fd), sbuf, protected, 0);
1305
                                }
1306
                        } else {
1307
                                /* Forward the message to the peer */
1308
                                send((video ? session->media.video_rtcp_fd : session->media.audio_rtcp_fd), buf, len, 0);
1309
                        }
1310
                }
1311
        }
1312
}
1313

    
1314
void janus_sipre_hangup_media(janus_plugin_session *handle) {
1315
        JANUS_LOG(LOG_INFO, "No WebRTC media anymore\n");
1316
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
1317
                return;
1318
        janus_sipre_session *session = (janus_sipre_session *)handle->plugin_handle;
1319
        if(!session) {
1320
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1321
                return;
1322
        }
1323
        if(session->destroyed)
1324
                return;
1325
        if(g_atomic_int_add(&session->hangingup, 1))
1326
                return;
1327
        if(!(session->status == janus_sipre_call_status_inviting ||
1328
                 session->status == janus_sipre_call_status_invited ||
1329
                 session->status == janus_sipre_call_status_incall))
1330
                return;
1331
        session->media.ready = FALSE;
1332
        session->media.on_hold = FALSE;
1333
        session->status = janus_sipre_call_status_closing;
1334
        /* Enqueue the BYE */
1335
        mqueue_push(mq, janus_sipre_mqueue_event_do_bye, janus_sipre_mqueue_payload_create(session, NULL, 0, NULL));
1336
        /* Get rid of the recorders, if available */
1337
        janus_mutex_lock(&session->rec_mutex);
1338
        if(session->arc) {
1339
                janus_recorder_close(session->arc);
1340
                JANUS_LOG(LOG_INFO, "Closed user's audio recording %s\n", session->arc->filename ? session->arc->filename : "??");
1341
                janus_recorder_free(session->arc);
1342
        }
1343
        session->arc = NULL;
1344
        if(session->arc_peer) {
1345
                janus_recorder_close(session->arc_peer);
1346
                JANUS_LOG(LOG_INFO, "Closed peer's audio recording %s\n", session->arc_peer->filename ? session->arc_peer->filename : "??");
1347
                janus_recorder_free(session->arc_peer);
1348
        }
1349
        session->arc_peer = NULL;
1350
        if(session->vrc) {
1351
                janus_recorder_close(session->vrc);
1352
                JANUS_LOG(LOG_INFO, "Closed user's video recording %s\n", session->vrc->filename ? session->vrc->filename : "??");
1353
                janus_recorder_free(session->vrc);
1354
        }
1355
        session->vrc = NULL;
1356
        if(session->vrc_peer) {
1357
                janus_recorder_close(session->vrc_peer);
1358
                JANUS_LOG(LOG_INFO, "Closed peer's video recording %s\n", session->vrc_peer->filename ? session->vrc_peer->filename : "??");
1359
                janus_recorder_free(session->vrc_peer);
1360
        }
1361
        session->vrc_peer = NULL;
1362
        janus_mutex_unlock(&session->rec_mutex);
1363
}
1364

    
1365
/* Thread to handle incoming messages */
1366
static void *janus_sipre_handler(void *data) {
1367
        JANUS_LOG(LOG_VERB, "Joining SIPre handler thread\n");
1368
        janus_sipre_message *msg = NULL;
1369
        int error_code = 0;
1370
        char error_cause[512];
1371
        json_t *root = NULL;
1372
        while(g_atomic_int_get(&initialized) && !g_atomic_int_get(&stopping)) {
1373
                msg = g_async_queue_pop(messages);
1374
                if(msg == NULL)
1375
                        continue;
1376
                if(msg == &exit_message)
1377
                        break;
1378
                if(msg->handle == NULL) {
1379
                        janus_sipre_message_free(msg);
1380
                        continue;
1381
                }
1382
                janus_sipre_session *session = NULL;
1383
                janus_mutex_lock(&sessions_mutex);
1384
                if(g_hash_table_lookup(sessions, msg->handle) != NULL ) {
1385
                        session = (janus_sipre_session *)msg->handle->plugin_handle;
1386
                }
1387
                janus_mutex_unlock(&sessions_mutex);
1388
                if(!session) {
1389
                        JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1390
                        janus_sipre_message_free(msg);
1391
                        continue;
1392
                }
1393
                if(session->destroyed) {
1394
                        janus_sipre_message_free(msg);
1395
                        continue;
1396
                }
1397
                /* Handle request */
1398
                error_code = 0;
1399
                root = msg->message;
1400
                if(msg->message == NULL) {
1401
                        JANUS_LOG(LOG_ERR, "No message??\n");
1402
                        error_code = JANUS_SIPRE_ERROR_NO_MESSAGE;
1403
                        g_snprintf(error_cause, 512, "%s", "No message??");
1404
                        goto error;
1405
                }
1406
                if(!json_is_object(root)) {
1407
                        JANUS_LOG(LOG_ERR, "JSON error: not an object\n");
1408
                        error_code = JANUS_SIPRE_ERROR_INVALID_JSON;
1409
                        g_snprintf(error_cause, 512, "JSON error: not an object");
1410
                        goto error;
1411
                }
1412
                JANUS_VALIDATE_JSON_OBJECT(root, request_parameters,
1413
                        error_code, error_cause, TRUE,
1414
                        JANUS_SIPRE_ERROR_MISSING_ELEMENT, JANUS_SIPRE_ERROR_INVALID_ELEMENT);
1415
                if(error_code != 0)
1416
                        goto error;
1417
                json_t *request = json_object_get(root, "request");
1418
                const char *request_text = json_string_value(request);
1419
                json_t *result = NULL;
1420

    
1421
                if(!strcasecmp(request_text, "register")) {
1422
                        /* Send a REGISTER */
1423
                        if(session->account.registration_status > janus_sipre_registration_status_unregistered) {
1424
                                JANUS_LOG(LOG_ERR, "Already registered (%s)\n", session->account.username);
1425
                                error_code = JANUS_SIPRE_ERROR_ALREADY_REGISTERED;
1426
                                g_snprintf(error_cause, 512, "Already registered (%s)", session->account.username);
1427
                                goto error;
1428
                        }
1429

    
1430
                        /* Cleanup old values */
1431
                        if(session->account.identity != NULL) {
1432
                                g_hash_table_remove(identities, session->account.identity);
1433
                                g_free(session->account.identity);
1434
                        }
1435
                        session->account.identity = NULL;
1436
                        session->account.sips = TRUE;
1437
                        if(session->account.username != NULL)
1438
                                g_free(session->account.username);
1439
                        session->account.username = NULL;
1440
                        if(session->account.display_name != NULL)
1441
                                g_free(session->account.display_name);
1442
                        session->account.display_name = NULL;
1443
                        if(session->account.authuser != NULL)
1444
                                g_free(session->account.authuser);
1445
                        session->account.authuser = NULL;
1446
                        if(session->account.secret != NULL)
1447
                                g_free(session->account.secret);
1448
                        session->account.secret = NULL;
1449
                        session->account.secret_type = janus_sipre_secret_type_unknown;
1450
                        if(session->account.proxy != NULL)
1451
                                g_free(session->account.proxy);
1452
                        session->account.proxy = NULL;
1453
                        if(session->account.user_agent != NULL)
1454
                                g_free(session->account.user_agent);
1455
                        session->account.user_agent = NULL;
1456
                        session->account.registration_status = janus_sipre_registration_status_unregistered;
1457

    
1458
                        gboolean guest = FALSE;
1459
                        JANUS_VALIDATE_JSON_OBJECT(root, register_parameters,
1460
                                error_code, error_cause, TRUE,
1461
                                JANUS_SIPRE_ERROR_MISSING_ELEMENT, JANUS_SIPRE_ERROR_INVALID_ELEMENT);
1462
                        if(error_code != 0)
1463
                                goto error;
1464
                        json_t *type = json_object_get(root, "type");
1465
                        if(type != NULL) {
1466
                                const char *type_text = json_string_value(type);
1467
                                if(!strcmp(type_text, "guest")) {
1468
                                        JANUS_LOG(LOG_INFO, "Registering as a guest\n");
1469
                                        guest = TRUE;
1470
                                } else {
1471
                                        JANUS_LOG(LOG_WARN, "Unknown type '%s', ignoring...\n", type_text);
1472
                                }
1473
                        }
1474

    
1475
                        gboolean send_register = TRUE;
1476
                        json_t *do_register = json_object_get(root, "send_register");
1477
                        if(do_register != NULL) {
1478
                                if(guest) {
1479
                                        JANUS_LOG(LOG_ERR, "Conflicting elements: send_register cannot be true if guest is true\n");
1480
                                        error_code = JANUS_SIPRE_ERROR_INVALID_ELEMENT;
1481
                                        g_snprintf(error_cause, 512, "Conflicting elements: send_register cannot be true if guest is true");
1482
                                        goto error;
1483
                                }
1484
                                send_register = json_is_true(do_register);
1485
                        }
1486

    
1487
                        gboolean sips = TRUE;
1488
                        json_t *do_sipres = json_object_get(root, "sips");
1489
                        if(do_sipres != NULL) {
1490
                                sips = json_is_true(do_sipres);
1491
                        }
1492

    
1493
                        /* Parse address */
1494
                        json_t *proxy = json_object_get(root, "proxy");
1495
                        const char *proxy_text = NULL;
1496
                        if(proxy && !json_is_null(proxy)) {
1497
                                /* Has to be validated separately because it could be null */
1498
                                JANUS_VALIDATE_JSON_OBJECT(root, proxy_parameters,
1499
                                        error_code, error_cause, TRUE,
1500
                                        JANUS_SIPRE_ERROR_MISSING_ELEMENT, JANUS_SIPRE_ERROR_INVALID_ELEMENT);
1501
                                if(error_code != 0)
1502
                                        goto error;
1503
                                proxy_text = json_string_value(proxy);
1504
                                if(janus_sipre_parse_uri(proxy_text) < 0) {
1505
                                        JANUS_LOG(LOG_ERR, "Invalid proxy address %s\n", proxy_text);
1506
                                        error_code = JANUS_SIPRE_ERROR_INVALID_ADDRESS;
1507
                                        g_snprintf(error_cause, 512, "Invalid proxy address %s\n", proxy_text);
1508
                                        goto error;
1509
                                }
1510
                        }
1511

    
1512
                        /* Parse register TTL */
1513
                        int ttl = register_ttl;
1514
                        json_t *reg_ttl = json_object_get(root, "register_ttl");
1515
                        if(reg_ttl && json_is_integer(reg_ttl))
1516
                                ttl = json_integer_value(reg_ttl);
1517
                        if(ttl <= 0)
1518
                                ttl = JANUS_DEFAULT_REGISTER_TTL;
1519
                        session->stack.expires = ttl;
1520

    
1521
                        /* Parse display name */
1522
                        const char* display_name_text = NULL;
1523
                        json_t *display_name = json_object_get(root, "display_name");
1524
                        if(display_name && json_is_string(display_name))
1525
                                display_name_text = json_string_value(display_name);
1526

    
1527
                        /* Parse user agent */
1528
                        const char* user_agent_text = NULL;
1529
                        json_t *user_agent = json_object_get(root, "user_agent");
1530
                        if(user_agent && json_is_string(user_agent))
1531
                                user_agent_text = json_string_value(user_agent);
1532

    
1533
                        /* Now the user part (always needed, even for the guest case) */
1534
                        json_t *username = json_object_get(root, "username");
1535
                        if(!username) {
1536
                                /* The username is mandatory even when registering as guests */
1537
                                JANUS_LOG(LOG_ERR, "Missing element (username)\n");
1538
                                error_code = JANUS_SIPRE_ERROR_MISSING_ELEMENT;
1539
                                g_snprintf(error_cause, 512, "Missing element (username)");
1540
                                goto error;
1541
                        }
1542
                        const char *username_text = NULL;
1543
                        char *user_id = NULL, *user_host = NULL;
1544
                        guint16 user_port = 0;
1545
                        /* Parse address */
1546
                        username_text = json_string_value(username);
1547
                        if(janus_sipre_parse_uri(username_text) < 0) {
1548
                                JANUS_LOG(LOG_ERR, "Invalid user address %s\n", username_text);
1549
                                error_code = JANUS_SIPRE_ERROR_INVALID_ADDRESS;
1550
                                g_snprintf(error_cause, 512, "Invalid user address %s\n", username_text);
1551
                                goto error;
1552
                        }
1553
                        user_id = janus_sipre_get_uri_username(username_text);
1554
                        user_host = janus_sipre_get_uri_host(username_text);
1555
                        user_port = janus_sipre_get_uri_port(username_text);
1556
                        if(guest) {
1557
                                /* Not needed, we can stop here: just say we're registered */
1558
                                JANUS_LOG(LOG_INFO, "Guest will have username %s\n", user_id);
1559
                                send_register = FALSE;
1560
                        } else {
1561
                                json_t *secret = json_object_get(root, "secret");
1562
                                json_t *ha1_secret = json_object_get(root, "ha1_secret");
1563
                                json_t *authuser = json_object_get(root, "authuser");
1564
                                if(!secret && !ha1_secret) {
1565
                                        g_free(user_id);
1566
                                        g_free(user_host);
1567
                                        JANUS_LOG(LOG_ERR, "Missing element (secret or ha1_secret)\n");
1568
                                        error_code = JANUS_SIPRE_ERROR_MISSING_ELEMENT;
1569
                                        g_snprintf(error_cause, 512, "Missing element (secret or ha1_secret)");
1570
                                        goto error;
1571
                                }
1572
                                if(secret && ha1_secret) {
1573
                                        g_free(user_id);
1574
                                        g_free(user_host);
1575
                                        JANUS_LOG(LOG_ERR, "Conflicting elements specified (secret and ha1_secret)\n");
1576
                                        error_code = JANUS_SIPRE_ERROR_INVALID_ELEMENT;
1577
                                        g_snprintf(error_cause, 512, "Conflicting elements specified (secret and ha1_secret)");
1578
                                        goto error;
1579
                                }
1580
                                const char *secret_text;
1581
                                if(secret) {
1582
                                        secret_text = json_string_value(secret);
1583
                                        session->account.secret = g_strdup(secret_text);
1584
                                        session->account.secret_type = janus_sipre_secret_type_plaintext;
1585
                                } else {
1586
                                        secret_text = json_string_value(ha1_secret);
1587
                                        session->account.secret = g_strdup(secret_text);
1588
                                        session->account.secret_type = janus_sipre_secret_type_hashed;
1589
                                }
1590
                                if(authuser) {
1591
                                        const char *authuser_text;
1592
                                        authuser_text = json_string_value(authuser);
1593
                                        session->account.authuser = g_strdup(authuser_text);
1594
                                } else {
1595
                                        session->account.authuser = g_strdup(user_id);
1596
                                }
1597
                                /* Got the values, try registering now */
1598
                                JANUS_LOG(LOG_VERB, "Registering user %s (secret %s) @ %s through %s\n",
1599
                                        user_id, secret_text, user_host, proxy_text != NULL ? proxy_text : "(null)");
1600
                        }
1601

    
1602
                        session->account.identity = g_strdup(username_text);
1603
                        g_hash_table_insert(identities, session->account.identity, session);
1604
                        session->account.sips = sips;
1605
                        session->account.username = g_strdup(user_id);
1606
                        if(display_name_text) {
1607
                                session->account.display_name = g_strdup(display_name_text);
1608
                        }
1609
                        if(user_agent_text) {
1610
                                session->account.user_agent = g_strdup(user_agent_text);
1611
                        }
1612
                        if(proxy_text) {
1613
                                session->account.proxy = g_strdup(proxy_text);
1614
                        } else {
1615
                                /* Build one from the user's identity */
1616
                                char uri[256];
1617
                                g_snprintf(uri, sizeof(uri), "sip:%s:%"SCNu16, user_host, (user_port ? user_port : 5060));
1618
                                session->account.proxy = g_strdup(uri);
1619
                        }
1620
                        g_free(user_host);
1621
                        g_free(user_id);
1622

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

    
2384
                /* Prepare JSON event */
2385
                json_t *event = json_object();
2386
                json_object_set_new(event, "sip", json_string("event"));
2387
                if(result != NULL)
2388
                        json_object_set_new(event, "result", result);
2389
                int ret = gateway->push_event(msg->handle, &janus_sipre_plugin, msg->transaction, event, NULL);
2390
                JANUS_LOG(LOG_VERB, "  >> Pushing event: %d (%s)\n", ret, janus_get_api_error(ret));
2391
                json_decref(event);
2392
                janus_sipre_message_free(msg);
2393
                continue;
2394

    
2395
error:
2396
                {
2397
                        /* Prepare JSON error event */
2398
                        json_t *event = json_object();
2399
                        json_object_set_new(event, "sip", json_string("event"));
2400
                        json_object_set_new(event, "error_code", json_integer(error_code));
2401
                        json_object_set_new(event, "error", json_string(error_cause));
2402
                        int ret = gateway->push_event(msg->handle, &janus_sipre_plugin, msg->transaction, event, NULL);
2403
                        JANUS_LOG(LOG_VERB, "  >> Pushing event: %d (%s)\n", ret, janus_get_api_error(ret));
2404
                        json_decref(event);
2405
                        janus_sipre_message_free(msg);
2406
                }
2407
        }
2408
        JANUS_LOG(LOG_VERB, "Leaving SIPre handler thread\n");
2409
        return NULL;
2410
}
2411

    
2412

    
2413
/* Process an incoming SDP */
2414
void janus_sipre_sdp_process(janus_sipre_session *session, janus_sdp *sdp, gboolean answer, gboolean update, gboolean *changed) {
2415
        if(!session || !sdp)
2416
                return;
2417
        /* c= */
2418
        if(sdp->c_addr) {
2419
                if(update && strcmp(sdp->c_addr, session->media.remote_ip)) {
2420
                        /* This is an update and an address changed */
2421
                        if(changed)
2422
                                *changed = TRUE;
2423
                }
2424
                g_free(session->media.remote_ip);
2425
                session->media.remote_ip = g_strdup(sdp->c_addr);
2426
        }
2427
        GList *temp = sdp->m_lines;
2428
        while(temp) {
2429
                janus_sdp_mline *m = (janus_sdp_mline *)temp->data;
2430
                session->media.require_srtp = session->media.require_srtp || (m->proto && !strcasecmp(m->proto, "RTP/SAVP"));
2431
                if(m->type == JANUS_SDP_AUDIO) {
2432
                        if(m->port) {
2433
                                if(m->port != session->media.remote_audio_rtp_port) {
2434
                                        /* This is an update and an address changed */
2435
                                        if(changed)
2436
                                                *changed = TRUE;
2437
                                }
2438
                                session->media.has_audio = TRUE;
2439
                                session->media.remote_audio_rtp_port = m->port;
2440
                                session->media.remote_audio_rtcp_port = m->port+1;        /* FIXME We're assuming RTCP is on the next port */
2441
                                if(m->direction == JANUS_SDP_SENDONLY || m->direction == JANUS_SDP_INACTIVE)
2442
                                        session->media.audio_send = FALSE;
2443
                                else
2444
                                        session->media.audio_send = TRUE;
2445
                        } else {
2446
                                session->media.audio_send = FALSE;
2447
                        }
2448
                } else if(m->type == JANUS_SDP_VIDEO) {
2449
                        if(m->port) {
2450
                                if(m->port != session->media.remote_video_rtp_port) {
2451
                                        /* This is an update and an address changed */
2452
                                        if(changed)
2453
                                                *changed = TRUE;
2454
                                }
2455
                                session->media.has_video = TRUE;
2456
                                session->media.remote_video_rtp_port = m->port;
2457
                                session->media.remote_video_rtcp_port = m->port+1;        /* FIXME We're assuming RTCP is on the next port */
2458
                                if(m->direction == JANUS_SDP_SENDONLY || m->direction == JANUS_SDP_INACTIVE)
2459
                                        session->media.video_send = FALSE;
2460
                                else
2461
                                        session->media.video_send = TRUE;
2462
                        } else {
2463
                                session->media.video_send = FALSE;
2464
                        }
2465
                } else {
2466
                        JANUS_LOG(LOG_WARN, "Unsupported media line (not audio/video)\n");
2467
                        temp = temp->next;
2468
                        continue;
2469
                }
2470
                if(m->c_addr) {
2471
                        if(update && strcmp(m->c_addr, session->media.remote_ip)) {
2472
                                /* This is an update and an address changed */
2473
                                if(changed)
2474
                                        *changed = TRUE;
2475
                        }
2476
                        g_free(session->media.remote_ip);
2477
                        session->media.remote_ip = g_strdup(m->c_addr);
2478
                }
2479
                if(update) {
2480
                        /* FIXME This is a session update, we only accept changes in IP/ports */
2481
                        temp = temp->next;
2482
                        continue;
2483
                }
2484
                GList *tempA = m->attributes;
2485
                while(tempA) {
2486
                        janus_sdp_attribute *a = (janus_sdp_attribute *)tempA->data;
2487
                        if(a->name) {
2488
                                if(!strcasecmp(a->name, "crypto")) {
2489
                                        if(m->type == JANUS_SDP_AUDIO || m->type == JANUS_SDP_VIDEO) {
2490
                                                gint32 tag = 0;
2491
                                                int suite;
2492
                                                char crypto[81];
2493
                                                /* FIXME inline can be more complex than that, and we're currently only offering SHA1_80 */
2494
                                                int res = sscanf(a->value, "%"SCNi32" AES_CM_128_HMAC_SHA1_%2d inline:%80s",
2495
                                                        &tag, &suite, crypto);
2496
                                                if(res != 3) {
2497
                                                        JANUS_LOG(LOG_WARN, "Failed to parse crypto line, ignoring... %s\n", a->value);
2498
                                                } else {
2499
                                                        gboolean video = (m->type == JANUS_SDP_VIDEO);
2500
                                                        int current_suite = video ? session->media.video_srtp_suite_in : session->media.audio_srtp_suite_in;
2501
                                                        if(current_suite == 0) {
2502
                                                                if(video)
2503
                                                                        session->media.video_srtp_suite_in = suite;
2504
                                                                else
2505
                                                                        session->media.audio_srtp_suite_in = suite;
2506
                                                                janus_sipre_srtp_set_remote(session, video, crypto, suite);
2507
                                                                session->media.has_srtp_remote = TRUE;
2508
                                                        } else {
2509
                                                                JANUS_LOG(LOG_WARN, "We already configured a %s crypto context (AES_CM_128_HMAC_SHA1_%d), skipping additional crypto line\n",
2510
                                                                        video ? "video" : "audio", current_suite);
2511
                                                        }
2512
                                                }
2513
                                        }
2514
                                }
2515
                        }
2516
                        tempA = tempA->next;
2517
                }
2518
                if(answer && (m->type == JANUS_SDP_AUDIO || m->type == JANUS_SDP_VIDEO)) {
2519
                        /* Check which codec was negotiated eventually */
2520
                        int pt = -1;
2521
                        if(m->ptypes)
2522
                                pt = GPOINTER_TO_INT(m->ptypes->data);
2523
                        if(pt > -1) {
2524
                                if(m->type == JANUS_SDP_AUDIO) {
2525
                                        session->media.audio_pt = pt;
2526
                                } else {
2527
                                        session->media.video_pt = pt;
2528
                                }
2529
                        }
2530
                }
2531
                temp = temp->next;
2532
        }
2533
        if(update && changed && *changed) {
2534
                /* Something changed: mark this on the session, so that the thread can update the sockets */
2535
                session->media.updated = TRUE;
2536
                if(session->media.pipefd[1] > 0) {
2537
                        int code = 1;
2538
                        ssize_t res = 0;
2539
                        do {
2540
                                res = write(session->media.pipefd[1], &code, sizeof(int));
2541
                        } while(res == -1 && errno == EINTR);
2542
                }
2543
        }
2544
}
2545

    
2546
char *janus_sipre_sdp_manipulate(janus_sipre_session *session, janus_sdp *sdp, gboolean answer) {
2547
        if(!session || !sdp)
2548
                return NULL;
2549
        /* Start replacing stuff */
2550
        JANUS_LOG(LOG_VERB, "Setting protocol to %s\n", session->media.require_srtp ? "RTP/SAVP" : "RTP/AVP");
2551
        GList *temp = sdp->m_lines;
2552
        while(temp) {
2553
                janus_sdp_mline *m = (janus_sdp_mline *)temp->data;
2554
                g_free(m->proto);
2555
                m->proto = g_strdup(session->media.require_srtp ? "RTP/SAVP" : "RTP/AVP");
2556
                if(m->type == JANUS_SDP_AUDIO) {
2557
                        m->port = session->media.local_audio_rtp_port;
2558
                        if(session->media.has_srtp_local) {
2559
                                char *crypto = NULL;
2560
                                session->media.audio_srtp_suite_out = 80;
2561
                                janus_sipre_srtp_set_local(session, FALSE, &crypto);
2562
                                /* FIXME 32? 80? Both? */
2563
                                janus_sdp_attribute *a = janus_sdp_attribute_create("crypto", "1 AES_CM_128_HMAC_SHA1_80 inline:%s", crypto);
2564
                                g_free(crypto);
2565
                                m->attributes = g_list_append(m->attributes, a);
2566
                        }
2567
                } else if(m->type == JANUS_SDP_VIDEO) {
2568
                        m->port = session->media.local_video_rtp_port;
2569
                        if(session->media.has_srtp_local) {
2570
                                char *crypto = NULL;
2571
                                session->media.audio_srtp_suite_out = 80;
2572
                                janus_sipre_srtp_set_local(session, TRUE, &crypto);
2573
                                /* FIXME 32? 80? Both? */
2574
                                janus_sdp_attribute *a = janus_sdp_attribute_create("crypto", "1 AES_CM_128_HMAC_SHA1_80 inline:%s", crypto);
2575
                                g_free(crypto);
2576
                                m->attributes = g_list_append(m->attributes, a);
2577
                        }
2578
                }
2579
                g_free(m->c_addr);
2580
                m->c_addr = g_strdup(local_ip);
2581
                if(answer && (m->type == JANUS_SDP_AUDIO || m->type == JANUS_SDP_VIDEO)) {
2582
                        /* Check which codec was negotiated eventually */
2583
                        int pt = -1;
2584
                        if(m->ptypes)
2585
                                pt = GPOINTER_TO_INT(m->ptypes->data);
2586
                        if(pt > -1) {
2587
                                if(m->type == JANUS_SDP_AUDIO) {
2588
                                        session->media.audio_pt = pt;
2589
                                } else {
2590
                                        session->media.video_pt = pt;
2591
                                }
2592
                        }
2593
                }
2594
                temp = temp->next;
2595
        }
2596
        /* Generate a SDP string out of our changes */
2597
        return janus_sdp_write(sdp);
2598
}
2599

    
2600
/* Bind local RTP/RTCP sockets */
2601
static int janus_sipre_allocate_local_ports(janus_sipre_session *session) {
2602
        if(session == NULL) {
2603
                JANUS_LOG(LOG_ERR, "Invalid session\n");
2604
                return -1;
2605
        }
2606
        /* Reset status */
2607
        if(session->media.audio_rtp_fd != -1) {
2608
                close(session->media.audio_rtp_fd);
2609
                session->media.audio_rtp_fd = -1;
2610
        }
2611
        if(session->media.audio_rtcp_fd != -1) {
2612
                close(session->media.audio_rtcp_fd);
2613
                session->media.audio_rtcp_fd = -1;
2614
        }
2615
        session->media.local_audio_rtp_port = 0;
2616
        session->media.local_audio_rtcp_port = 0;
2617
        session->media.audio_ssrc = 0;
2618
        if(session->media.video_rtp_fd != -1) {
2619
                close(session->media.video_rtp_fd);
2620
                session->media.video_rtp_fd = -1;
2621
        }
2622
        if(session->media.video_rtcp_fd != -1) {
2623
                close(session->media.video_rtcp_fd);
2624
                session->media.video_rtcp_fd = -1;
2625
        }
2626
        session->media.local_video_rtp_port = 0;
2627
        session->media.local_video_rtcp_port = 0;
2628
        session->media.video_ssrc = 0;
2629
        if(session->media.pipefd[0] > 0) {
2630
                close(session->media.pipefd[0]);
2631
                session->media.pipefd[0] = -1;
2632
        }
2633
        if(session->media.pipefd[1] > 0) {
2634
                close(session->media.pipefd[1]);
2635
                session->media.pipefd[1] = -1;
2636
        }
2637
        /* Start */
2638
        int attempts = 100;        /* FIXME Don't retry forever */
2639
        if(session->media.has_audio) {
2640
                JANUS_LOG(LOG_VERB, "Allocating audio ports:\n");
2641
                struct sockaddr_in audio_rtp_address, audio_rtcp_address;
2642
                while(session->media.local_audio_rtp_port == 0 || session->media.local_audio_rtcp_port == 0) {
2643
                        if(attempts == 0)        /* Too many failures */
2644
                                return -1;
2645
                        if(session->media.audio_rtp_fd == -1) {
2646
                                session->media.audio_rtp_fd = socket(AF_INET, SOCK_DGRAM, 0);
2647
                        }
2648
                        if(session->media.audio_rtcp_fd == -1) {
2649
                                session->media.audio_rtcp_fd = socket(AF_INET, SOCK_DGRAM, 0);
2650
                        }
2651
                        int rtp_port = g_random_int_range(10000, 60000);        /* FIXME Should this be configurable? */
2652
                        if(rtp_port % 2)
2653
                                rtp_port++;        /* Pick an even port for RTP */
2654
                        audio_rtp_address.sin_family = AF_INET;
2655
                        audio_rtp_address.sin_port = htons(rtp_port);
2656
                        inet_pton(AF_INET, local_ip, &audio_rtp_address.sin_addr.s_addr);
2657
                        if(bind(session->media.audio_rtp_fd, (struct sockaddr *)(&audio_rtp_address), sizeof(struct sockaddr)) < 0) {
2658
                                JANUS_LOG(LOG_ERR, "Bind failed for audio RTP (port %d), trying a different one...\n", rtp_port);
2659
                                attempts--;
2660
                                continue;
2661
                        }
2662
                        JANUS_LOG(LOG_VERB, "Audio RTP listener bound to port %d\n", rtp_port);
2663
                        int rtcp_port = rtp_port+1;
2664
                        audio_rtcp_address.sin_family = AF_INET;
2665
                        audio_rtcp_address.sin_port = htons(rtcp_port);
2666
                        inet_pton(AF_INET, local_ip, &audio_rtcp_address.sin_addr.s_addr);
2667
                        if(bind(session->media.audio_rtcp_fd, (struct sockaddr *)(&audio_rtcp_address), sizeof(struct sockaddr)) < 0) {
2668
                                JANUS_LOG(LOG_ERR, "Bind failed for audio RTCP (port %d), trying a different one...\n", rtcp_port);
2669
                                /* RTP socket is not valid anymore, reset it */
2670
                                close(session->media.audio_rtp_fd);
2671
                                session->media.audio_rtp_fd = -1;
2672
                                attempts--;
2673
                                continue;
2674
                        }
2675
                        JANUS_LOG(LOG_VERB, "Audio RTCP listener bound to port %d\n", rtcp_port);
2676
                        session->media.local_audio_rtp_port = rtp_port;
2677
                        session->media.local_audio_rtcp_port = rtcp_port;
2678
                }
2679
        }
2680
        if(session->media.has_video) {
2681
                JANUS_LOG(LOG_VERB, "Allocating video ports:\n");
2682
                struct sockaddr_in video_rtp_address, video_rtcp_address;
2683
                while(session->media.local_video_rtp_port == 0 || session->media.local_video_rtcp_port == 0) {
2684
                        if(attempts == 0)        /* Too many failures */
2685
                                return -1;
2686
                        if(session->media.video_rtp_fd == -1) {
2687
                                session->media.video_rtp_fd = socket(AF_INET, SOCK_DGRAM, 0);
2688
                        }
2689
                        if(session->media.video_rtcp_fd == -1) {
2690
                                session->media.video_rtcp_fd = socket(AF_INET, SOCK_DGRAM, 0);
2691
                        }
2692
                        int rtp_port = g_random_int_range(10000, 60000);        /* FIXME Should this be configurable? */
2693
                        if(rtp_port % 2)
2694
                                rtp_port++;        /* Pick an even port for RTP */
2695
                        video_rtp_address.sin_family = AF_INET;
2696
                        video_rtp_address.sin_port = htons(rtp_port);
2697
                        inet_pton(AF_INET, local_ip, &video_rtp_address.sin_addr.s_addr);
2698
                        if(bind(session->media.video_rtp_fd, (struct sockaddr *)(&video_rtp_address), sizeof(struct sockaddr)) < 0) {
2699
                                JANUS_LOG(LOG_ERR, "Bind failed for video RTP (port %d), trying a different one...\n", rtp_port);
2700
                                attempts--;
2701
                                continue;
2702
                        }
2703
                        JANUS_LOG(LOG_VERB, "Video RTP listener bound to port %d\n", rtp_port);
2704
                        int rtcp_port = rtp_port+1;
2705
                        video_rtcp_address.sin_family = AF_INET;
2706
                        video_rtcp_address.sin_port = htons(rtcp_port);
2707
                        inet_pton(AF_INET, local_ip, &video_rtcp_address.sin_addr.s_addr);
2708
                        if(bind(session->media.video_rtcp_fd, (struct sockaddr *)(&video_rtcp_address), sizeof(struct sockaddr)) < 0) {
2709
                                JANUS_LOG(LOG_ERR, "Bind failed for video RTCP (port %d), trying a different one...\n", rtcp_port);
2710
                                /* RTP socket is not valid anymore, reset it */
2711
                                close(session->media.video_rtp_fd);
2712
                                session->media.video_rtp_fd = -1;
2713
                                attempts--;
2714
                                continue;
2715
                        }
2716
                        JANUS_LOG(LOG_VERB, "Video RTCP listener bound to port %d\n", rtcp_port);
2717
                        session->media.local_video_rtp_port = rtp_port;
2718
                        session->media.local_video_rtcp_port = rtcp_port;
2719
                }
2720
        }
2721
        /* We need this to quickly interrupt the poll when it's time to update a session or wrap up */
2722
        pipe(session->media.pipefd);
2723
        return 0;
2724
}
2725

    
2726
/* Helper method to (re)connect RTP/RTCP sockets */
2727
static void janus_sipre_connect_sockets(janus_sipre_session *session, struct sockaddr_in *server_addr) {
2728
        if(!session || !server_addr)
2729
                return;
2730

    
2731
        if(session->media.updated) {
2732
                JANUS_LOG(LOG_VERB, "Updating session sockets\n");
2733
        }
2734

    
2735
        /* Connect peers (FIXME This pretty much sucks right now) */
2736
        if(session->media.remote_audio_rtp_port) {
2737
                server_addr->sin_port = htons(session->media.remote_audio_rtp_port);
2738
                if(connect(session->media.audio_rtp_fd, (struct sockaddr *)server_addr, sizeof(struct sockaddr)) == -1) {
2739
                        JANUS_LOG(LOG_ERR, "[SIPre-%s] Couldn't connect audio RTP? (%s:%d)\n", session->account.username, session->media.remote_ip, session->media.remote_audio_rtp_port);
2740
                        JANUS_LOG(LOG_ERR, "[SIPre-%s]   -- %d (%s)\n", session->account.username, errno, strerror(errno));
2741
                }
2742
        }
2743
        if(session->media.remote_audio_rtcp_port) {
2744
                server_addr->sin_port = htons(session->media.remote_audio_rtcp_port);
2745
                if(connect(session->media.audio_rtcp_fd, (struct sockaddr *)server_addr, sizeof(struct sockaddr)) == -1) {
2746
                        JANUS_LOG(LOG_ERR, "[SIPre-%s] Couldn't connect audio RTCP? (%s:%d)\n", session->account.username, session->media.remote_ip, session->media.remote_audio_rtcp_port);
2747
                        JANUS_LOG(LOG_ERR, "[SIPre-%s]   -- %d (%s)\n", session->account.username, errno, strerror(errno));
2748
                }
2749
        }
2750
        if(session->media.remote_video_rtp_port) {
2751
                server_addr->sin_port = htons(session->media.remote_video_rtp_port);
2752
                if(connect(session->media.video_rtp_fd, (struct sockaddr *)server_addr, sizeof(struct sockaddr)) == -1) {
2753
                        JANUS_LOG(LOG_ERR, "[SIPre-%s] Couldn't connect video RTP? (%s:%d)\n", session->account.username, session->media.remote_ip, session->media.remote_video_rtp_port);
2754
                        JANUS_LOG(LOG_ERR, "[SIPre-%s]   -- %d (%s)\n", session->account.username, errno, strerror(errno));
2755
                }
2756
        }
2757
        if(session->media.remote_video_rtcp_port) {
2758
                server_addr->sin_port = htons(session->media.remote_video_rtcp_port);
2759
                if(connect(session->media.video_rtcp_fd, (struct sockaddr *)server_addr, sizeof(struct sockaddr)) == -1) {
2760
                        JANUS_LOG(LOG_ERR, "[SIPre-%s] Couldn't connect video RTCP? (%s:%d)\n", session->account.username, session->media.remote_ip, session->media.remote_video_rtcp_port);
2761
                        JANUS_LOG(LOG_ERR, "[SIPre-%s]   -- %d (%s)\n", session->account.username, errno, strerror(errno));
2762
                }
2763
        }
2764

    
2765
}
2766

    
2767
/* Thread to relay RTP/RTCP frames coming from the SIPre peer */
2768
static void *janus_sipre_relay_thread(void *data) {
2769
        janus_sipre_session *session = (janus_sipre_session *)data;
2770
        if(!session || !session->account.username || !session->callee) {
2771
                g_thread_unref(g_thread_self());
2772
                return NULL;
2773
        }
2774
        JANUS_LOG(LOG_VERB, "Starting relay thread (%s <--> %s)\n", session->account.username, session->callee);
2775

    
2776
        gboolean have_server_ip = TRUE;
2777
        struct sockaddr_in server_addr;
2778
        memset(&server_addr, 0, sizeof(server_addr));
2779
        server_addr.sin_family = AF_INET;
2780
        if(inet_aton(session->media.remote_ip, &server_addr.sin_addr) == 0) {        /* Not a numeric IP... */
2781
                struct hostent *host = gethostbyname(session->media.remote_ip);        /* ...resolve name */
2782
                if(!host) {
2783
                        JANUS_LOG(LOG_ERR, "[SIPre-%s] Couldn't get host (%s)\n", session->account.username, session->media.remote_ip);
2784
                        have_server_ip = FALSE;
2785
                } else {
2786
                        server_addr.sin_addr = *(struct in_addr *)host->h_addr_list;
2787
                }
2788
        }
2789
        if(have_server_ip)
2790
                janus_sipre_connect_sockets(session, &server_addr);
2791

    
2792
        if(!session->callee) {
2793
                JANUS_LOG(LOG_VERB, "[SIPre-%s] Leaving thread, no callee...\n", session->account.username);
2794
                g_thread_unref(g_thread_self());
2795
                return NULL;
2796
        }
2797
        /* File descriptors */
2798
        socklen_t addrlen;
2799
        struct sockaddr_in remote;
2800
        int resfd = 0, bytes = 0;
2801
        struct pollfd fds[5];
2802
        int pipe_fd = session->media.pipefd[0];
2803
        char buffer[1500];
2804
        memset(buffer, 0, 1500);
2805
        /* Loop */
2806
        int num = 0;
2807
        gboolean goon = TRUE;
2808
        int astep = 0, vstep = 0;
2809
        guint32 ats = 0, vts = 0;
2810
        while(goon && session != NULL && !session->destroyed &&
2811
                        session->status > janus_sipre_call_status_idle &&
2812
                        session->status < janus_sipre_call_status_closing) {        /* FIXME We need a per-call watchdog as well */
2813

    
2814
                if(session->media.updated) {
2815
                        /* Apparently there was a session update */
2816
                        if(session->media.remote_ip != NULL && (inet_aton(session->media.remote_ip, &server_addr.sin_addr) != 0)) {
2817
                                janus_sipre_connect_sockets(session, &server_addr);
2818
                        } else {
2819
                                JANUS_LOG(LOG_ERR, "[SIPre-%s] Couldn't update session details (missing or invalid remote IP address)\n", session->account.username);
2820
                        }
2821
                        session->media.updated = FALSE;
2822
                }
2823

    
2824
                /* Prepare poll */
2825
                num = 0;
2826
                if(session->media.audio_rtp_fd != -1) {
2827
                        fds[num].fd = session->media.audio_rtp_fd;
2828
                        fds[num].events = POLLIN;
2829
                        fds[num].revents = 0;
2830
                        num++;
2831
                }
2832
                if(session->media.audio_rtcp_fd != -1) {
2833
                        fds[num].fd = session->media.audio_rtcp_fd;
2834
                        fds[num].events = POLLIN;
2835
                        fds[num].revents = 0;
2836
                        num++;
2837
                }
2838
                if(session->media.video_rtp_fd != -1) {
2839
                        fds[num].fd = session->media.video_rtp_fd;
2840
                        fds[num].events = POLLIN;
2841
                        fds[num].revents = 0;
2842
                        num++;
2843
                }
2844
                if(session->media.video_rtcp_fd != -1) {
2845
                        fds[num].fd = session->media.video_rtcp_fd;
2846
                        fds[num].events = POLLIN;
2847
                        fds[num].revents = 0;
2848
                        num++;
2849
                }
2850
                if(pipe_fd != -1) {
2851
                        fds[num].fd = pipe_fd;
2852
                        fds[num].events = POLLIN;
2853
                        fds[num].revents = 0;
2854
                        num++;
2855
                }
2856
                /* Wait for some data */
2857
                resfd = poll(fds, num, 1000);
2858
                if(resfd < 0) {
2859
                        JANUS_LOG(LOG_ERR, "[SIPre-%s] Error polling...\n", session->account.username);
2860
                        JANUS_LOG(LOG_ERR, "[SIPre-%s]   -- %d (%s)\n", session->account.username, errno, strerror(errno));
2861
                        break;
2862
                } else if(resfd == 0) {
2863
                        /* No data, keep going */
2864
                        continue;
2865
                }
2866
                if(session == NULL || session->destroyed ||
2867
                                session->status <= janus_sipre_call_status_idle ||
2868
                                session->status >= janus_sipre_call_status_closing)
2869
                        break;
2870
                int i = 0;
2871
                for(i=0; i<num; i++) {
2872
                        if(fds[i].revents & (POLLERR | POLLHUP)) {
2873
                                /* Socket error? */
2874
                                JANUS_LOG(LOG_ERR, "[SIPre-%s] Error polling: %s...\n", session->account.username,
2875
                                        fds[i].revents & POLLERR ? "POLLERR" : "POLLHUP");
2876
                                JANUS_LOG(LOG_ERR, "[SIPre-%s]   -- %d (%s)\n", session->account.username, errno, strerror(errno));
2877
                                if(session->media.updated)
2878
                                        break;
2879
                                goon = FALSE;        /* Can we assume it's pretty much over, after a POLLERR? */
2880
                                /* FIXME Simulate a "hangup" coming from the browser */
2881
                                janus_sipre_message *msg = g_malloc0(sizeof(janus_sipre_message));
2882
                                msg->handle = session->handle;
2883
                                msg->message = json_pack("{ss}", "request", "hangup");
2884
                                msg->transaction = NULL;
2885
                                msg->jsep = NULL;
2886
                                g_async_queue_push(messages, msg);
2887
                                break;
2888
                        } else if(fds[i].revents & POLLIN) {
2889
                                if(pipe_fd != -1 && fds[i].fd == pipe_fd) {
2890
                                        /* Poll interrupted for a reason, go on */
2891
                                        int code = 0;
2892
                                        bytes = read(pipe_fd, &code, sizeof(int));
2893
                                        break;
2894
                                }
2895
                                /* Got an RTP/RTCP packet */
2896
                                addrlen = sizeof(remote);
2897
                                bytes = recvfrom(fds[i].fd, buffer, 1500, 0, (struct sockaddr*)&remote, &addrlen);
2898
                                /* Let's check what this is */
2899
                                gboolean video = fds[i].fd == session->media.video_rtp_fd || fds[i].fd == session->media.video_rtcp_fd;
2900
                                gboolean rtcp = fds[i].fd == session->media.audio_rtcp_fd || fds[i].fd == session->media.video_rtcp_fd;
2901
                                if(!rtcp) {
2902
                                        /* Audio or Video RTP */
2903
                                        rtp_header *header = (rtp_header *)buffer;
2904
                                        if((video && session->media.video_ssrc_peer != ntohl(header->ssrc)) ||
2905
                                                        (!video && session->media.audio_ssrc_peer != ntohl(header->ssrc))) {
2906
                                                if(video) {
2907
                                                        session->media.video_ssrc_peer = ntohl(header->ssrc);
2908
                                                } else {
2909
                                                        session->media.audio_ssrc_peer = ntohl(header->ssrc);
2910
                                                }
2911
                                                JANUS_LOG(LOG_VERB, "[SIPre-%s] Got SIP peer %s SSRC: %"SCNu32"\n",
2912
                                                        session->account.username ? session->account.username : "unknown",
2913
                                                        video ? "video" : "audio", session->media.audio_ssrc_peer);
2914
                                        }
2915
                                        /* Is this SRTP? */
2916
                                        if(session->media.has_srtp_remote) {
2917
                                                int buflen = bytes;
2918
                                                srtp_err_status_t res = srtp_unprotect(
2919
                                                        (video ? session->media.video_srtp_in : session->media.audio_srtp_in),
2920
                                                        buffer, &buflen);
2921
                                                if(res != srtp_err_status_ok && res != srtp_err_status_replay_fail && res != srtp_err_status_replay_old) {
2922
                                                        guint32 timestamp = ntohl(header->timestamp);
2923
                                                        guint16 seq = ntohs(header->seq_number);
2924
                                                        JANUS_LOG(LOG_ERR, "[SIPre-%s] %s SRTP unprotect error: %s (len=%d-->%d, ts=%"SCNu32", seq=%"SCNu16")\n",
2925
                                                                session->account.username ? session->account.username : "unknown",
2926
                                                                video ? "Video" : "Audio", janus_srtp_error_str(res), bytes, buflen, timestamp, seq);
2927
                                                        continue;
2928
                                                }
2929
                                                bytes = buflen;
2930
                                        }
2931
                                        /* Check if the SSRC changed (e.g., after a re-INVITE or UPDATE) */
2932
                                        guint32 timestamp = ntohl(header->timestamp);
2933
                                        janus_rtp_header_update(header, &session->media.context, video,
2934
                                                (video ? (vstep ? vstep : 4500) : (astep ? astep : 960)));
2935
                                        if(video) {
2936
                                                if(vts == 0) {
2937
                                                        vts = timestamp;
2938
                                                } else if(vstep == 0) {
2939
                                                        vstep = timestamp-vts;
2940
                                                        if(vstep < 0) {
2941
                                                                vstep = 0;
2942
                                                        }
2943
                                                }
2944
                                        } else {
2945
                                                if(ats == 0) {
2946
                                                        ats = timestamp;
2947
                                                } else if(astep == 0) {
2948
                                                        astep = timestamp-ats;
2949
                                                        if(astep < 0) {
2950
                                                                astep = 0;
2951
                                                        }
2952
                                                }
2953
                                        }
2954
                                        /* Save the frame if we're recording */
2955
                                        janus_recorder_save_frame(video ? session->vrc_peer : session->arc_peer, buffer, bytes);
2956
                                        /* Relay to browser */
2957
                                        gateway->relay_rtp(session->handle, video, buffer, bytes);
2958
                                        continue;
2959
                                } else {
2960
                                        /* Audio or Video RTCP */
2961
                                        if(session->media.has_srtp_remote) {
2962
                                                int buflen = bytes;
2963
                                                srtp_err_status_t res = srtp_unprotect_rtcp(
2964
                                                        (video ? session->media.video_srtp_in : session->media.audio_srtp_in),
2965
                                                        buffer, &buflen);
2966
                                                if(res != srtp_err_status_ok && res != srtp_err_status_replay_fail && res != srtp_err_status_replay_old) {
2967
                                                        JANUS_LOG(LOG_ERR, "[SIPre-%s] %s SRTCP unprotect error: %s (len=%d-->%d)\n",
2968
                                                                session->account.username ? session->account.username : "unknown",
2969
                                                                video ? "Video" : "Audio", janus_srtp_error_str(res), bytes, buflen);
2970
                                                        continue;
2971
                                                }
2972
                                                bytes = buflen;
2973
                                        }
2974
                                        /* Relay to browser */
2975
                                        gateway->relay_rtcp(session->handle, video, buffer, bytes);
2976
                                        continue;
2977
                                }
2978
                        }
2979
                }
2980
        }
2981
        if(session->media.audio_rtp_fd != -1) {
2982
                close(session->media.audio_rtp_fd);
2983
                session->media.audio_rtp_fd = -1;
2984
        }
2985
        if(session->media.audio_rtcp_fd != -1) {
2986
                close(session->media.audio_rtcp_fd);
2987
                session->media.audio_rtcp_fd = -1;
2988
        }
2989
        session->media.local_audio_rtp_port = 0;
2990
        session->media.local_audio_rtcp_port = 0;
2991
        session->media.audio_ssrc = 0;
2992
        if(session->media.video_rtp_fd != -1) {
2993
                close(session->media.video_rtp_fd);
2994
                session->media.video_rtp_fd = -1;
2995
        }
2996
        if(session->media.video_rtcp_fd != -1) {
2997
                close(session->media.video_rtcp_fd);
2998
                session->media.video_rtcp_fd = -1;
2999
        }
3000
        session->media.local_video_rtp_port = 0;
3001
        session->media.local_video_rtcp_port = 0;
3002
        session->media.video_ssrc = 0;
3003
        if(session->media.pipefd[0] > 0) {
3004
                close(session->media.pipefd[0]);
3005
                session->media.pipefd[0] = -1;
3006
        }
3007
        if(session->media.pipefd[1] > 0) {
3008
                close(session->media.pipefd[1]);
3009
                session->media.pipefd[1] = -1;
3010
        }
3011
        /* Clean up SRTP stuff, if needed */
3012
        janus_sipre_srtp_cleanup(session);
3013
        /* Done */
3014
        JANUS_LOG(LOG_VERB, "Leaving SIPre relay thread\n");
3015
        g_thread_unref(g_thread_self());
3016
        return NULL;
3017
}
3018

    
3019

    
3020
/* libre loop thread */
3021
gpointer janus_sipre_stack_thread(gpointer user_data) {
3022
        JANUS_LOG(LOG_INFO, "Joining libre loop thread...\n");
3023

    
3024
        /* Setup libre */
3025
        int err = libre_init();
3026
        if(err) {
3027
                JANUS_LOG(LOG_ERR, "libre_init() failed: %d (%s)\n", err, strerror(err));
3028
                goto done;
3029
        }
3030
        /* Initialize this thread as a worker */
3031
        err = re_thread_init();
3032
        if(err != 0) {
3033
                printf("re_thread_init failed: %d (%s)\n", err, strerror(err));
3034
                goto done;
3035
        }
3036
        err = mqueue_alloc(&mq, janus_sipre_mqueue_handler, NULL);
3037
        if(err) {
3038
                JANUS_LOG(LOG_ERR, "Failed to initialize message queue: %d (%s)\n", err, strerror(err));
3039
                goto done;
3040
        }
3041
        g_atomic_int_set(&libre_inited, 1);
3042

    
3043
        /* Enter loop */
3044
        err = re_main(NULL);
3045
        if(err != 0) {
3046
                JANUS_LOG(LOG_ERR, "re_main() failed: %d (%s)\n", err, strerror(err));
3047
        }
3048

    
3049
        /* Done here */
3050
        JANUS_LOG(LOG_INFO, "Leaving libre loop thread...\n");
3051
        re_thread_close();
3052
        /* Deinitialize libre */
3053
        libre_close();
3054

    
3055
done:
3056
        g_atomic_int_set(&libre_inited, -1);
3057
        return NULL;
3058
}
3059

    
3060
/* Called when challenged for credentials */
3061
int janus_sipre_cb_auth(char **user, char **pass, const char *realm, void *arg) {
3062
        janus_sipre_session *session = (janus_sipre_session *)arg;
3063
        JANUS_LOG(LOG_HUGE, "[SIPre-%s] janus_sipre_cb_auth (realm=%s)\n", session->account.username, realm);
3064
        /* TODO How do we handle hashed secrets? */
3065
        int err = 0;
3066
        err |= str_dup(user, session->account.authuser);
3067
        err |= str_dup(pass, session->account.secret);
3068
        JANUS_LOG(LOG_HUGE, "[SIPre-%s]   -- %s / %s\n", session->account.username, *user, *pass);
3069
        return err;
3070
}
3071

    
3072
/* Called when REGISTER responses are received */
3073
void janus_sipre_cb_register(int err, const struct sip_msg *msg, void *arg) {
3074
        janus_sipre_session *session = (janus_sipre_session *)arg;
3075
        JANUS_LOG(LOG_HUGE, "[SIPre-%s] janus_sipre_cb_register\n", session->account.username);
3076
        if(err) {
3077
                JANUS_LOG(LOG_ERR, "[SIPre-%s] REGISTER error: %s\n", session->account.username, strerror(err));
3078
                /* FIXME Should we send an event here? */
3079
        } else {
3080
                JANUS_LOG(LOG_VERB, "[SIPre-%s] REGISTER reply: %u\n", session->account.username, msg->scode);
3081
                if(msg->scode == 200) {
3082
                        if(session->account.registration_status < janus_sipre_registration_status_registered)
3083
                                session->account.registration_status = janus_sipre_registration_status_registered;
3084
                        /* Notify the browser */
3085
                        json_t *call = json_object();
3086
                        json_object_set_new(call, "sip", json_string("event"));
3087
                        json_t *calling = json_object();
3088
                        json_object_set_new(calling, "event", json_string("registered"));
3089
                        json_object_set_new(calling, "username", json_string(session->account.username));
3090
                        json_object_set_new(calling, "register_sent", json_true());
3091
                        json_object_set_new(call, "result", calling);
3092
                        if(!session->destroyed) {
3093
                                int ret = gateway->push_event(session->handle, &janus_sipre_plugin, session->transaction, call, NULL);
3094
                                JANUS_LOG(LOG_VERB, "  >> Pushing event to peer: %d (%s)\n", ret, janus_get_api_error(ret));
3095
                        }
3096
                        json_decref(call);
3097
                        /* Also notify event handlers */
3098
                        if(notify_events && gateway->events_is_enabled()) {
3099
                                json_t *info = json_object();
3100
                                json_object_set_new(info, "event", json_string("registered"));
3101
                                json_object_set_new(info, "identity", json_string(session->account.identity));
3102
                                if(session->account.proxy)
3103
                                        json_object_set_new(info, "proxy", json_string(session->account.proxy));
3104
                                gateway->notify_event(&janus_sipre_plugin, session->handle, info);
3105
                        }
3106
                } else {
3107
                        /* Authentication failed? */
3108
                        session->account.registration_status = janus_sipre_registration_status_failed;
3109
                        /* Tell the browser... */
3110
                        json_t *event = json_object();
3111
                        json_object_set_new(event, "sip", json_string("event"));
3112
                        json_t *result = json_object();
3113
                        json_object_set_new(result, "event", json_string("registration_failed"));
3114
                        json_object_set_new(result, "code", json_integer(msg->scode));
3115
                        char reason[256];
3116
                        reason[0] = '\0';
3117
                        if(msg->reason.l > 0) {
3118
                                g_snprintf(reason, (msg->reason.l < 255 ? msg->reason.l+1 : 255), "%s", msg->reason.p);
3119
                                json_object_set_new(result, "reason", json_string(reason));
3120
                        }
3121
                        json_object_set_new(event, "result", result);
3122
                        if(!session->destroyed) {
3123
                                int ret = gateway->push_event(session->handle, &janus_sipre_plugin, session->transaction, event, NULL);
3124
                                JANUS_LOG(LOG_VERB, "  >> Pushing event to peer: %d (%s)\n", ret, janus_get_api_error(ret));
3125
                        }
3126
                        json_decref(event);
3127
                        /* Also notify event handlers */
3128
                        if(notify_events && gateway->events_is_enabled()) {
3129
                                json_t *info = json_object();
3130
                                json_object_set_new(info, "event", json_string("registration_failed"));
3131
                                json_object_set_new(info, "code", json_integer(msg->scode));
3132
                                if(msg->reason.l > 0) {
3133
                                        json_object_set_new(info, "reason", json_string(reason));
3134
                                }
3135
                                gateway->notify_event(&janus_sipre_plugin, session->handle, info);
3136
                        }
3137
                }
3138
        }
3139
}
3140

    
3141
/* Called when SIP progress (e.g., 180 Ringing) responses are received */
3142
void janus_sipre_cb_progress(const struct sip_msg *msg, void *arg) {
3143
        janus_sipre_session *session = (janus_sipre_session *)arg;
3144
        char reason[256];
3145
        reason[0] = '\0';
3146
        if(msg->reason.l > 0) {
3147
                g_snprintf(reason, (msg->reason.l < 255 ? msg->reason.l+1 : 255), "%s", msg->reason.p);
3148
        }
3149
        JANUS_LOG(LOG_HUGE, "[SIPre-%s] Session progress: %u %s\n", session->account.username, msg->scode, reason);
3150
        /* FIXME Anything we should do with this? Notify the user? */
3151
}
3152

    
3153
/* Called upon incoming INVITEs */
3154
void janus_sipre_cb_incoming(const struct sip_msg *msg, void *arg) {
3155
        janus_sipre_session *session = (janus_sipre_session *)arg;
3156
        JANUS_LOG(LOG_HUGE, "[SIPre-%s] janus_sipre_cb_incoming (%p)\n", session->account.username, session);
3157
        /* Increase the reference to the msg instance, as we'll need it either
3158
         * to reply with an error right away, or for a success/error later */
3159
        mem_ref((struct sip_msg *)msg);
3160
        /* Parse a few relevant identifiers */
3161
        char *from = NULL;
3162
        re_sdprintf(&from, "%H", uri_encode, &msg->from.uri);
3163
        JANUS_LOG(LOG_HUGE, "[SIPre-%s]   -- Caller: %s\n", session->account.username, from);
3164
        char dname[256];
3165
        dname[0] = '\0';
3166
        if(msg->from.dname.l > 0) {
3167
                g_snprintf(dname, sizeof(dname), "%.*s", (int)msg->from.dname.l, msg->from.dname.p);
3168
                JANUS_LOG(LOG_HUGE, "[SIPre-%s]   -- Display: %s\n", session->account.username, dname);
3169
        }
3170
        char callid[256];
3171
        g_snprintf(callid, sizeof(callid), "%.*s", (int)msg->callid.l, msg->callid.p);
3172
        JANUS_LOG(LOG_HUGE, "[SIPre-%s]   -- Call-ID: %s\n", session->account.username, callid);
3173
        /* Make sure we're not in a call already */
3174
        if(session->stack.sess != NULL) {
3175
                /* Already in a call */
3176
                JANUS_LOG(LOG_VERB, "Already in a call (busy, status=%s)\n", janus_sipre_call_status_string(session->status));
3177
                mqueue_push(mq, janus_sipre_mqueue_event_do_rcode, janus_sipre_mqueue_payload_create(session, msg, 486, session));
3178
                /* Notify the web app about the missed invite */
3179
                json_t *missed = json_object();
3180
                json_object_set_new(missed, "sip", json_string("event"));
3181
                json_t *result = json_object();
3182
                json_object_set_new(result, "event", json_string("missed_call"));
3183
                json_object_set_new(result, "caller", json_string(from));
3184
                if(strlen(dname)) {
3185
                        json_object_set_new(result, "displayname", json_string(dname));
3186
                }
3187
                json_object_set_new(missed, "result", result);
3188
                if(!session->destroyed) {
3189
                        int ret = gateway->push_event(session->handle, &janus_sipre_plugin, session->transaction, missed, NULL);
3190
                        JANUS_LOG(LOG_VERB, "  >> Pushing event to peer: %d (%s)\n", ret, janus_get_api_error(ret));
3191
                }
3192
                json_decref(missed);
3193
                /* Also notify event handlers */
3194
                if(notify_events && gateway->events_is_enabled()) {
3195
                        json_t *info = json_object();
3196
                        json_object_set_new(info, "event", json_string("missed_call"));
3197
                        json_object_set_new(info, "caller", json_string(from));
3198
                        gateway->notify_event(&janus_sipre_plugin, session->handle, info);
3199
                }
3200
                return;
3201
        }
3202
        /* New incoming call */
3203
        const char *offer = (const char *)mbuf_buf(msg->mb);
3204
        if(offer == NULL) {
3205
                /* No SDP? */
3206
                JANUS_LOG(LOG_WARN, "[SIPre-%s] No SDP in the INVITE?\n", session->account.username);
3207
                mqueue_push(mq, janus_sipre_mqueue_event_do_rcode, janus_sipre_mqueue_payload_create(session, msg, 488, NULL));
3208
                return;
3209
        }
3210
        char sdp_offer[1024];
3211
        g_snprintf(sdp_offer, sizeof(sdp_offer), "%.*s", (int)mbuf_get_left(msg->mb), offer);
3212
        JANUS_LOG(LOG_HUGE, "[SIPre-%s]   -- Offer: %s\n", session->account.username, sdp_offer);
3213
        /* Parse the remote SDP */
3214
        char sdperror[100];
3215
        janus_sdp *sdp = janus_sdp_parse(sdp_offer, sdperror, sizeof(sdperror));
3216
        if(!sdp) {
3217
                JANUS_LOG(LOG_ERR, "Error parsing SDP! %s\n", sdperror);
3218
                mqueue_push(mq, janus_sipre_mqueue_event_do_rcode, janus_sipre_mqueue_payload_create(session, msg, 488, NULL));
3219
                return;
3220
        }
3221
        session->callee = g_strdup(from);
3222
        session->callid = g_strdup(callid);
3223
        g_hash_table_insert(callids, session->callid, session);
3224
        session->status = janus_sipre_call_status_invited;
3225
        /* Clean up SRTP stuff from before first, in case it's still needed */
3226
        janus_sipre_srtp_cleanup(session);
3227
        /* Parse SDP */
3228
        JANUS_LOG(LOG_VERB, "Someone is inviting us a call\n");
3229
        gboolean changed = FALSE;
3230
        janus_sipre_sdp_process(session, sdp, FALSE, FALSE, &changed);
3231
        /* Check if offer has neither audio nor video, fail with 488 */
3232
        if (!session->media.has_audio && !session->media.has_video) {
3233
                mqueue_push(mq, janus_sipre_mqueue_event_do_rcode, janus_sipre_mqueue_payload_create(session, msg, 488, NULL));
3234
                janus_sdp_free(sdp);
3235
                return;
3236
        }
3237
        /* Also fail with 488 if there's no remote IP address that can be used for RTP */
3238
        if (!session->media.remote_ip) {
3239
                mqueue_push(mq, janus_sipre_mqueue_event_do_rcode, janus_sipre_mqueue_payload_create(session, msg, 488, NULL));
3240
                janus_sdp_free(sdp);
3241
                return;
3242
        }
3243
        session->stack.invite = msg;
3244
        /* Send SDP to the browser */
3245
        json_t *jsep = json_pack("{ssss}", "type", "offer", "sdp", sdp_offer);
3246
        json_t *call = json_object();
3247
        json_object_set_new(call, "sip", json_string("event"));
3248
        json_t *calling = json_object();
3249
        json_object_set_new(calling, "event", json_string("incomingcall"));
3250
        json_object_set_new(calling, "username", json_string(session->callee));
3251
        if(strlen(dname)) {
3252
                json_object_set_new(calling, "displayname", json_string(dname));
3253
        }
3254
        if(session->media.has_srtp_remote) {
3255
                /* FIXME Maybe a true/false instead? */
3256
                json_object_set_new(calling, "srtp", json_string(session->media.require_srtp ? "sdes_mandatory" : "sdes_optional"));
3257
        }
3258
        json_object_set_new(call, "result", calling);
3259
        if(!session->destroyed) {
3260
                int ret = gateway->push_event(session->handle, &janus_sipre_plugin, session->transaction, call, jsep);
3261
                JANUS_LOG(LOG_VERB, "  >> Pushing event to peer: %d (%s)\n", ret, janus_get_api_error(ret));
3262
        }
3263
        json_decref(call);
3264
        json_decref(jsep);
3265
        janus_sdp_free(sdp);
3266
        /* Also notify event handlers */
3267
        if(notify_events && gateway->events_is_enabled()) {
3268
                json_t *info = json_object();
3269
                json_object_set_new(info, "event", json_string("incomingcall"));
3270
                if(session->callid)
3271
                        json_object_set_new(info, "call-id", json_string(session->callid));
3272
                json_object_set_new(info, "username", json_string(session->callee));
3273
                if(strlen(dname))
3274
                        json_object_set_new(info, "displayname", json_string(dname));
3275
                gateway->notify_event(&janus_sipre_plugin, session->handle, info);
3276
        }
3277
        /* Send a Ringing back */
3278
        mqueue_push(mq, janus_sipre_mqueue_event_do_rcode, janus_sipre_mqueue_payload_create(session, msg, 180, NULL));
3279
}
3280

    
3281
/* Called when an SDP offer is received (re-INVITE) */
3282
int janus_sipre_cb_offer(struct mbuf **mbp, const struct sip_msg *msg, void *arg) {
3283
        janus_sipre_session *session = (janus_sipre_session *)arg;
3284
        JANUS_LOG(LOG_HUGE, "[SIPre-%s] janus_sipre_cb_offer\n", session->account.username);
3285
        /* Get the SDP */
3286
        const char *offer = (const char *)mbuf_buf(msg->mb);
3287
        if(offer == NULL) {
3288
                /* No SDP? */
3289
                JANUS_LOG(LOG_WARN, "[SIPre-%s] No SDP in the re-INVITE?\n", session->account.username);
3290
                return EINVAL;
3291
        }
3292
        char sdp_offer[1024];
3293
        g_snprintf(sdp_offer, sizeof(sdp_offer), "%.*s", (int)mbuf_get_left(msg->mb), offer);
3294
        JANUS_LOG(LOG_VERB, "Someone is updating a call:\n%s", sdp_offer);
3295
        /* Parse the remote SDP */
3296
        char sdperror[100];
3297
        janus_sdp *sdp = janus_sdp_parse(sdp_offer, sdperror, sizeof(sdperror));
3298
        if(!sdp) {
3299
                JANUS_LOG(LOG_ERR, "Error parsing SDP! %s\n", sdperror);
3300
                return EINVAL;
3301
        }
3302
        gboolean changed = FALSE;
3303
        janus_sipre_sdp_process(session, sdp, FALSE, TRUE, &changed);
3304
        janus_sdp_free(sdp);
3305
        /* Check if offer has neither audio nor video, fail with 488 */
3306
        if (!session->media.has_audio && !session->media.has_video) {
3307
                mqueue_push(mq, janus_sipre_mqueue_event_do_rcode, janus_sipre_mqueue_payload_create(session, msg, 488, NULL));
3308
                return EINVAL;
3309
        }
3310
        /* Also fail with 488 if there's no remote IP address that can be used for RTP */
3311
        if (!session->media.remote_ip) {
3312
                mqueue_push(mq, janus_sipre_mqueue_event_do_rcode, janus_sipre_mqueue_payload_create(session, msg, 488, NULL));
3313
                return EINVAL;
3314
        }
3315
        char *answer = janus_sdp_write(session->sdp);
3316
        JANUS_LOG(LOG_VERB, "Answering re-INVITE:\n%s", answer);
3317
        *mbp = mbuf_alloc(strlen(answer)+1);
3318
        mbuf_printf(*mbp, "%s", answer);
3319
        mbuf_set_pos(*mbp, 0);
3320
        return 0;
3321
}
3322

    
3323

    
3324
/* Called when an SDP answer is received */
3325
int janus_sipre_cb_answer(const struct sip_msg *msg, void *arg) {
3326
        janus_sipre_session *session = (janus_sipre_session *)arg;
3327
        JANUS_LOG(LOG_HUGE, "[SIPre-%s] janus_sipre_cb_answer\n", session->account.username);
3328
        /* Get the SDP */
3329
        const char *answer = (const char *)mbuf_buf(msg->mb);
3330
        if(answer == NULL) {
3331
                /* No SDP? */
3332
                JANUS_LOG(LOG_WARN, "[SIPre-%s] No SDP in the answer?\n", session->account.username);
3333
                return EINVAL;
3334
        }
3335
        char sdp_answer[1024];
3336
        g_snprintf(sdp_answer, sizeof(sdp_answer), "%.*s", (int)mbuf_get_left(msg->mb), answer);
3337
        /* Parse the SDP */
3338
        char sdperror[100];
3339
        janus_sdp *sdp = janus_sdp_parse(sdp_answer, sdperror, sizeof(sdperror));
3340
        if(!sdp) {
3341
                JANUS_LOG(LOG_ERR, "Error parsing SDP! %s\n", sdperror);
3342
                return EINVAL;
3343
        }
3344
        /* Parse SDP */
3345
        JANUS_LOG(LOG_VERB, "Peer accepted our call:\n%s", sdp_answer);
3346
        session->status = janus_sipre_call_status_incall;
3347
        gboolean changed = FALSE;
3348
        gboolean update = session->media.ready;
3349
        janus_sipre_sdp_process(session, sdp, TRUE, update, &changed);
3350
        /* If we asked for SRTP and are not getting it, fail */
3351
        if(session->media.require_srtp && !session->media.has_srtp_remote) {
3352
                JANUS_LOG(LOG_ERR, "We asked for mandatory SRTP but didn't get any in the reply!\n");
3353
                janus_sdp_free(sdp);
3354
                /* Hangup immediately */
3355
                session->media.ready = FALSE;
3356
                session->media.on_hold = FALSE;
3357
                session->status = janus_sipre_call_status_closing;
3358
                mqueue_push(mq, janus_sipre_mqueue_event_do_bye, janus_sipre_mqueue_payload_create(session, msg, 0, NULL));
3359
                g_free(session->callee);
3360
                session->callee = NULL;
3361
                return EINVAL;
3362
        }
3363
        if(!session->media.remote_ip) {
3364
                /* No remote address parsed? Give up */
3365
                JANUS_LOG(LOG_ERR, "No remote IP address found for RTP, something's wrong with the SDP!\n");
3366
                janus_sdp_free(sdp);
3367
                /* Hangup immediately */
3368
                session->media.ready = FALSE;
3369
                session->media.on_hold = FALSE;
3370
                session->status = janus_sipre_call_status_closing;
3371
                mqueue_push(mq, janus_sipre_mqueue_event_do_bye, janus_sipre_mqueue_payload_create(session, msg, 0, NULL));
3372
                g_free(session->callee);
3373
                session->callee = NULL;
3374
                return EINVAL;
3375
        }
3376
        if(session->media.audio_pt > -1) {
3377
                session->media.audio_pt_name = janus_get_codec_from_pt(sdp_answer, session->media.audio_pt);
3378
                JANUS_LOG(LOG_VERB, "Detected audio codec: %d (%s)\n", session->media.audio_pt, session->media.audio_pt_name);
3379
        }
3380
        if(session->media.video_pt > -1) {
3381
                session->media.video_pt_name = janus_get_codec_from_pt(sdp_answer, session->media.video_pt);
3382
                JANUS_LOG(LOG_VERB, "Detected video codec: %d (%s)\n", session->media.video_pt, session->media.video_pt_name);
3383
        }
3384
        session->media.ready = TRUE;        /* FIXME Maybe we need a better way to signal this */
3385
        if(update) {
3386
                /* Don't push to the browser if this is in response to a hold/unhold we sent ourselves */
3387
                JANUS_LOG(LOG_WARN, "This is an update to an existing call (possibly in response to hold/unhold)\n");
3388
                return 0;
3389
        }
3390
        GError *error = NULL;
3391
        char tname[16];
3392
        g_snprintf(tname, sizeof(tname), "siprertp %s", session->account.username);
3393
        g_thread_try_new(tname, janus_sipre_relay_thread, session, &error);
3394
        if(error != NULL) {
3395
                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the RTP/RTCP thread...\n", error->code, error->message ? error->message : "??");
3396
        }
3397
        /* Send SDP to the browser */
3398
        json_t *jsep = json_pack("{ssss}", "type", "answer", "sdp", sdp_answer);
3399
        json_t *call = json_object();
3400
        json_object_set_new(call, "sip", json_string("event"));
3401
        json_t *calling = json_object();
3402
        json_object_set_new(calling, "event", json_string("accepted"));
3403
        json_object_set_new(calling, "username", json_string(session->callee));
3404
        json_object_set_new(call, "result", calling);
3405
        if(!session->destroyed) {
3406
                int ret = gateway->push_event(session->handle, &janus_sipre_plugin, session->transaction, call, jsep);
3407
                JANUS_LOG(LOG_VERB, "  >> Pushing event to peer: %d (%s)\n", ret, janus_get_api_error(ret));
3408
        }
3409
        json_decref(call);
3410
        json_decref(jsep);
3411
        janus_sdp_free(sdp);
3412
        /* Also notify event handlers */
3413
        if(notify_events && gateway->events_is_enabled()) {
3414
                json_t *info = json_object();
3415
                json_object_set_new(info, "event", json_string("accepted"));
3416
                if(session->callid)
3417
                        json_object_set_new(info, "call-id", json_string(session->callid));
3418
                json_object_set_new(info, "username", json_string(session->callee));
3419
                gateway->notify_event(&janus_sipre_plugin, session->handle, info);
3420
        }
3421

    
3422
        return 0;
3423
}
3424

    
3425
/* Called when the session is established */
3426
void janus_sipre_cb_established(const struct sip_msg *msg, void *arg) {
3427
        janus_sipre_session *session = (janus_sipre_session *)arg;
3428
        if(session == NULL) {
3429
                JANUS_LOG(LOG_WARN, "[SIPre-??] janus_sipre_cb_established\n");
3430
                return;
3431
        }
3432
        JANUS_LOG(LOG_HUGE, "[SIPre-%s] janus_sipre_cb_established\n", session->account.username);
3433
        /* FIXME Anything to do here? */
3434
}
3435

    
3436
/* Called when the session fails to connect or is terminated by the peer */
3437
void janus_sipre_cb_closed(int err, const struct sip_msg *msg, void *arg) {
3438
        janus_sipre_session *session = (janus_sipre_session *)arg;
3439
        if(session == NULL) {
3440
                JANUS_LOG(LOG_HUGE, "[SIPre-??] janus_sipre_cb_closed\n");
3441
                return;
3442
        }
3443
        if(err) {
3444
                JANUS_LOG(LOG_VERB, "[SIPre-%s] Session closed: %d %s\n", session->account.username, err, strerror(err));
3445
        } else {
3446
                JANUS_LOG(LOG_VERB, "[SIPre-%s] Session closed: %u %s\n", session->account.username, msg->scode, (char *)&msg->reason.p);
3447
        }
3448

    
3449
        /* Tell the browser... */
3450
        json_t *event = json_object();
3451
        json_object_set_new(event, "sip", json_string("event"));
3452
        json_t *result = json_object();
3453
        json_object_set_new(result, "event", json_string("hangup"));
3454
        json_object_set_new(result, "code", json_integer(err ? err : msg->scode));
3455
        char reason[256];
3456
        reason[0] = '\0';
3457
        if(!err && msg->reason.l > 0) {
3458
                g_snprintf(reason, (msg->reason.l < 255 ? msg->reason.l+1 : 255), "%s", msg->reason.p);
3459
        }
3460
        json_object_set_new(result, "reason", json_string(err ? strerror(err) : reason));
3461
        json_object_set_new(event, "result", result);
3462
        if(!session->destroyed) {
3463
                int ret = gateway->push_event(session->handle, &janus_sipre_plugin, session->transaction, event, NULL);
3464
                JANUS_LOG(LOG_VERB, "  >> Pushing event to peer: %d (%s)\n", ret, janus_get_api_error(ret));
3465
        }
3466
        json_decref(event);
3467
        /* Also notify event handlers */
3468
        if(notify_events && gateway->events_is_enabled()) {
3469
                json_t *info = json_object();
3470
                json_object_set_new(info, "event", json_string("hangup"));
3471
                json_object_set_new(info, "code", json_integer(err ? err : msg->scode));
3472
                json_object_set_new(info, "reason", json_string(err ? strerror(err) : reason));
3473
                gateway->notify_event(&janus_sipre_plugin, session->handle, info);
3474
        }
3475

    
3476
        /* Cleanup */
3477
        session->stack.sess = mem_deref(session->stack.sess);
3478
        //~ session->stack.reg = mem_deref(session->stack.reg);
3479
        session->media.ready = FALSE;
3480
        session->media.on_hold = FALSE;
3481
        session->status = janus_sipre_call_status_idle;
3482
}
3483

    
3484
/* Called when all SIP transactions are completed */
3485
void janus_sipre_cb_exit(void *arg) {
3486
        janus_sipre_session *session = (janus_sipre_session *)arg;
3487
        if(session == NULL) {
3488
                JANUS_LOG(LOG_HUGE, "[SIPre-??] janus_sipre_cb_exit\n");
3489
                return;
3490
        }
3491
        JANUS_LOG(LOG_INFO, "[SIPre-%s] Cleaning SIP stack\n", session->account.username);
3492
        mem_deref(&session->stack.sipstack);
3493
}
3494

    
3495
/* Callback to implement SIP requests in the re_main loop thread */
3496
void janus_sipre_mqueue_handler(int id, void *data, void *arg) {
3497
        JANUS_LOG(LOG_HUGE, "janus_sipre_mqueue_handler: %d (%s)\n", id, janus_sipre_mqueue_event_string((janus_sipre_mqueue_event)id));
3498
        switch((janus_sipre_mqueue_event)id) {
3499
                case janus_sipre_mqueue_event_do_init: {
3500
                        janus_sipre_mqueue_payload *payload = (janus_sipre_mqueue_payload *)data;
3501
                        janus_sipre_session *session = (janus_sipre_session *)payload->session;
3502
                        /* Let's allocate the stack first */
3503
                        int err = sip_alloc(&session->stack.sipstack, NULL, 32, 32, 32, JANUS_SIPRE_NAME, janus_sipre_cb_exit, session);
3504
                        if(err) {
3505
                                JANUS_LOG(LOG_ERR, "Failed to initialize libre SIP stack: %d (%s)\n", err, strerror(err));
3506
                                g_free(payload);
3507
                                return;
3508
                        }
3509
                        JANUS_LOG(LOG_INFO, "Initializing SIP transports\n");
3510
                        struct sa laddr, laddrs;
3511
                        sa_set_str(&laddr, local_ip, 0);
3512
                        sa_set_str(&laddrs, local_ip, 0);
3513
                        err = 0;
3514
                        err |= sip_transp_add(session->stack.sipstack, SIP_TRANSP_UDP, &laddr);
3515
                        err |= sip_transp_add(session->stack.sipstack, SIP_TRANSP_TCP, &laddr);
3516
                        if(err) {
3517
                                JANUS_LOG(LOG_ERR, "Failed to initialize libre SIP transports: %d (%s)\n", err, strerror(err));
3518
                                g_free(payload);
3519
                                return;
3520
                        }
3521
                        err = tls_alloc(&session->stack.tls, TLS_METHOD_SSLV23, NULL, NULL);
3522
                        err |= sip_transp_add(session->stack.sipstack, SIP_TRANSP_TLS, &laddrs, session->stack.tls);
3523
                        err |= sipsess_listen(&session->stack.sess_sock, session->stack.sipstack, 32, janus_sipre_cb_incoming, session);
3524
                        if(err) {
3525
                                mem_deref(session->stack.sipstack);
3526
                                mem_deref(session->stack.tls);
3527
                                JANUS_LOG(LOG_ERR, "Failed to initialize libre SIPS transports: %d (%s)\n", err, strerror(err));
3528
                                g_free(payload);
3529
                                return;
3530
                        }
3531
#ifdef HAVE_LIBRE_SIPTRACE
3532
                        if(gateway->events_is_enabled()) {
3533
                                /* Trace incoming/outgoing SIP messages */
3534
                                sip_set_trace(session->stack.sipstack, janus_sipre_msg_logger);
3535
                        }
3536
#endif
3537
                        mem_deref(session->stack.tls);
3538
                        g_free(payload);
3539
                        break;
3540
                }
3541
                case janus_sipre_mqueue_event_do_register: {
3542
                        janus_sipre_mqueue_payload *payload = (janus_sipre_mqueue_payload *)data;
3543
                        janus_sipre_session *session = (janus_sipre_session *)payload->session;
3544
                        JANUS_LOG(LOG_VERB, "[SIPre-%s] Sending REGISTER\n", session->account.username);
3545
                        /* Check if there are custom headers to add */
3546
                        char *headers = (char *)payload->data;
3547
                        /* Send the REGISTER */
3548
                        int err = sipreg_register(&session->stack.reg, session->stack.sipstack,
3549
                                session->account.proxy,
3550
                                session->account.identity, session->account.identity, session->stack.expires,
3551
                                session->account.display_name ? session->account.display_name : session->account.username, NULL, 0, 0,
3552
                                janus_sipre_cb_auth, session, FALSE,
3553
                                janus_sipre_cb_register, session, NULL, (headers ? headers : ""), NULL);
3554
                        g_free(headers);
3555
                        if(err != 0) {
3556
                                JANUS_LOG(LOG_ERR, "Error attempting to REGISTER: %d (%s)\n", err, strerror(err));
3557
                                /* Tell the browser... */
3558
                                json_t *event = json_object();
3559
                                json_object_set_new(event, "sip", json_string("event"));
3560
                                json_t *result = json_object();
3561
                                json_object_set_new(result, "event", json_string("registration_failed"));
3562
                                json_object_set_new(result, "code", json_integer(err));
3563
                                json_object_set_new(result, "reason", json_string(strerror(err)));
3564
                                json_object_set_new(event, "result", result);
3565
                                if(!session->destroyed) {
3566
                                        int ret = gateway->push_event(session->handle, &janus_sipre_plugin, session->transaction, event, NULL);
3567
                                        JANUS_LOG(LOG_VERB, "  >> Pushing event to peer: %d (%s)\n", ret, janus_get_api_error(ret));
3568
                                }
3569
                                json_decref(event);
3570
                                /* Also notify event handlers */
3571
                                if(notify_events && gateway->events_is_enabled()) {
3572
                                        json_t *info = json_object();
3573
                                        json_object_set_new(info, "event", json_string("registration_failed"));
3574
                                        json_object_set_new(info, "code", json_integer(err));
3575
                                        json_object_set_new(info, "reason", json_string(strerror(err)));
3576
                                        gateway->notify_event(&janus_sipre_plugin, session->handle, info);
3577
                                }
3578
                        }
3579
                        g_free(payload);
3580
                        break;
3581
                }
3582
                case janus_sipre_mqueue_event_do_call: {
3583
                        janus_sipre_mqueue_payload *payload = (janus_sipre_mqueue_payload *)data;
3584
                        janus_sipre_session *session = (janus_sipre_session *)payload->session;
3585
                        JANUS_LOG(LOG_VERB, "[SIPre-%s] Sending INVITE\n%s", session->account.username, session->temp_sdp);
3586
                        /* Check if there are custom headers to add */
3587
                        char *headers = (char *)payload->data;
3588
                        /* Convert the SDP into a struct mbuf */
3589
                        struct mbuf *mb = mbuf_alloc(strlen(session->temp_sdp)+1);
3590
                        mbuf_printf(mb, "%s", session->temp_sdp);
3591
                        mbuf_set_pos(mb, 0);
3592
                        /* Send the INVITE */
3593
                        int err = sipsess_connect(&session->stack.sess, session->stack.sess_sock,
3594
                                session->callee,
3595
                                session->account.display_name, session->account.identity,
3596
                                session->account.display_name ? session->account.display_name : session->account.username,
3597
                                NULL, 0, "application/sdp", mb,
3598
                                janus_sipre_cb_auth, session, FALSE,
3599
                                janus_sipre_cb_offer, janus_sipre_cb_answer,
3600
                                janus_sipre_cb_progress, janus_sipre_cb_established,
3601
                                NULL, NULL, janus_sipre_cb_closed, session,
3602
                                "%s", (headers ? headers : ""));
3603
                        g_free(headers);
3604
                        if(err != 0) {
3605
                                JANUS_LOG(LOG_ERR, "Error attempting to INVITE: %d (%s)\n", err, strerror(err));
3606
                                /* Tell the browser... */
3607
                                json_t *event = json_object();
3608
                                json_object_set_new(event, "sip", json_string("event"));
3609
                                json_t *result = json_object();
3610
                                json_object_set_new(result, "event", json_string("hangup"));
3611
                                json_object_set_new(result, "code", json_integer(err));
3612
                                json_object_set_new(result, "reason", json_string(strerror(err)));
3613
                                json_object_set_new(event, "result", result);
3614
                                if(!session->destroyed) {
3615
                                        int ret = gateway->push_event(session->handle, &janus_sipre_plugin, session->transaction, event, NULL);
3616
                                        JANUS_LOG(LOG_VERB, "  >> Pushing event to peer: %d (%s)\n", ret, janus_get_api_error(ret));
3617
                                }
3618
                                json_decref(event);
3619
                                /* Also notify event handlers */
3620
                                if(notify_events && gateway->events_is_enabled()) {
3621
                                        json_t *info = json_object();
3622
                                        json_object_set_new(info, "event", json_string("hangup"));
3623
                                        json_object_set_new(info, "code", json_integer(err));
3624
                                        json_object_set_new(info, "reason", json_string(strerror(err)));
3625
                                        gateway->notify_event(&janus_sipre_plugin, session->handle, info);
3626
                                }
3627
                        }
3628
                        mem_deref(mb);
3629
                        g_free(session->temp_sdp);
3630
                        session->temp_sdp = NULL;
3631
                        g_free(payload);
3632
                        break;
3633
                }
3634
                case janus_sipre_mqueue_event_do_accept: {
3635
                        janus_sipre_mqueue_payload *payload = (janus_sipre_mqueue_payload *)data;
3636
                        janus_sipre_session *session = (janus_sipre_session *)payload->session;
3637
                        JANUS_LOG(LOG_VERB, "[SIPre-%s] Sending 200 OK\n%s", session->account.username, session->temp_sdp);
3638
                        /* Convert the SDP into a struct mbuf */
3639
                        struct mbuf *mb = mbuf_alloc(strlen(session->temp_sdp)+1);
3640
                        mbuf_printf(mb, "%s", session->temp_sdp);
3641
                        mbuf_set_pos(mb, 0);
3642
                        /* Send the 200 OK */
3643
                        int err = sipsess_answer(session->stack.sess, 200, "OK", mb, NULL);
3644
                        if(err != 0) {
3645
                                JANUS_LOG(LOG_ERR, "Error attempting to send the 200 OK: %d (%s)\n", err, strerror(err));
3646
                                /* Tell the browser... */
3647
                                json_t *event = json_object();
3648
                                json_object_set_new(event, "sip", json_string("event"));
3649
                                json_t *result = json_object();
3650
                                json_object_set_new(result, "event", json_string("hangup"));
3651
                                json_object_set_new(result, "code", json_integer(err));
3652
                                json_object_set_new(result, "reason", json_string(strerror(err)));
3653
                                json_object_set_new(event, "result", result);
3654
                                if(!session->destroyed) {
3655
                                        int ret = gateway->push_event(session->handle, &janus_sipre_plugin, session->transaction, event, NULL);
3656
                                        JANUS_LOG(LOG_VERB, "  >> Pushing event to peer: %d (%s)\n", ret, janus_get_api_error(ret));
3657
                                }
3658
                                json_decref(event);
3659
                                /* Also notify event handlers */
3660
                                if(notify_events && gateway->events_is_enabled()) {
3661
                                        json_t *info = json_object();
3662
                                        json_object_set_new(info, "event", json_string("hangup"));
3663
                                        json_object_set_new(info, "code", json_integer(err));
3664
                                        json_object_set_new(info, "reason", json_string(strerror(err)));
3665
                                        gateway->notify_event(&janus_sipre_plugin, session->handle, info);
3666
                                }
3667
                        }
3668
                        mem_deref(mb);
3669
                        g_free(session->temp_sdp);
3670
                        session->temp_sdp = NULL;
3671
                        g_free(payload);
3672
                        break;
3673
                }
3674
                case janus_sipre_mqueue_event_do_rcode: {
3675
                        janus_sipre_mqueue_payload *payload = (janus_sipre_mqueue_payload *)data;
3676
                        janus_sipre_session *session = (janus_sipre_session *)payload->session;
3677
                        JANUS_LOG(LOG_VERB, "[SIPre-%s] Sending response code %d\n", session->account.username, payload->rcode);
3678
                        /* Send the response code */
3679
                        int err = 0;
3680
                        if(session->stack.sess == NULL) {
3681
                                /* We still need to accept the connection */
3682
                                err = sipsess_accept(&session->stack.sess, session->stack.sess_sock,
3683
                                        session->stack.invite, payload->rcode, janus_sipre_error_reason(payload->rcode),
3684
                                        session->account.display_name ? session->account.display_name : session->account.username,
3685
                                        "application/sdp", NULL,
3686
                                        janus_sipre_cb_auth, session, FALSE,
3687
                                        janus_sipre_cb_offer, janus_sipre_cb_answer,
3688
                                        janus_sipre_cb_established, NULL, NULL,
3689
                                        janus_sipre_cb_closed, session, NULL);
3690
                        } else {
3691
                                /* Connection already accepted */
3692
                                if(payload->rcode < 200) {
3693
                                        /* 1xx */
3694
                                        err = sipsess_progress(session->stack.sess, payload->rcode, janus_sipre_error_reason(payload->rcode), NULL, NULL);
3695
                                } else if(payload->rcode < 300) {
3696
                                        /* 2xx */
3697
                                        err = sipsess_answer(session->stack.sess, payload->rcode, janus_sipre_error_reason(payload->rcode), NULL, NULL);
3698
                                } else {
3699
                                        /* 3xx, 4xx, 5xx, 6xx */
3700
                                        if(payload->data == NULL) {
3701
                                                /* Send an error message on the current call */
3702
                                                err = sipsess_reject(session->stack.sess, payload->rcode, janus_sipre_error_reason(payload->rcode), NULL);
3703
                                                session->media.ready = FALSE;
3704
                                                session->media.on_hold = FALSE;
3705
                                                session->status = janus_sipre_call_status_idle;
3706
                                        } else {
3707
                                                /* We're rejecting a new call because we're busy in another one: accept first and then reject */
3708
                                                struct sipsess *sess = NULL;
3709
                                                err = sipsess_accept(&sess, session->stack.sess_sock,
3710
                                                        payload->msg, 180, janus_sipre_error_reason(180),
3711
                                                        session->account.display_name ? session->account.display_name : session->account.username,
3712
                                                        "application/sdp", NULL,
3713
                                                        janus_sipre_cb_auth, session, FALSE,
3714
                                                        janus_sipre_cb_offer, janus_sipre_cb_answer,
3715
                                                        janus_sipre_cb_established, NULL, NULL,
3716
                                                        janus_sipre_cb_closed, session, NULL);
3717
                                                err = sipsess_reject(sess, payload->rcode, janus_sipre_error_reason(payload->rcode), NULL);
3718
                                        }
3719
                                }
3720
                        }
3721
                        if(err != 0) {
3722
                                JANUS_LOG(LOG_ERR, "Error attempting to send the %d error code: %d (%s)\n", payload->rcode, err, strerror(err));
3723
                        }
3724
                        if(payload->rcode > 399) {
3725
                                g_free(session->callee);
3726
                                session->callee = NULL;
3727
                                g_free(session->callid);
3728
                                session->callid = NULL;
3729
                                /* FIXME */
3730
                                session->stack.sess = NULL;
3731
                        }
3732
                        mem_deref((void *)payload->msg);
3733
                        g_free(payload);
3734
                        break;
3735
                }
3736
                case janus_sipre_mqueue_event_do_update: {
3737
                        janus_sipre_mqueue_payload *payload = (janus_sipre_mqueue_payload *)data;
3738
                        janus_sipre_session *session = (janus_sipre_session *)payload->session;
3739
                        JANUS_LOG(LOG_VERB, "[SIPre-%s] Sending SIP re-INVITE\n", session->account.username);
3740
                        /* Convert the SDP into a struct mbuf */
3741
                        struct mbuf *mb = mbuf_alloc(strlen(session->temp_sdp)+1);
3742
                        mbuf_printf(mb, "%s", session->temp_sdp);
3743
                        mbuf_set_pos(mb, 0);
3744
                        /* Send the INVITE */
3745
                        int err = sipsess_modify(session->stack.sess, mb);
3746
                        if(err != 0) {
3747
                                JANUS_LOG(LOG_ERR, "Error attempting to re-INVITE: %d (%s)\n", err, strerror(err));
3748
                        }
3749
                        mem_deref(mb);
3750
                        g_free(session->temp_sdp);
3751
                        session->temp_sdp = NULL;
3752
                        g_free(payload);
3753
                        break;
3754
                }
3755
                case janus_sipre_mqueue_event_do_sipinfo: {
3756
                        janus_sipre_mqueue_payload *payload = (janus_sipre_mqueue_payload *)data;
3757
                        janus_sipre_session *session = (janus_sipre_session *)payload->session;
3758
                        JANUS_LOG(LOG_VERB, "[SIPre-%s] Sending SIP INFO (DTMF): %s\n", session->account.username, (char *)payload->data);
3759
                        /* Convert the SDP into a struct mbuf */
3760
                        struct mbuf *mb = mbuf_alloc(strlen((char *)payload->data)+1);
3761
                        mbuf_printf(mb, "%s", (char *)payload->data);
3762
                        mbuf_set_pos(mb, 0);
3763
                        g_free(payload->data);
3764
                        /* Send the 200 OK */
3765
                        int err = sipsess_info(session->stack.sess, "application/dtmf-relay", mb, NULL, NULL);
3766
                        if(err != 0) {
3767
                                JANUS_LOG(LOG_ERR, "Error attempting to send the SIP INFO: %d (%s)\n", err, strerror(err));
3768
                                /* Tell the browser... */
3769
                                json_t *event = json_object();
3770
                                json_object_set_new(event, "sip", json_string("event"));
3771
                                json_t *result = json_object();
3772
                                json_object_set_new(result, "event", json_string("dtmferror"));
3773
                                json_object_set_new(result, "code", json_integer(err));
3774
                                json_object_set_new(result, "reason", json_string(strerror(err)));
3775
                                json_object_set_new(event, "result", result);
3776
                        }
3777
                        mem_deref(mb);
3778
                        g_free(payload);
3779
                        break;
3780
                }
3781
                case janus_sipre_mqueue_event_do_bye: {
3782
                        janus_sipre_mqueue_payload *payload = (janus_sipre_mqueue_payload *)data;
3783
                        janus_sipre_session *session = (janus_sipre_session *)payload->session;
3784
                        JANUS_LOG(LOG_VERB, "[SIPre-%s] Sending BYE\n", session->account.username);
3785
                        /* FIXME How do we send a BYE? */
3786
                        session->stack.sess = mem_deref(session->stack.sess);
3787
                        g_free(session->callee);
3788
                        session->callee = NULL;
3789
                        g_free(payload);
3790
                        /* Tell the browser... */
3791
                        json_t *event = json_object();
3792
                        json_object_set_new(event, "sip", json_string("event"));
3793
                        json_t *result = json_object();
3794
                        json_object_set_new(result, "event", json_string("hangup"));
3795
                        json_object_set_new(result, "code", json_integer(200));
3796
                        json_object_set_new(result, "reason", json_string("BYE"));
3797
                        json_object_set_new(event, "result", result);
3798
                        if(!session->destroyed) {
3799
                                int ret = gateway->push_event(session->handle, &janus_sipre_plugin, session->transaction, event, NULL);
3800
                                JANUS_LOG(LOG_VERB, "  >> Pushing event to peer: %d (%s)\n", ret, janus_get_api_error(ret));
3801
                        }
3802
                        json_decref(event);
3803
                        /* Also notify event handlers */
3804
                        if(notify_events && gateway->events_is_enabled()) {
3805
                                json_t *info = json_object();
3806
                                json_object_set_new(info, "event", json_string("hangup"));
3807
                                json_object_set_new(info, "code", json_integer(200));
3808
                                json_object_set_new(info, "reason", json_string("BYE"));
3809
                                gateway->notify_event(&janus_sipre_plugin, session->handle, info);
3810
                        }
3811
                        session->media.ready = FALSE;
3812
                        session->media.on_hold = FALSE;
3813
                        session->status = janus_sipre_call_status_idle;
3814
                        break;
3815
                }
3816
                case janus_sipre_mqueue_event_do_destroy: {
3817
                        janus_sipre_mqueue_payload *payload = (janus_sipre_mqueue_payload *)data;
3818
                        janus_sipre_session *session = (janus_sipre_session *)payload->session;
3819
                        JANUS_LOG(LOG_VERB, "[SIPre-%s] Destroying session\n", session->account.username);
3820
                        /* FIXME How to correctly clean up? */
3821
                        sipsess_close_all(session->stack.sess_sock);
3822
                        break;
3823
                }
3824
                case janus_sipre_mqueue_event_do_exit:
3825
                        /* We're done, here, break the loop */
3826
                        re_cancel();
3827
                        break;
3828
                default:
3829
                        /* Shouldn't happen */
3830
                        break;
3831
        }
3832
}