Statistics
| Branch: | Revision:

janus-gateway / plugins / janus_sip.c @ 8241c758

History | View | Annotate | Download (144 KB)

1 be35facb meetecho
/*! \file   janus_sip.c
2
 * \author Lorenzo Miniero <lorenzo@meetecho.com>
3 9d11ac50 meetecho
 * \copyright GNU General Public License v3
4 be35facb meetecho
 * \brief  Janus SIP plugin
5
 * \details  This is a simple SIP plugin for Janus, allowing WebRTC peers
6
 * to register at a SIP server (e.g., Asterisk) and call SIP user agents
7
 * through the gateway. Specifically, when attaching to the plugin peers
8
 * are requested to provide their SIP server credentials, i.e., the address
9
 * of the SIP server and their username/secret. This results in the plugin
10
 * registering at the SIP server and acting as a SIP client on behalf of
11
 * the web peer. Most of the SIP states and lifetime are masked by the plugin,
12
 * and only the relevant events (e.g., INVITEs and BYEs) and functionality
13
 * (call, hangup) are made available to the web peer: peers can call
14
 * extensions at the SIP server or wait for incoming INVITEs, and during
15 91bc289d Lorenzo Miniero
 * a call they can send DTMF tones. Calls can do plain RTP or SDES-SRTP.
16 eeabd833 Saúl Ibarra Corretgé
 *
17 be35facb meetecho
 * The concept behind this plugin is to allow different web pages associated
18
 * to the same peer, and hence the same SIP user, to attach to the plugin
19
 * at the same time and yet just do a SIP REGISTER once. The same should
20
 * apply for calls: while an incoming call would be notified to all the
21
 * web UIs associated to the peer, only one would be able to pick up and
22
 * answer, in pretty much the same way as SIP forking works but without the
23
 * need to fork in the same place. This specific functionality, though, has
24
 * not been implemented as of yet.
25 eeabd833 Saúl Ibarra Corretgé
 *
26 6dd1c12c meetecho
 * \todo Only Asterisk and Kamailio have been tested as a SIP server, and
27
 * specifically only with basic audio calls: this plugin needs some work
28
 * to make it more stable and reliable.
29 eeabd833 Saúl Ibarra Corretgé
 *
30 02fac6b4 meetecho
 * \section sipapi SIP Plugin API
31 eeabd833 Saúl Ibarra Corretgé
 *
32 02fac6b4 meetecho
 * All requests you can send in the SIP Plugin API are asynchronous,
33
 * which means all responses (successes and errors) will be delivered
34 eeabd833 Saúl Ibarra Corretgé
 * as events with the same transaction.
35
 *
36 02fac6b4 meetecho
 * The supported requests are \c register , \c call , \c accept and
37
 * \c hangup . \c register can be used, as the name suggests, to register
38
 * a username at a SIP registrar to call and be called; \c call is used
39
 * to send an INVITE to a different SIP URI through the plugin, while
40
 * \c accept is used to accept the call in case one is invited instead
41
 * of inviting; finally, \c hangup can be used to terminate the
42
 * communication at any time, either to hangup (BYE) an ongoing call or
43
 * to cancel/decline (CANCEL/BYE) a call that hasn't started yet.
44 eeabd833 Saúl Ibarra Corretgé
 *
45 02fac6b4 meetecho
 * Actual API docs: TBD.
46 eeabd833 Saúl Ibarra Corretgé
 *
47 be35facb meetecho
 * \ingroup plugins
48
 * \ref plugins
49
 */
50
51
#include "plugin.h"
52
53 c97cb850 Saúl Ibarra Corretgé
#include <arpa/inet.h>
54 be35facb meetecho
#include <net/if.h>
55
56
#include <jansson.h>
57
58
#include <sofia-sip/msg_header.h>
59
#include <sofia-sip/nua.h>
60
#include <sofia-sip/sdp.h>
61
#include <sofia-sip/sip_status.h>
62 33f37af8 Saúl Ibarra Corretgé
#include <sofia-sip/url.h>
63 276d765d Saúl Ibarra Corretgé
#include <sofia-sip/tport_tag.h>
64 fee76880 Lorenzo Miniero
#include <sofia-sip/su_log.h>
65 be35facb meetecho
66 6bb3f34d Nicholas Wylie
#include "../debug.h"
67 3a26e009 meetecho
#include "../apierror.h"
68 be35facb meetecho
#include "../config.h"
69 3a26e009 meetecho
#include "../mutex.h"
70 6089eb4e Lorenzo Miniero
#include "../record.h"
71 f6a402e8 meetecho
#include "../rtp.h"
72
#include "../rtcp.h"
73 60e2d6d3 Lorenzo Miniero
#include "../sdp-utils.h"
74 e12d163e meetecho
#include "../utils.h"
75 be35facb meetecho
76 871c362e Lorenzo Miniero
#ifdef HAVE_SRTP_2
77
#include <srtp2/srtp.h>
78
#include <openssl/rand.h>
79
#include <openssl/err.h>
80
static int srtp_crypto_get_random(uint8_t *key, int len) {
81
        /* libsrtp 2.0 doesn't have crypto_get_random, we use OpenSSL's RAND_* to replace it:
82
         *                 https://wiki.openssl.org/index.php/Random_Numbers */
83
        int rc = RAND_bytes(key, len);
84
        if(rc != 1) {
85
                /* Error generating */
86
                JANUS_LOG(LOG_ERR, "RAND_bytes failes: %s\n", ERR_reason_error_string(ERR_get_error()));
87
                return -1;
88
        }
89
        return 0;
90
}
91
#else
92
#include <srtp/srtp.h>
93
#include <srtp/crypto_kernel.h>
94
#define srtp_err_status_t err_status_t
95
#define srtp_err_status_ok err_status_ok
96
#define srtp_err_status_replay_fail err_status_replay_fail
97
#define srtp_err_status_replay_old err_status_replay_old
98
#define srtp_crypto_policy_set_rtp_default crypto_policy_set_rtp_default
99
#define srtp_crypto_policy_set_rtcp_default crypto_policy_set_rtcp_default
100
#define srtp_crypto_policy_set_aes_cm_128_hmac_sha1_32 crypto_policy_set_aes_cm_128_hmac_sha1_32
101
#define srtp_crypto_policy_set_aes_cm_128_hmac_sha1_80 crypto_policy_set_aes_cm_128_hmac_sha1_80
102
#define srtp_crypto_get_random crypto_get_random
103
#endif
104
105 be35facb meetecho
106
/* Plugin information */
107 5ac3e902 richstorm
#define JANUS_SIP_VERSION                        6
108
#define JANUS_SIP_VERSION_STRING        "0.0.6"
109 be35facb meetecho
#define JANUS_SIP_DESCRIPTION                "This is a simple SIP plugin for Janus, allowing WebRTC peers to register at a SIP server and call SIP user agents through the gateway."
110
#define JANUS_SIP_NAME                                "JANUS SIP plugin"
111 a3d13e20 meetecho
#define JANUS_SIP_AUTHOR                        "Meetecho s.r.l."
112 be35facb meetecho
#define JANUS_SIP_PACKAGE                        "janus.plugin.sip"
113
114
/* Plugin methods */
115
janus_plugin *create(void);
116
int janus_sip_init(janus_callbacks *callback, const char *config_path);
117
void janus_sip_destroy(void);
118 667b2005 meetecho
int janus_sip_get_api_compatibility(void);
119 be35facb meetecho
int janus_sip_get_version(void);
120
const char *janus_sip_get_version_string(void);
121
const char *janus_sip_get_description(void);
122
const char *janus_sip_get_name(void);
123 a3d13e20 meetecho
const char *janus_sip_get_author(void);
124 be35facb meetecho
const char *janus_sip_get_package(void);
125 cfd5c0d6 meetecho
void janus_sip_create_session(janus_plugin_session *handle, int *error);
126 dd11fa0a Lorenzo Miniero
struct janus_plugin_result *janus_sip_handle_message(janus_plugin_session *handle, char *transaction, json_t *message, json_t *jsep);
127 cfd5c0d6 meetecho
void janus_sip_setup_media(janus_plugin_session *handle);
128
void janus_sip_incoming_rtp(janus_plugin_session *handle, int video, char *buf, int len);
129
void janus_sip_incoming_rtcp(janus_plugin_session *handle, int video, char *buf, int len);
130
void janus_sip_hangup_media(janus_plugin_session *handle);
131
void janus_sip_destroy_session(janus_plugin_session *handle, int *error);
132 dd11fa0a Lorenzo Miniero
json_t *janus_sip_query_session(janus_plugin_session *handle);
133 be35facb meetecho
134
/* Plugin setup */
135
static janus_plugin janus_sip_plugin =
136 1281ca86 meetecho
        JANUS_PLUGIN_INIT (
137 be35facb meetecho
                .init = janus_sip_init,
138
                .destroy = janus_sip_destroy,
139
140 667b2005 meetecho
                .get_api_compatibility = janus_sip_get_api_compatibility,
141 be35facb meetecho
                .get_version = janus_sip_get_version,
142
                .get_version_string = janus_sip_get_version_string,
143
                .get_description = janus_sip_get_description,
144
                .get_name = janus_sip_get_name,
145 a3d13e20 meetecho
                .get_author = janus_sip_get_author,
146 be35facb meetecho
                .get_package = janus_sip_get_package,
147 eeabd833 Saúl Ibarra Corretgé
148 be35facb meetecho
                .create_session = janus_sip_create_session,
149
                .handle_message = janus_sip_handle_message,
150
                .setup_media = janus_sip_setup_media,
151
                .incoming_rtp = janus_sip_incoming_rtp,
152
                .incoming_rtcp = janus_sip_incoming_rtcp,
153
                .hangup_media = janus_sip_hangup_media,
154
                .destroy_session = janus_sip_destroy_session,
155 667b2005 meetecho
                .query_session = janus_sip_query_session,
156 1281ca86 meetecho
        );
157 be35facb meetecho
158
/* Plugin creator */
159
janus_plugin *create(void) {
160 3a26e009 meetecho
        JANUS_LOG(LOG_VERB, "%s created!\n", JANUS_SIP_NAME);
161 be35facb meetecho
        return &janus_sip_plugin;
162
}
163
164 94926fcd Andreas Girgensohn
/* Parameter validation */
165
static struct janus_json_parameter request_parameters[] = {
166
        {"request", JSON_STRING, JANUS_JSON_PARAM_REQUIRED}
167
};
168
static struct janus_json_parameter register_parameters[] = {
169
        {"type", JSON_STRING, 0},
170
        {"send_register", JANUS_JSON_BOOL, 0},
171
        {"sips", JANUS_JSON_BOOL, 0},
172
        {"username", JSON_STRING, 0},
173
        {"secret", JSON_STRING, 0},
174
        {"ha1_secret", JSON_STRING, 0},
175
        {"authuser", JSON_STRING, 0}
176
};
177
static struct janus_json_parameter proxy_parameters[] = {
178
        {"proxy", JSON_STRING, 0}
179
};
180
static struct janus_json_parameter call_parameters[] = {
181
        {"uri", JSON_STRING, JANUS_JSON_PARAM_REQUIRED},
182 1a4bc02f Lorenzo Miniero
        {"autoack", JANUS_JSON_BOOL, 0},
183 94926fcd Andreas Girgensohn
        {"headers", JSON_OBJECT, 0},
184
        {"srtp", JSON_STRING, 0}
185
};
186
static struct janus_json_parameter accept_parameters[] = {
187
        {"srtp", JSON_STRING, 0}
188
};
189
static struct janus_json_parameter recording_parameters[] = {
190
        {"action", JSON_STRING, JANUS_JSON_PARAM_REQUIRED},
191
        {"audio", JANUS_JSON_BOOL, 0},
192
        {"video", JANUS_JSON_BOOL, 0},
193
        {"peer_audio", JANUS_JSON_BOOL, 0},
194
        {"peer_video", JANUS_JSON_BOOL, 0},
195
        {"filename", JSON_STRING, 0}
196
};
197
static struct janus_json_parameter dtmf_info_parameters[] = {
198
        {"digit", JSON_STRING, JANUS_JSON_PARAM_REQUIRED},
199
        {"duration", JSON_INTEGER, JANUS_JSON_PARAM_POSITIVE}
200
};
201 be35facb meetecho
202
/* Useful stuff */
203 4239218c meetecho
static volatile gint initialized = 0, stopping = 0;
204 71a04f89 Lorenzo Miniero
static gboolean notify_events = TRUE;
205 be35facb meetecho
static janus_callbacks *gateway = NULL;
206 8d3af711 Saúl Ibarra Corretgé
207 c97cb850 Saúl Ibarra Corretgé
static char local_ip[INET6_ADDRSTRLEN];
208 8d3af711 Saúl Ibarra Corretgé
static int keepalive_interval = 120;
209 49f09b14 Saúl Ibarra Corretgé
static gboolean behind_nat = FALSE;
210 cb2b1f3d Saúl Ibarra Corretgé
static char *user_agent;
211 0270beb3 Saúl Ibarra Corretgé
#define JANUS_DEFAULT_REGISTER_TTL        3600
212
static int register_ttl = JANUS_DEFAULT_REGISTER_TTL;
213 be35facb meetecho
214
static GThread *handler_thread;
215 dbf63b61 meetecho
static GThread *watchdog;
216 be35facb meetecho
static void *janus_sip_handler(void *data);
217
218
typedef struct janus_sip_message {
219 cfd5c0d6 meetecho
        janus_plugin_session *handle;
220 be35facb meetecho
        char *transaction;
221 dd11fa0a Lorenzo Miniero
        json_t *message;
222
        json_t *jsep;
223 be35facb meetecho
} janus_sip_message;
224 4d13c20d meetecho
static GAsyncQueue *messages = NULL;
225 b9e8b01f Lorenzo Miniero
static janus_sip_message exit_message;
226 be35facb meetecho
227 90e0cdb4 Lorenzo Miniero
static void janus_sip_message_free(janus_sip_message *msg) {
228
        if(!msg || msg == &exit_message)
229 3a26e009 meetecho
                return;
230 4d13c20d meetecho
231 3a26e009 meetecho
        msg->handle = NULL;
232 4d13c20d meetecho
233
        g_free(msg->transaction);
234 3a26e009 meetecho
        msg->transaction = NULL;
235 dd11fa0a Lorenzo Miniero
        if(msg->message)
236
                json_decref(msg->message);
237 3a26e009 meetecho
        msg->message = NULL;
238 dd11fa0a Lorenzo Miniero
        if(msg->jsep)
239
                json_decref(msg->jsep);
240
        msg->jsep = NULL;
241 4d13c20d meetecho
242 3a26e009 meetecho
        g_free(msg);
243
}
244
245
246 ad872005 Saúl Ibarra Corretgé
typedef enum {
247 735be1e9 Saúl Ibarra Corretgé
        janus_sip_registration_status_disabled = -2,
248 ad872005 Saúl Ibarra Corretgé
        janus_sip_registration_status_failed = -1,
249
        janus_sip_registration_status_unregistered = 0,
250
        janus_sip_registration_status_registering,
251
        janus_sip_registration_status_registered,
252
        janus_sip_registration_status_unregistering,
253
} janus_sip_registration_status;
254
255
static const char *janus_sip_registration_status_string(janus_sip_registration_status status) {
256 71f7ef5a meetecho
        switch(status) {
257 735be1e9 Saúl Ibarra Corretgé
                case janus_sip_registration_status_disabled:
258
                        return "disabled";
259 ad872005 Saúl Ibarra Corretgé
                case janus_sip_registration_status_failed:
260 71f7ef5a meetecho
                        return "failed";
261 ad872005 Saúl Ibarra Corretgé
                case janus_sip_registration_status_unregistered:
262 71f7ef5a meetecho
                        return "unregistered";
263 ad872005 Saúl Ibarra Corretgé
                case janus_sip_registration_status_registering:
264 71f7ef5a meetecho
                        return "registering";
265 ad872005 Saúl Ibarra Corretgé
                case janus_sip_registration_status_registered:
266 71f7ef5a meetecho
                        return "registered";
267 ad872005 Saúl Ibarra Corretgé
                case janus_sip_registration_status_unregistering:
268
                        return "unregistering";
269
                default:
270
                        return "unknown";
271
        }
272
}
273
274
275
typedef enum {
276
        janus_sip_call_status_idle = 0,
277
        janus_sip_call_status_inviting,
278
        janus_sip_call_status_invited,
279
        janus_sip_call_status_incall,
280
        janus_sip_call_status_closing,
281
} janus_sip_call_status;
282
283
static const char *janus_sip_call_status_string(janus_sip_call_status status) {
284
        switch(status) {
285
                case janus_sip_call_status_idle:
286
                        return "idle";
287
                case janus_sip_call_status_inviting:
288 71f7ef5a meetecho
                        return "inviting";
289 ad872005 Saúl Ibarra Corretgé
                case janus_sip_call_status_invited:
290 71f7ef5a meetecho
                        return "invited";
291 ad872005 Saúl Ibarra Corretgé
                case janus_sip_call_status_incall:
292 71f7ef5a meetecho
                        return "incall";
293 ad872005 Saúl Ibarra Corretgé
                case janus_sip_call_status_closing:
294 71f7ef5a meetecho
                        return "closing";
295
                default:
296 ad872005 Saúl Ibarra Corretgé
                        return "unknown";
297 71f7ef5a meetecho
        }
298
}
299 be35facb meetecho
300
301
/* Sofia stuff */
302
typedef struct ssip_s ssip_t;
303
typedef struct ssip_oper_s ssip_oper_t;
304
305 6da4d93c Saúl Ibarra Corretgé
typedef enum {
306
        janus_sip_secret_type_plaintext = 1,
307
        janus_sip_secret_type_hashed = 2,
308
        janus_sip_secret_type_unknown
309
} janus_sip_secret_type;
310
311 be35facb meetecho
typedef struct janus_sip_account {
312 a37dd8a2 meetecho
        char *identity;
313 372e28b5 Saúl Ibarra Corretgé
        char *user_agent;                /* Used to override the general UA string */
314 43a3a2dc Lorenzo Miniero
        gboolean sips;
315 be35facb meetecho
        char *username;
316 147173bd Saúl Ibarra Corretgé
        char *display_name;                /* Used for outgoing calls in the From header */
317 99f4b957 tuijldert
        char *authuser;                        /**< username to use for authentication */
318 be35facb meetecho
        char *secret;
319 6da4d93c Saúl Ibarra Corretgé
        janus_sip_secret_type secret_type;
320 be35facb meetecho
        int sip_port;
321 a37dd8a2 meetecho
        char *proxy;
322 ad872005 Saúl Ibarra Corretgé
        janus_sip_registration_status registration_status;
323 be35facb meetecho
} janus_sip_account;
324
325 4d8ee7e6 Lorenzo Miniero
typedef struct janus_sip_rtp_context {
326
        /* Needed to fix seq and ts in case of re-INVITEs/UPDATEs that result in a RTP stream */
327
        uint32_t a_last_ssrc, a_last_ts, a_base_ts, a_base_ts_prev,
328
                        v_last_ssrc, v_last_ts, v_base_ts, v_base_ts_prev;
329
        uint16_t a_last_seq, a_base_seq, a_base_seq_prev,
330
                        v_last_seq, v_base_seq, v_base_seq_prev;
331
} janus_sip_rtp_context;
332
333 be35facb meetecho
typedef struct janus_sip_media {
334 a37dd8a2 meetecho
        char *remote_ip;
335 be35facb meetecho
        int ready:1;
336 1a4bc02f Lorenzo Miniero
        gboolean autoack;
337 ac36fd1d Lorenzo Miniero
        gboolean require_srtp, has_srtp_local, has_srtp_remote;
338 be35facb meetecho
        int has_audio:1;
339
        int audio_rtp_fd, audio_rtcp_fd;
340
        int local_audio_rtp_port, remote_audio_rtp_port;
341
        int local_audio_rtcp_port, remote_audio_rtcp_port;
342 f6a402e8 meetecho
        guint32 audio_ssrc, audio_ssrc_peer;
343 02eeeba4 Lorenzo Miniero
        int audio_pt;
344
        const char *audio_pt_name;
345 91bc289d Lorenzo Miniero
        srtp_t audio_srtp_in, audio_srtp_out;
346
        srtp_policy_t audio_remote_policy, audio_local_policy;
347
        int audio_srtp_suite_in, audio_srtp_suite_out;
348 4d8ee7e6 Lorenzo Miniero
        gboolean audio_send;
349 be35facb meetecho
        int has_video:1;
350
        int video_rtp_fd, video_rtcp_fd;
351
        int local_video_rtp_port, remote_video_rtp_port;
352
        int local_video_rtcp_port, remote_video_rtcp_port;
353 f6a402e8 meetecho
        guint32 video_ssrc, video_ssrc_peer;
354 02eeeba4 Lorenzo Miniero
        int video_pt;
355
        const char *video_pt_name;
356 91bc289d Lorenzo Miniero
        srtp_t video_srtp_in, video_srtp_out;
357
        srtp_policy_t video_remote_policy, video_local_policy;
358
        int video_srtp_suite_in, video_srtp_suite_out;
359 4d8ee7e6 Lorenzo Miniero
        gboolean video_send;
360
        janus_sip_rtp_context context;
361
        int pipefd[2];
362
        gboolean updated;
363 be35facb meetecho
} janus_sip_media;
364
365
typedef struct janus_sip_session {
366 cfd5c0d6 meetecho
        janus_plugin_session *handle;
367 be35facb meetecho
        ssip_t *stack;
368
        janus_sip_account account;
369 ad872005 Saúl Ibarra Corretgé
        janus_sip_call_status status;
370 be35facb meetecho
        janus_sip_media media;
371 91b1c78a meetecho
        char *transaction;
372 be35facb meetecho
        char *callee;
373 4d8c7356 Lorenzo Miniero
        char *callid;
374 4d8ee7e6 Lorenzo Miniero
        janus_sdp *sdp;                                /* The SDP this user sent */
375 6089eb4e Lorenzo Miniero
        janus_recorder *arc;                /* The Janus recorder instance for this user's audio, if enabled */
376
        janus_recorder *arc_peer;        /* The Janus recorder instance for the peer's audio, if enabled */
377
        janus_recorder *vrc;                /* The Janus recorder instance for this user's video, if enabled */
378
        janus_recorder *vrc_peer;        /* The Janus recorder instance for the peer's video, if enabled */
379 d223cef1 Lorenzo Miniero
        janus_mutex rec_mutex;                /* Mutex to protect the recorders from race conditions */
380 4239218c meetecho
        volatile gint hangingup;
381 78955474 meetecho
        gint64 destroyed;        /* Time at which this session was marked as destroyed */
382 a37dd8a2 meetecho
        janus_mutex mutex;
383 be35facb meetecho
} janus_sip_session;
384 506f60ae Jack Leigh
static GHashTable *sessions;
385 5fa9a305 meetecho
static GList *old_sessions;
386 fee76880 Lorenzo Miniero
static GHashTable *identities;
387
static GHashTable *callids;
388 506f60ae Jack Leigh
static janus_mutex sessions_mutex;
389 be35facb meetecho
390
391
#undef SU_ROOT_MAGIC_T
392
#define SU_ROOT_MAGIC_T        ssip_t
393
#undef NUA_MAGIC_T
394
#define NUA_MAGIC_T                ssip_t
395
#undef NUA_HMAGIC_T
396
#define NUA_HMAGIC_T        ssip_oper_t
397
398
struct ssip_s {
399
        su_home_t s_home[1];
400
        su_root_t *s_root;
401
        nua_t *s_nua;
402
        nua_handle_t *s_nh_r, *s_nh_i;
403
        janus_sip_session *session;
404
};
405
406
407 91bc289d Lorenzo Miniero
/* SRTP stuff (in case we need SDES) */
408
#define SRTP_MASTER_KEY_LENGTH        16
409
#define SRTP_MASTER_SALT_LENGTH        14
410
#define SRTP_MASTER_LENGTH (SRTP_MASTER_KEY_LENGTH + SRTP_MASTER_SALT_LENGTH)
411
static const char *janus_sip_srtp_error[] =
412
{
413 871c362e Lorenzo Miniero
        "srtp_err_status_ok",
414
        "srtp_err_status_fail",
415
        "srtp_err_status_bad_param",
416
        "srtp_err_status_alloc_fail",
417
        "srtp_err_status_dealloc_fail",
418
        "srtp_err_status_init_fail",
419
        "srtp_err_status_terminus",
420
        "srtp_err_status_auth_fail",
421
        "srtp_err_status_cipher_fail",
422
        "srtp_err_status_replay_fail",
423
        "srtp_err_status_replay_old",
424
        "srtp_err_status_algo_fail",
425
        "srtp_err_status_no_such_op",
426
        "srtp_err_status_no_ctx",
427
        "srtp_err_status_cant_check",
428
        "srtp_err_status_key_expired",
429
        "srtp_err_status_socket_err",
430
        "srtp_err_status_signal_err",
431
        "srtp_err_status_nonce_bad",
432
        "srtp_err_status_read_fail",
433
        "srtp_err_status_write_fail",
434
        "srtp_err_status_parse_err",
435
        "srtp_err_status_encode_err",
436
        "srtp_err_status_semaphore_err",
437
        "srtp_err_status_pfkey_err",
438 91bc289d Lorenzo Miniero
};
439
static const gchar *janus_sip_get_srtp_error(int error) {
440
        if(error < 0 || error > 24)
441
                return NULL;
442
        return janus_sip_srtp_error[error];
443
}
444
static int janus_sip_srtp_set_local(janus_sip_session *session, gboolean video, char **crypto) {
445
        if(session == NULL)
446
                return -1;
447
        /* Generate key/salt */
448
        uint8_t *key = g_malloc0(SRTP_MASTER_LENGTH);
449 871c362e Lorenzo Miniero
        srtp_crypto_get_random(key, SRTP_MASTER_LENGTH);
450 91bc289d Lorenzo Miniero
        /* Set SRTP policies */
451
        srtp_policy_t *policy = video ? &session->media.video_local_policy : &session->media.audio_local_policy;
452 871c362e Lorenzo Miniero
        srtp_crypto_policy_set_rtp_default(&(policy->rtp));
453
        srtp_crypto_policy_set_rtcp_default(&(policy->rtcp));
454 91bc289d Lorenzo Miniero
        policy->ssrc.type = ssrc_any_inbound;
455
        policy->key = key;
456
        policy->next = NULL;
457
        /* Create SRTP context */
458 871c362e Lorenzo Miniero
        srtp_err_status_t res = srtp_create(video ? &session->media.video_srtp_out : &session->media.audio_srtp_out, policy);
459
        if(res != srtp_err_status_ok) {
460 91bc289d Lorenzo Miniero
                /* Something went wrong... */
461
                JANUS_LOG(LOG_ERR, "Oops, error creating outbound SRTP session: %d (%s)\n", res, janus_sip_get_srtp_error(res));
462
                g_free(key);
463
                policy->key = NULL;
464
                return -2;
465
        }
466
        /* Base64 encode the salt */
467
        *crypto = g_base64_encode(key, SRTP_MASTER_LENGTH);
468
        if((video && session->media.video_srtp_out) || (!video && session->media.audio_srtp_out)) {
469 203da285 Lorenzo Miniero
                JANUS_LOG(LOG_VERB, "%s outbound SRTP session created\n", video ? "Video" : "Audio");
470 91bc289d Lorenzo Miniero
        }
471
        return 0;
472
}
473
static int janus_sip_srtp_set_remote(janus_sip_session *session, gboolean video, const char *crypto, int suite) {
474
        if(session == NULL || crypto == NULL)
475
                return -1;
476
        /* Base64 decode the crypto string and set it as the remote SRTP context */
477
        gsize len = 0;
478
        guchar *decoded = g_base64_decode(crypto, &len);
479
        if(len < SRTP_MASTER_LENGTH) {
480
                /* FIXME Can this happen? */
481
                g_free(decoded);
482
                return -2;
483
        }
484
        /* Set SRTP policies */
485
        srtp_policy_t *policy = video ? &session->media.video_remote_policy : &session->media.audio_remote_policy;
486 871c362e Lorenzo Miniero
        srtp_crypto_policy_set_rtp_default(&(policy->rtp));
487
        srtp_crypto_policy_set_rtcp_default(&(policy->rtcp));
488 91bc289d Lorenzo Miniero
        if(suite == 32) {
489 871c362e Lorenzo Miniero
                srtp_crypto_policy_set_aes_cm_128_hmac_sha1_32(&(policy->rtp));
490
                srtp_crypto_policy_set_aes_cm_128_hmac_sha1_32(&(policy->rtcp));
491 91bc289d Lorenzo Miniero
        } else if(suite == 80) {
492 871c362e Lorenzo Miniero
                srtp_crypto_policy_set_aes_cm_128_hmac_sha1_80(&(policy->rtp));
493
                srtp_crypto_policy_set_aes_cm_128_hmac_sha1_80(&(policy->rtcp));
494 91bc289d Lorenzo Miniero
        }
495
        policy->ssrc.type = ssrc_any_inbound;
496
        policy->key = decoded;
497
        policy->next = NULL;
498
        /* Create SRTP context */
499 871c362e Lorenzo Miniero
        srtp_err_status_t res = srtp_create(video ? &session->media.video_srtp_in : &session->media.audio_srtp_in, policy);
500
        if(res != srtp_err_status_ok) {
501 91bc289d Lorenzo Miniero
                /* Something went wrong... */
502
                JANUS_LOG(LOG_ERR, "Oops, error creating inbound SRTP session: %d (%s)\n", res, janus_sip_get_srtp_error(res));
503
                g_free(decoded);
504
                policy->key = NULL;
505
                return -2;
506
        }
507
        if((video && session->media.video_srtp_in) || (!video && session->media.audio_srtp_in)) {
508 203da285 Lorenzo Miniero
                JANUS_LOG(LOG_VERB, "%s inbound SRTP session created\n", video ? "Video" : "Audio");
509 91bc289d Lorenzo Miniero
        }
510
        return 0;
511
}
512
static void janus_sip_srtp_cleanup(janus_sip_session *session) {
513
        if(session == NULL)
514
                return;
515 1a4bc02f Lorenzo Miniero
        session->media.autoack = TRUE;
516 ac36fd1d Lorenzo Miniero
        session->media.require_srtp = FALSE;
517 91bc289d Lorenzo Miniero
        session->media.has_srtp_local = FALSE;
518
        session->media.has_srtp_remote = FALSE;
519
        /* Audio */
520
        if(session->media.audio_srtp_out)
521
                srtp_dealloc(session->media.audio_srtp_out);
522
        session->media.audio_srtp_out = NULL;
523
        g_free(session->media.audio_local_policy.key);
524
        session->media.audio_local_policy.key = NULL;
525 ed66f503 Lorenzo Miniero
        session->media.audio_srtp_suite_out = 0;
526 91bc289d Lorenzo Miniero
        if(session->media.audio_srtp_in)
527
                srtp_dealloc(session->media.audio_srtp_in);
528
        session->media.audio_srtp_in = NULL;
529
        g_free(session->media.audio_remote_policy.key);
530
        session->media.audio_remote_policy.key = NULL;
531 ed66f503 Lorenzo Miniero
        session->media.audio_srtp_suite_in = 0;
532 91bc289d Lorenzo Miniero
        /* Video */
533
        if(session->media.video_srtp_out)
534
                srtp_dealloc(session->media.video_srtp_out);
535
        session->media.video_srtp_out = NULL;
536
        g_free(session->media.video_local_policy.key);
537
        session->media.video_local_policy.key = NULL;
538
        session->media.video_srtp_suite_out = 0;
539
        if(session->media.video_srtp_in)
540
                srtp_dealloc(session->media.video_srtp_in);
541
        session->media.video_srtp_in = NULL;
542
        g_free(session->media.video_remote_policy.key);
543
        session->media.video_remote_policy.key = NULL;
544 ed66f503 Lorenzo Miniero
        session->media.video_srtp_suite_in = 0;
545 91bc289d Lorenzo Miniero
}
546
547
548 be35facb meetecho
/* Sofia Event thread */
549
gpointer janus_sip_sofia_thread(gpointer user_data);
550
/* Sofia callbacks */
551
void janus_sip_sofia_callback(nua_event_t event, int status, char const *phrase, nua_t *nua, nua_magic_t *magic, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tags[]);
552 203da285 Lorenzo Miniero
/* SDP parsing and manipulation */
553 4d8ee7e6 Lorenzo Miniero
void janus_sip_sdp_process(janus_sip_session *session, janus_sdp *sdp, gboolean answer, gboolean update, gboolean *changed);
554 60e2d6d3 Lorenzo Miniero
char *janus_sip_sdp_manipulate(janus_sip_session *session, janus_sdp *sdp, gboolean answer);
555 be35facb meetecho
/* Media */
556
static int janus_sip_allocate_local_ports(janus_sip_session *session);
557
static void *janus_sip_relay_thread(void *data);
558
559
560 33f37af8 Saúl Ibarra Corretgé
/* URI parsing utilies */
561
562
#define JANUS_SIP_URI_MAXLEN        1024
563
typedef struct {
564
        char data[JANUS_SIP_URI_MAXLEN];
565
        url_t url[1];
566
} janus_sip_uri_t;
567
568
/* Parses a SIP URI (SIPS is not supported), returns 0 on success, -1 otherwise */
569
static int janus_sip_parse_uri(janus_sip_uri_t *sip_uri, const char *data) {
570
        g_strlcpy(sip_uri->data, data, JANUS_SIP_URI_MAXLEN);
571
        if (url_d(sip_uri->url, sip_uri->data) < 0 || sip_uri->url->url_type != url_sip)
572
                return -1;
573
        return 0;
574
}
575
576 a78520c4 Lorenzo Miniero
/* Similar to the above function, but it also accepts SIPS URIs */
577 33f37af8 Saúl Ibarra Corretgé
static int janus_sip_parse_proxy_uri(janus_sip_uri_t *sip_uri, const char *data) {
578
        g_strlcpy(sip_uri->data, data, JANUS_SIP_URI_MAXLEN);
579
        if (url_d(sip_uri->url, sip_uri->data) < 0 || (sip_uri->url->url_type != url_sip && sip_uri->url->url_type != url_sips))
580
                return -1;
581
        return 0;
582
}
583
584 3cc3cab3 meetecho
/* Error codes */
585
#define JANUS_SIP_ERROR_UNKNOWN_ERROR                499
586
#define JANUS_SIP_ERROR_NO_MESSAGE                        440
587
#define JANUS_SIP_ERROR_INVALID_JSON                441
588
#define JANUS_SIP_ERROR_INVALID_REQUEST                442
589
#define JANUS_SIP_ERROR_MISSING_ELEMENT                443
590
#define JANUS_SIP_ERROR_INVALID_ELEMENT                444
591
#define JANUS_SIP_ERROR_ALREADY_REGISTERED        445
592
#define JANUS_SIP_ERROR_INVALID_ADDRESS                446
593
#define JANUS_SIP_ERROR_WRONG_STATE                        447
594
#define JANUS_SIP_ERROR_MISSING_SDP                        448
595
#define JANUS_SIP_ERROR_LIBSOFIA_ERROR                449
596
#define JANUS_SIP_ERROR_IO_ERROR                        450
597 6089eb4e Lorenzo Miniero
#define JANUS_SIP_ERROR_RECORDING_ERROR                451
598 ac36fd1d Lorenzo Miniero
#define JANUS_SIP_ERROR_TOO_STRICT                        452
599 3cc3cab3 meetecho
600
601 5fa9a305 meetecho
/* SIP watchdog/garbage collector (sort of) */
602
void *janus_sip_watchdog(void *data);
603
void *janus_sip_watchdog(void *data) {
604
        JANUS_LOG(LOG_INFO, "SIP watchdog started\n");
605
        gint64 now = 0;
606 dbf63b61 meetecho
        while(g_atomic_int_get(&initialized) && !g_atomic_int_get(&stopping)) {
607 5fa9a305 meetecho
                janus_mutex_lock(&sessions_mutex);
608
                /* Iterate on all the sessions */
609
                now = janus_get_monotonic_time();
610
                if(old_sessions != NULL) {
611
                        GList *sl = old_sessions;
612 1281ca86 meetecho
                        JANUS_LOG(LOG_HUGE, "Checking %d old SIP sessions...\n", g_list_length(old_sessions));
613 5fa9a305 meetecho
                        while(sl) {
614
                                janus_sip_session *session = (janus_sip_session *)sl->data;
615 dbf63b61 meetecho
                                if(!session) {
616 5fa9a305 meetecho
                                        sl = sl->next;
617
                                        continue;
618
                                }
619 6c5a0b90 MichaelB76
                                if (now-session->destroyed >= 5*G_USEC_PER_SEC) {
620 5fa9a305 meetecho
                                        /* We're lazy and actually get rid of the stuff only after a few seconds */
621 1281ca86 meetecho
                                        JANUS_LOG(LOG_VERB, "Freeing old SIP session\n");
622 5fa9a305 meetecho
                                        GList *rm = sl->next;
623
                                        old_sessions = g_list_delete_link(old_sessions, sl);
624 6c5a0b90 MichaelB76
                                        sl = rm;
625 d6ab329d MichaelB76
                                        if (session->account.identity) {
626 fee76880 Lorenzo Miniero
                                            g_hash_table_remove(identities, session->account.identity);
627 d6ab329d MichaelB76
                                            g_free(session->account.identity);
628
                                            session->account.identity = NULL;
629
                                        }
630 43a3a2dc Lorenzo Miniero
                                        session->account.sips = TRUE;
631 d6ab329d MichaelB76
                                        if (session->account.proxy) {
632
                                            g_free(session->account.proxy);
633
                                            session->account.proxy = NULL;
634
                                        }
635
                                        if (session->account.secret) {
636
                                            g_free(session->account.secret);
637
                                            session->account.secret = NULL;
638
                                        }
639
                                        if (session->account.username) {
640
                                            g_free(session->account.username);
641
                                            session->account.username = NULL;
642
                                        }
643 147173bd Saúl Ibarra Corretgé
                                        if (session->account.display_name) {
644
                                            g_free(session->account.display_name);
645
                                            session->account.display_name = NULL;
646
                                        }
647 372e28b5 Saúl Ibarra Corretgé
                                        if (session->account.user_agent) {
648
                                            g_free(session->account.user_agent);
649
                                            session->account.user_agent = NULL;
650
                                        }
651 86ba5bd2 tuijldert
                                        if (session->account.authuser) {
652
                                            g_free(session->account.authuser);
653
                                            session->account.authuser = NULL;
654
                                        }
655 6c5a0b90 MichaelB76
                                        if (session->callee) {
656
                                            g_free(session->callee);
657
                                            session->callee = NULL;
658
                                        }
659 4d8c7356 Lorenzo Miniero
                                        if (session->callid) {
660 fee76880 Lorenzo Miniero
                                            g_hash_table_remove(callids, session->callid);
661 4d8c7356 Lorenzo Miniero
                                            g_free(session->callid);
662
                                            session->callid = NULL;
663
                                        }
664 4d8ee7e6 Lorenzo Miniero
                                        if (session->sdp) {
665
                                            janus_sdp_free(session->sdp);
666
                                            session->sdp = NULL;
667
                                        }
668 6c5a0b90 MichaelB76
                                        if (session->transaction) {
669
                                            g_free(session->transaction);
670
                                            session->transaction = NULL;
671
                                        }
672 d6ab329d MichaelB76
                                        if (session->media.remote_ip) {
673
                                            g_free(session->media.remote_ip);
674
                                            session->media.remote_ip = NULL;
675 6c5a0b90 MichaelB76
                                        }
676 91bc289d Lorenzo Miniero
                                        janus_sip_srtp_cleanup(session);
677 6c5a0b90 MichaelB76
                                        session->handle = NULL;
678 5fa9a305 meetecho
                                        g_free(session);
679
                                        session = NULL;
680
                                        continue;
681
                                }
682
                                sl = sl->next;
683
                        }
684
                }
685
                janus_mutex_unlock(&sessions_mutex);
686 1e2f5d89 meetecho
                g_usleep(500000);
687 5fa9a305 meetecho
        }
688
        JANUS_LOG(LOG_INFO, "SIP watchdog stopped\n");
689
        return NULL;
690
}
691
692
693 575c9ada Saúl Ibarra Corretgé
static void janus_sip_detect_local_ip(char *buf, size_t buflen) {
694 77d8e4c0 Saúl Ibarra Corretgé
        JANUS_LOG(LOG_VERB, "Autodetecting local IP...\n");
695
696
        struct sockaddr_in addr;
697
        socklen_t len;
698
        int fd = socket(AF_INET, SOCK_DGRAM, 0);
699
        if (fd == -1)
700
                goto error;
701
        addr.sin_family = AF_INET;
702
        addr.sin_port = htons(1);
703
        inet_pton(AF_INET, "1.2.3.4", &addr.sin_addr.s_addr);
704
        if (connect(fd, (const struct sockaddr*) &addr, sizeof(addr)) < 0)
705
                goto error;
706
        len = sizeof(addr);
707
        if (getsockname(fd, (struct sockaddr*) &addr, &len) < 0)
708
                goto error;
709 bcb7ee3c Saúl Ibarra Corretgé
        if (getnameinfo((const struct sockaddr*) &addr, sizeof(addr),
710 575c9ada Saúl Ibarra Corretgé
                        buf, buflen,
711 bcb7ee3c Saúl Ibarra Corretgé
                        NULL, 0, NI_NUMERICHOST) != 0)
712
                goto error;
713 9b74bab0 Saúl Ibarra Corretgé
        close(fd);
714 77d8e4c0 Saúl Ibarra Corretgé
        return;
715
716
error:
717
        if (fd != -1)
718
                close(fd);
719
        JANUS_LOG(LOG_VERB, "Couldn't find any address! using 127.0.0.1 as the local IP... (which is NOT going to work out of your machine)\n");
720 575c9ada Saúl Ibarra Corretgé
        g_strlcpy(buf, "127.0.0.1", buflen);
721 c97cb850 Saúl Ibarra Corretgé
}
722
723
724 4d8c7356 Lorenzo Miniero
/* Random string helper (for call-ids) */
725
static char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
726
static void janus_sip_random_string(int length, char *buffer) {
727
        if(length > 0 && buffer) {
728
                int l = (int)(sizeof(charset)-1);
729
                int i=0;
730
                for(i=0; i<length; i++) {
731
                        int key = rand() % l;
732
                        buffer[i] = charset[key];
733
                }
734
                buffer[length-1] = '\0';
735
        }
736
}
737
738
739 fee76880 Lorenzo Miniero
/* Sofia SIP logger function: when the Event Handlers mechanism is enabled,
740
 * we use this to intercept SIP messages sent by the stack (received
741
 * messages are more easily recoverable in janus_sip_sofia_callback) */
742
char sofia_log[2048];
743
char call_id[255];
744
gboolean skip = FALSE, started = FALSE, append = FALSE;
745
static void janus_sip_sofia_logger(void *stream, char const *fmt, va_list ap) {
746
        if(!fmt)
747
                return;
748
        char line[255];
749
        g_vsnprintf(line, sizeof(line), fmt, ap);
750
        if(skip) {
751
                /* This is a message we're not interested in: just check when it ends */
752
                if(line[3] == '-') {
753
                        skip = FALSE;
754
                        append = FALSE;
755
                }
756
                return;
757
        }
758
        if(append) {
759
                /* We're copying a message in our buffer: check if this is the end */
760
                if(line[3] == '-') {
761
                        if(!started) {
762
                                /* Ok, start appending from now on */
763
                                started = TRUE;
764
                                sofia_log[0] = '\0';
765
                                call_id[0] = '\0';
766
                        } else {
767
                                /* Message ended, handle it */
768
                                skip = FALSE;
769
                                append = FALSE;
770
                                /* Look for the session this message belongs to */
771
                                janus_sip_session *session = NULL;
772
                                if(strlen(call_id))
773
                                        session = g_hash_table_lookup(callids, call_id);
774
                                if(!session) {
775
                                        /* Couldn't find any SIP session with that Call-ID, check the request */
776
                                        if(strstr(sofia_log, "REGISTER") == sofia_log || strstr(sofia_log, "SIP/2.0 ") == sofia_log) {
777
                                                /* FIXME This is a REGISTER or a response code:
778
                                                 * check the To header and get the identity from there */
779
                                                char *from = strstr(sofia_log, "To: ");
780
                                                if(from) {
781
                                                        from = from+4;
782
                                                        char *start = strstr(from, "<");
783
                                                        if(start) {
784
                                                                start++;
785
                                                                char *end = strstr(from, ">");
786
                                                                if(end) {
787
                                                                        *end = '\0';
788
                                                                        g_snprintf(call_id, sizeof(call_id), "%s", start);
789
                                                                        *end = '>';
790
                                                                        session = g_hash_table_lookup(identities, call_id);
791
                                                                }
792
                                                        }
793
                                                }
794
                                        }
795
                                }
796
                                if(session) {
797
                                        /* Notify event handlers about the content of the whole outgoing SIP message */
798
                                        json_t *info = json_object();
799
                                        json_object_set_new(info, "event", json_string("sip-out"));
800
                                        json_object_set_new(info, "sip", json_string(sofia_log));
801 c734a91a Lorenzo Miniero
                                        gateway->notify_event(&janus_sip_plugin, session->handle, info);
802 fee76880 Lorenzo Miniero
                                } else {
803
                                        JANUS_LOG(LOG_WARN, "Couldn't find a session associated to this message, dropping it...\n%s", sofia_log);
804
                                }
805
                                /* Done, reset the buffers */
806
                                sofia_log[0] = '\0';
807
                                call_id[0] = '\0';
808
                        }
809
                        return;
810
                }
811
                if(strlen(line) == 1) {
812
                        /* Append a carriage and return */
813
                        g_strlcat(sofia_log, "\r\n", sizeof(sofia_log));
814
                } else {
815
                        /* If this is an OPTIONS, we don't care: drop it */
816
                        char *header = &line[3];
817
                        if(strstr(header, "OPTIONS") == header) {
818
                                skip = TRUE;
819
                                return;
820
                        }
821
                        /* Is this a Call-ID header? Keep note of it */
822
                        if(strstr(header, "Call-ID") == header) {
823
                                g_snprintf(call_id, sizeof(call_id), "%s", header+9);
824
                        }
825
                        /* Append the line to our buffer, skipping the indent */
826
                        g_strlcat(sofia_log, &line[3], sizeof(sofia_log));
827
                }
828
                return;
829
        }
830
        /* Still waiting to decide if this is a message we need */
831
        if(line[0] == 's' && line[1] == 'e' && line[2] == 'n' && line[3] == 'd' && line[4] == ' ') {
832
                /* An outgoing message is going to be logged, prepare for that */
833
                skip = FALSE;
834
                started = FALSE;
835
                append = TRUE;
836
                int length = atoi(&line[5]);
837
                JANUS_LOG(LOG_HUGE, "Intercepting message (%d bytes)\n", length);
838
                if(strstr(line, "-----"))
839
                        started = TRUE;
840
        }
841
}
842
843
844 be35facb meetecho
/* Plugin implementation */
845
int janus_sip_init(janus_callbacks *callback, const char *config_path) {
846 dbf63b61 meetecho
        if(g_atomic_int_get(&stopping)) {
847 be35facb meetecho
                /* Still stopping from before */
848
                return -1;
849
        }
850
        if(callback == NULL || config_path == NULL) {
851
                /* Invalid arguments */
852
                return -1;
853
        }
854
855
        /* Read configuration */
856
        char filename[255];
857 c94052c2 meetecho
        g_snprintf(filename, 255, "%s/%s.cfg", config_path, JANUS_SIP_PACKAGE);
858 3a26e009 meetecho
        JANUS_LOG(LOG_VERB, "Configuration file: %s\n", filename);
859 be35facb meetecho
        janus_config *config = janus_config_parse(filename);
860 71a04f89 Lorenzo Miniero
        if(config != NULL) {
861 be35facb meetecho
                janus_config_print(config);
862 c97cb850 Saúl Ibarra Corretgé
863 71a04f89 Lorenzo Miniero
                gboolean local_ip_set = FALSE;
864
                janus_config_item *item = janus_config_get_item_drilldown(config, "general", "local_ip");
865
                if(item && item->value) {
866
                        int family;
867
                        if (!janus_is_ip_valid(item->value, &family)) {
868
                                JANUS_LOG(LOG_WARN, "Invalid local IP specified: %s, guessing the default...\n", item->value);
869 77d8e4c0 Saúl Ibarra Corretgé
                        } else {
870 71a04f89 Lorenzo Miniero
                                /* Verify that we can actually bind to that address */
871
                                int fd = socket(family, SOCK_DGRAM, 0);
872
                                if (fd == -1) {
873
                                        JANUS_LOG(LOG_WARN, "Error creating test socket, falling back to detecting IP address...\n");
874 dc48ff07 Saúl Ibarra Corretgé
                                } else {
875 71a04f89 Lorenzo Miniero
                                        int r;
876
                                        struct sockaddr_storage ss;
877
                                        socklen_t addrlen;
878
                                        memset(&ss, 0, sizeof(ss));
879
                                        if (family == AF_INET) {
880
                                                struct sockaddr_in *addr4 = (struct sockaddr_in*)&ss;
881
                                                addr4->sin_family = AF_INET;
882
                                                addr4->sin_port = 0;
883
                                                inet_pton(AF_INET, item->value, &(addr4->sin_addr.s_addr));
884
                                                addrlen = sizeof(struct sockaddr_in);
885
                                        } else {
886
                                                struct sockaddr_in6 *addr6 = (struct sockaddr_in6*)&ss;
887
                                                addr6->sin6_family = AF_INET6;
888
                                                addr6->sin6_port = 0;
889
                                                inet_pton(AF_INET6, item->value, &(addr6->sin6_addr.s6_addr));
890
                                                addrlen = sizeof(struct sockaddr_in6);
891
                                        }
892
                                        r = bind(fd, (const struct sockaddr*)&ss, addrlen);
893
                                        close(fd);
894
                                        if (r < 0) {
895
                                                JANUS_LOG(LOG_WARN, "Error setting local IP address to %s, falling back to detecting IP address...\n", item->value);
896
                                        } else {
897
                                                g_strlcpy(local_ip, item->value, sizeof(local_ip));
898
                                                local_ip_set = TRUE;
899
                                        }
900 dc48ff07 Saúl Ibarra Corretgé
                                }
901 77d8e4c0 Saúl Ibarra Corretgé
                        }
902 c97cb850 Saúl Ibarra Corretgé
                }
903 71a04f89 Lorenzo Miniero
                if (!local_ip_set)
904
                        janus_sip_detect_local_ip(local_ip, sizeof(local_ip));
905
                JANUS_LOG(LOG_VERB, "Local IP set to %s\n", local_ip);
906
907
                item = janus_config_get_item_drilldown(config, "general", "keepalive_interval");
908
                if(item && item->value)
909
                        keepalive_interval = atoi(item->value);
910
                JANUS_LOG(LOG_VERB, "SIP keep-alive interval set to %d seconds\n", keepalive_interval);
911
912
                item = janus_config_get_item_drilldown(config, "general", "register_ttl");
913
                if(item && item->value)
914
                        register_ttl = atoi(item->value);
915
                JANUS_LOG(LOG_VERB, "SIP registration TTL set to %d seconds\n", register_ttl);
916
917
                item = janus_config_get_item_drilldown(config, "general", "behind_nat");
918
                if(item && item->value)
919
                        behind_nat = janus_is_true(item->value);
920
921
                item = janus_config_get_item_drilldown(config, "general", "user_agent");
922
                if(item && item->value)
923
                        user_agent = g_strdup(item->value);
924
                else
925
                        user_agent = g_strdup("Janus WebRTC Gateway SIP Plugin "JANUS_SIP_VERSION_STRING);
926
                JANUS_LOG(LOG_VERB, "SIP User-Agent set to %s\n", user_agent);
927
928
                item = janus_config_get_item_drilldown(config, "general", "events");
929
                if(item != NULL && item->value != NULL)
930
                        notify_events = janus_is_true(item->value);
931
                if(!notify_events && callback->events_is_enabled()) {
932
                        JANUS_LOG(LOG_WARN, "Notification of events to handlers disabled for %s\n", JANUS_SIP_NAME);
933
                }
934
935
                janus_config_destroy(config);
936 a37dd8a2 meetecho
        }
937 be35facb meetecho
        config = NULL;
938
939 871c362e Lorenzo Miniero
#ifdef HAVE_SRTP_2
940
        /* Init randomizer (for randum numbers in SRTP) */
941
        RAND_poll();
942
#endif
943
944 be35facb meetecho
        /* Setup sofia */
945
        su_init();
946 fee76880 Lorenzo Miniero
        if(callback->events_is_enabled()) {
947
                /* Enable the transport logging, as we want to have access to the SIP messages */
948
                setenv("TPORT_LOG", "1", 1);
949
                su_log_redirect(NULL, janus_sip_sofia_logger, NULL);
950
        }
951 be35facb meetecho
952
        sessions = g_hash_table_new(NULL, NULL);
953 fee76880 Lorenzo Miniero
        callids = g_hash_table_new(g_str_hash, g_str_equal);
954
        identities = g_hash_table_new(g_str_hash, g_str_equal);
955 3a26e009 meetecho
        janus_mutex_init(&sessions_mutex);
956 4d13c20d meetecho
        messages = g_async_queue_new_full((GDestroyNotify) janus_sip_message_free);
957 be35facb meetecho
        /* This is the callback we'll need to invoke to contact the gateway */
958
        gateway = callback;
959
960 dbf63b61 meetecho
        g_atomic_int_set(&initialized, 1);
961
962
        GError *error = NULL;
963 5fa9a305 meetecho
        /* Start the sessions watchdog */
964 c7498fa9 Lorenzo Miniero
        watchdog = g_thread_try_new("sip watchdog", &janus_sip_watchdog, NULL, &error);
965 dbf63b61 meetecho
        if(error != NULL) {
966
                g_atomic_int_set(&initialized, 0);
967
                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the SIP watchdog thread...\n", error->code, error->message ? error->message : "??");
968 5fa9a305 meetecho
                return -1;
969
        }
970 be35facb meetecho
        /* Launch the thread that will handle incoming messages */
971 c7498fa9 Lorenzo Miniero
        handler_thread = g_thread_try_new("sip handler", janus_sip_handler, NULL, &error);
972 be35facb meetecho
        if(error != NULL) {
973 dbf63b61 meetecho
                g_atomic_int_set(&initialized, 0);
974
                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the SIP handler thread...\n", error->code, error->message ? error->message : "??");
975 be35facb meetecho
                return -1;
976
        }
977 3a26e009 meetecho
        JANUS_LOG(LOG_INFO, "%s initialized!\n", JANUS_SIP_NAME);
978 be35facb meetecho
        return 0;
979
}
980
981 77992057 Philip Withnall
void janus_sip_destroy(void) {
982 dbf63b61 meetecho
        if(!g_atomic_int_get(&initialized))
983 be35facb meetecho
                return;
984 dbf63b61 meetecho
        g_atomic_int_set(&stopping, 1);
985 2e28ee7b Lorenzo Miniero
986 b9e8b01f Lorenzo Miniero
        g_async_queue_push(messages, &exit_message);
987 be35facb meetecho
        if(handler_thread != NULL) {
988
                g_thread_join(handler_thread);
989 dbf63b61 meetecho
                handler_thread = NULL;
990
        }
991
        if(watchdog != NULL) {
992
                g_thread_join(watchdog);
993
                watchdog = NULL;
994 be35facb meetecho
        }
995 3a26e009 meetecho
        /* FIXME We should destroy the sessions cleanly */
996 dbf63b61 meetecho
        janus_mutex_lock(&sessions_mutex);
997 be35facb meetecho
        g_hash_table_destroy(sessions);
998 fee76880 Lorenzo Miniero
        g_hash_table_destroy(callids);
999
        g_hash_table_destroy(identities);
1000
        sessions = NULL;
1001
        callids = NULL;
1002
        identities = NULL;
1003 dbf63b61 meetecho
        janus_mutex_unlock(&sessions_mutex);
1004 4d13c20d meetecho
        g_async_queue_unref(messages);
1005
        messages = NULL;
1006 dbf63b61 meetecho
        g_atomic_int_set(&initialized, 0);
1007
        g_atomic_int_set(&stopping, 0);
1008 0351dafc Lorenzo Miniero
1009
        /* Deinitialize sofia */
1010
        su_deinit();
1011
1012 3a26e009 meetecho
        JANUS_LOG(LOG_INFO, "%s destroyed!\n", JANUS_SIP_NAME);
1013 be35facb meetecho
}
1014
1015 667b2005 meetecho
int janus_sip_get_api_compatibility(void) {
1016
        /* Important! This is what your plugin MUST always return: don't lie here or bad things will happen */
1017
        return JANUS_PLUGIN_API_VERSION;
1018
}
1019
1020 77992057 Philip Withnall
int janus_sip_get_version(void) {
1021 be35facb meetecho
        return JANUS_SIP_VERSION;
1022
}
1023
1024 77992057 Philip Withnall
const char *janus_sip_get_version_string(void) {
1025 be35facb meetecho
        return JANUS_SIP_VERSION_STRING;
1026
}
1027
1028 77992057 Philip Withnall
const char *janus_sip_get_description(void) {
1029 be35facb meetecho
        return JANUS_SIP_DESCRIPTION;
1030
}
1031
1032 77992057 Philip Withnall
const char *janus_sip_get_name(void) {
1033 be35facb meetecho
        return JANUS_SIP_NAME;
1034
}
1035
1036 77992057 Philip Withnall
const char *janus_sip_get_author(void) {
1037 a3d13e20 meetecho
        return JANUS_SIP_AUTHOR;
1038
}
1039
1040 77992057 Philip Withnall
const char *janus_sip_get_package(void) {
1041 be35facb meetecho
        return JANUS_SIP_PACKAGE;
1042
}
1043
1044 cfd5c0d6 meetecho
void janus_sip_create_session(janus_plugin_session *handle, int *error) {
1045 8878e296 meetecho
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
1046 be35facb meetecho
                *error = -1;
1047
                return;
1048 eeabd833 Saúl Ibarra Corretgé
        }
1049 17078397 Saúl Ibarra Corretgé
        janus_sip_session *session = g_malloc0(sizeof(janus_sip_session));
1050 be35facb meetecho
        session->handle = handle;
1051 a37dd8a2 meetecho
        session->account.identity = NULL;
1052 43a3a2dc Lorenzo Miniero
        session->account.sips = TRUE;
1053 be35facb meetecho
        session->account.username = NULL;
1054 147173bd Saúl Ibarra Corretgé
        session->account.display_name = NULL;
1055 372e28b5 Saúl Ibarra Corretgé
        session->account.user_agent = NULL;
1056 86ba5bd2 tuijldert
        session->account.authuser = NULL;
1057 be35facb meetecho
        session->account.secret = NULL;
1058 6da4d93c Saúl Ibarra Corretgé
        session->account.secret_type = janus_sip_secret_type_unknown;
1059 be35facb meetecho
        session->account.sip_port = 0;
1060 a37dd8a2 meetecho
        session->account.proxy = NULL;
1061 ad872005 Saúl Ibarra Corretgé
        session->account.registration_status = janus_sip_registration_status_unregistered;
1062
        session->status = janus_sip_call_status_idle;
1063 1d287e40 Lorenzo Miniero
        session->stack = NULL;
1064 91b1c78a meetecho
        session->transaction = NULL;
1065 be35facb meetecho
        session->callee = NULL;
1066 4d8c7356 Lorenzo Miniero
        session->callid = NULL;
1067 4d8ee7e6 Lorenzo Miniero
        session->sdp = NULL;
1068 a37dd8a2 meetecho
        session->media.remote_ip = NULL;
1069 be35facb meetecho
        session->media.ready = 0;
1070 1a4bc02f Lorenzo Miniero
        session->media.autoack = TRUE;
1071 ac36fd1d Lorenzo Miniero
        session->media.require_srtp = FALSE;
1072 91bc289d Lorenzo Miniero
        session->media.has_srtp_local = FALSE;
1073
        session->media.has_srtp_remote = FALSE;
1074 be35facb meetecho
        session->media.has_audio = 0;
1075 dff30cfe Lorenzo Miniero
        session->media.audio_rtp_fd = -1;
1076
        session->media.audio_rtcp_fd= -1;
1077 be35facb meetecho
        session->media.local_audio_rtp_port = 0;
1078
        session->media.remote_audio_rtp_port = 0;
1079
        session->media.local_audio_rtcp_port = 0;
1080
        session->media.remote_audio_rtcp_port = 0;
1081 f6a402e8 meetecho
        session->media.audio_ssrc = 0;
1082
        session->media.audio_ssrc_peer = 0;
1083 02eeeba4 Lorenzo Miniero
        session->media.audio_pt = -1;
1084
        session->media.audio_pt_name = NULL;
1085 91bc289d Lorenzo Miniero
        session->media.audio_srtp_suite_in = 0;
1086
        session->media.audio_srtp_suite_out = 0;
1087 4d8ee7e6 Lorenzo Miniero
        session->media.audio_send = TRUE;
1088 be35facb meetecho
        session->media.has_video = 0;
1089 dff30cfe Lorenzo Miniero
        session->media.video_rtp_fd = -1;
1090
        session->media.video_rtcp_fd= -1;
1091 be35facb meetecho
        session->media.local_video_rtp_port = 0;
1092
        session->media.remote_video_rtp_port = 0;
1093
        session->media.local_video_rtcp_port = 0;
1094
        session->media.remote_video_rtcp_port = 0;
1095 f6a402e8 meetecho
        session->media.video_ssrc = 0;
1096
        session->media.video_ssrc_peer = 0;
1097 02eeeba4 Lorenzo Miniero
        session->media.video_pt = -1;
1098
        session->media.video_pt_name = NULL;
1099 91bc289d Lorenzo Miniero
        session->media.video_srtp_suite_in = 0;
1100
        session->media.video_srtp_suite_out = 0;
1101 4d8ee7e6 Lorenzo Miniero
        session->media.video_send = TRUE;
1102
        /* Initialize the RTP context */
1103
        session->media.context.a_last_ssrc = 0;
1104
        session->media.context.a_last_ssrc = 0;
1105
        session->media.context.a_last_ts = 0;
1106
        session->media.context.a_base_ts = 0;
1107
        session->media.context.a_base_ts_prev = 0;
1108
        session->media.context.v_last_ssrc = 0;
1109
        session->media.context.v_last_ts = 0;
1110
        session->media.context.v_base_ts = 0;
1111
        session->media.context.v_base_ts_prev = 0;
1112
        session->media.context.a_last_seq = 0;
1113
        session->media.context.a_base_seq = 0;
1114
        session->media.context.a_base_seq_prev = 0;
1115
        session->media.context.v_last_seq = 0;
1116
        session->media.context.v_base_seq = 0;
1117
        session->media.context.v_base_seq_prev = 0;
1118
        session->media.pipefd[0] = -1;
1119
        session->media.pipefd[1] = -1;
1120
        session->media.updated = FALSE;
1121 d223cef1 Lorenzo Miniero
        janus_mutex_init(&session->rec_mutex);
1122 5fa9a305 meetecho
        session->destroyed = 0;
1123 f65c61ff Lorenzo Miniero
        g_atomic_int_set(&session->hangingup, 0);
1124 a37dd8a2 meetecho
        janus_mutex_init(&session->mutex);
1125 be35facb meetecho
        handle->plugin_handle = session;
1126
1127 3a26e009 meetecho
        janus_mutex_lock(&sessions_mutex);
1128
        g_hash_table_insert(sessions, handle, session);
1129
        janus_mutex_unlock(&sessions_mutex);
1130
1131 be35facb meetecho
        return;
1132
}
1133
1134 cfd5c0d6 meetecho
void janus_sip_destroy_session(janus_plugin_session *handle, int *error) {
1135 8878e296 meetecho
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
1136 be35facb meetecho
                *error = -1;
1137
                return;
1138 eeabd833 Saúl Ibarra Corretgé
        }
1139 6089eb4e Lorenzo Miniero
        janus_sip_session *session = (janus_sip_session *)handle->plugin_handle;
1140 be35facb meetecho
        if(!session) {
1141 ce97b4a5 meetecho
                JANUS_LOG(LOG_ERR, "No SIP session associated with this handle...\n");
1142 be35facb meetecho
                *error = -2;
1143
                return;
1144
        }
1145 3a26e009 meetecho
        janus_mutex_lock(&sessions_mutex);
1146 793d18b1 meetecho
        if(!session->destroyed) {
1147
                g_hash_table_remove(sessions, handle);
1148
                janus_sip_hangup_media(handle);
1149 78955474 meetecho
                session->destroyed = janus_get_monotonic_time();
1150 793d18b1 meetecho
                JANUS_LOG(LOG_VERB, "Destroying SIP session (%s)...\n", session->account.username ? session->account.username : "unregistered user");
1151 1d287e40 Lorenzo Miniero
                if(session->stack != NULL) {
1152
                        /* Shutdown the NUA: this will remove the session later on */
1153
                        nua_shutdown(session->stack->s_nua);
1154
                } else {
1155
                        /* No stack, maybe never registered: cleaning up and removing the session is done in a lazy way */
1156
                        old_sessions = g_list_append(old_sessions, session);
1157
                }
1158 793d18b1 meetecho
        }
1159 5fa9a305 meetecho
        janus_mutex_unlock(&sessions_mutex);
1160 be35facb meetecho
        return;
1161
}
1162
1163 dd11fa0a Lorenzo Miniero
json_t *janus_sip_query_session(janus_plugin_session *handle) {
1164 667b2005 meetecho
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
1165
                return NULL;
1166 ad872005 Saúl Ibarra Corretgé
        }
1167 667b2005 meetecho
        janus_sip_session *session = (janus_sip_session *)handle->plugin_handle;
1168
        if(!session) {
1169
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1170
                return NULL;
1171
        }
1172
        /* Provide some generic info, e.g., if we're in a call and with whom */
1173
        json_t *info = json_object();
1174
        json_object_set_new(info, "username", session->account.username ? json_string(session->account.username) : NULL);
1175 147173bd Saúl Ibarra Corretgé
        json_object_set_new(info, "display_name", session->account.display_name ? json_string(session->account.display_name) : NULL);
1176 372e28b5 Saúl Ibarra Corretgé
        json_object_set_new(info, "user_agent", session->account.user_agent ? json_string(session->account.user_agent) : NULL);
1177 667b2005 meetecho
        json_object_set_new(info, "identity", session->account.identity ? json_string(session->account.identity) : NULL);
1178 ad872005 Saúl Ibarra Corretgé
        json_object_set_new(info, "registration_status", json_string(janus_sip_registration_status_string(session->account.registration_status)));
1179
        json_object_set_new(info, "call_status", json_string(janus_sip_call_status_string(session->status)));
1180 91bc289d Lorenzo Miniero
        if(session->callee) {
1181 667b2005 meetecho
                json_object_set_new(info, "callee", json_string(session->callee ? session->callee : "??"));
1182 1a4bc02f Lorenzo Miniero
                json_object_set_new(info, "auto-ack", json_string(session->media.autoack ? "yes" : "no"));
1183 ac36fd1d Lorenzo Miniero
                json_object_set_new(info, "srtp-required", json_string(session->media.require_srtp ? "yes" : "no"));
1184 91bc289d Lorenzo Miniero
                json_object_set_new(info, "sdes-local", json_string(session->media.has_srtp_local ? "yes" : "no"));
1185
                json_object_set_new(info, "sdes-remote", json_string(session->media.has_srtp_remote ? "yes" : "no"));
1186
        }
1187 6089eb4e Lorenzo Miniero
        if(session->arc || session->vrc || session->arc_peer || session->vrc_peer) {
1188
                json_t *recording = json_object();
1189
                if(session->arc && session->arc->filename)
1190
                        json_object_set_new(recording, "audio", json_string(session->arc->filename));
1191
                if(session->vrc && session->vrc->filename)
1192
                        json_object_set_new(recording, "video", json_string(session->vrc->filename));
1193
                if(session->arc_peer && session->arc_peer->filename)
1194
                        json_object_set_new(recording, "audio-peer", json_string(session->arc_peer->filename));
1195
                if(session->vrc_peer && session->vrc_peer->filename)
1196
                        json_object_set_new(recording, "video-peer", json_string(session->vrc_peer->filename));
1197
                json_object_set_new(info, "recording", recording);
1198
        }
1199 667b2005 meetecho
        json_object_set_new(info, "destroyed", json_integer(session->destroyed));
1200 dd11fa0a Lorenzo Miniero
        return info;
1201 667b2005 meetecho
}
1202
1203 dd11fa0a Lorenzo Miniero
struct janus_plugin_result *janus_sip_handle_message(janus_plugin_session *handle, char *transaction, json_t *message, json_t *jsep) {
1204 8878e296 meetecho
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
1205 dd11fa0a Lorenzo Miniero
                return janus_plugin_result_new(JANUS_PLUGIN_ERROR, g_atomic_int_get(&stopping) ? "Shutting down" : "Plugin not initialized", NULL);
1206 17078397 Saúl Ibarra Corretgé
        janus_sip_message *msg = g_malloc0(sizeof(janus_sip_message));
1207 be35facb meetecho
        msg->handle = handle;
1208 3a26e009 meetecho
        msg->transaction = transaction;
1209 be35facb meetecho
        msg->message = message;
1210 dd11fa0a Lorenzo Miniero
        msg->jsep = jsep;
1211 4d13c20d meetecho
        g_async_queue_push(messages, msg);
1212 292d035f meetecho
1213
        /* All the requests to this plugin are handled asynchronously */
1214 dd11fa0a Lorenzo Miniero
        return janus_plugin_result_new(JANUS_PLUGIN_OK_WAIT, NULL, NULL);
1215 be35facb meetecho
}
1216
1217 cfd5c0d6 meetecho
void janus_sip_setup_media(janus_plugin_session *handle) {
1218 3a26e009 meetecho
        JANUS_LOG(LOG_INFO, "WebRTC media is now available\n");
1219 8878e296 meetecho
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
1220 be35facb meetecho
                return;
1221 eeabd833 Saúl Ibarra Corretgé
        janus_sip_session *session = (janus_sip_session *)handle->plugin_handle;
1222 be35facb meetecho
        if(!session) {
1223 3a26e009 meetecho
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1224 be35facb meetecho
                return;
1225
        }
1226 5fa9a305 meetecho
        if(session->destroyed)
1227 be35facb meetecho
                return;
1228 3a3cc054 meetecho
        g_atomic_int_set(&session->hangingup, 0);
1229 be35facb meetecho
        /* TODO Only relay RTP/RTCP when we get this event */
1230
}
1231
1232 cfd5c0d6 meetecho
void janus_sip_incoming_rtp(janus_plugin_session *handle, int video, char *buf, int len) {
1233 8878e296 meetecho
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
1234 be35facb meetecho
                return;
1235
        if(gateway) {
1236
                /* Honour the audio/video active flags */
1237 eeabd833 Saúl Ibarra Corretgé
                janus_sip_session *session = (janus_sip_session *)handle->plugin_handle;
1238 5fa9a305 meetecho
                if(!session || session->destroyed) {
1239 3a26e009 meetecho
                        JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1240 be35facb meetecho
                        return;
1241
                }
1242 ad872005 Saúl Ibarra Corretgé
                if(session->status != janus_sip_call_status_incall)
1243 a37dd8a2 meetecho
                        return;
1244 be35facb meetecho
                /* Forward to our SIP peer */
1245
                if(video) {
1246 4d8ee7e6 Lorenzo Miniero
                        if(!session->media.video_send) {
1247
                                /* Dropping video packet, peer doesn't want to receive it */
1248
                                return;
1249
                        }
1250 f6a402e8 meetecho
                        if(session->media.video_ssrc == 0) {
1251
                                rtp_header *header = (rtp_header *)buf;
1252
                                session->media.video_ssrc = ntohl(header->ssrc);
1253
                                JANUS_LOG(LOG_VERB, "Got SIP video SSRC: %"SCNu32"\n", session->media.video_ssrc);
1254
                        }
1255 be35facb meetecho
                        if(session->media.has_video && session->media.video_rtp_fd) {
1256 6089eb4e Lorenzo Miniero
                                /* Save the frame if we're recording */
1257 55cc1c59 Andreas Girgensohn
                                janus_recorder_save_frame(session->vrc, buf, len);
1258 91bc289d Lorenzo Miniero
                                /* Is SRTP involved? */
1259
                                if(session->media.has_srtp_local) {
1260
                                        char sbuf[2048];
1261
                                        memcpy(&sbuf, buf, len);
1262
                                        int protected = len;
1263
                                        int res = srtp_protect(session->media.video_srtp_out, &sbuf, &protected);
1264 871c362e Lorenzo Miniero
                                        if(res != srtp_err_status_ok) {
1265 91bc289d Lorenzo Miniero
                                                rtp_header *header = (rtp_header *)&sbuf;
1266
                                                guint32 timestamp = ntohl(header->timestamp);
1267
                                                guint16 seq = ntohs(header->seq_number);
1268
                                                JANUS_LOG(LOG_ERR, "[SIP-%s] Video SRTP protect error... %s (len=%d-->%d, ts=%"SCNu32", seq=%"SCNu16")...\n",
1269
                                                        session->account.username, janus_sip_get_srtp_error(res), len, protected, timestamp, seq);
1270
                                        } else {
1271
                                                /* Forward the frame to the peer */
1272
                                                send(session->media.video_rtp_fd, sbuf, protected, 0);
1273
                                        }
1274
                                } else {
1275
                                        /* Forward the frame to the peer */
1276
                                        send(session->media.video_rtp_fd, buf, len, 0);
1277
                                }
1278 be35facb meetecho
                        }
1279
                } else {
1280 4d8ee7e6 Lorenzo Miniero
                        if(!session->media.audio_send) {
1281
                                /* Dropping audio packet, peer doesn't want to receive it */
1282
                                return;
1283
                        }
1284 f6a402e8 meetecho
                        if(session->media.audio_ssrc == 0) {
1285
                                rtp_header *header = (rtp_header *)buf;
1286
                                session->media.audio_ssrc = ntohl(header->ssrc);
1287
                                JANUS_LOG(LOG_VERB, "Got SIP audio SSRC: %"SCNu32"\n", session->media.audio_ssrc);
1288
                        }
1289 be35facb meetecho
                        if(session->media.has_audio && session->media.audio_rtp_fd) {
1290 6089eb4e Lorenzo Miniero
                                /* Save the frame if we're recording */
1291 55cc1c59 Andreas Girgensohn
                                janus_recorder_save_frame(session->arc, buf, len);
1292 91bc289d Lorenzo Miniero
                                /* Is SRTP involved? */
1293
                                if(session->media.has_srtp_local) {
1294
                                        char sbuf[2048];
1295
                                        memcpy(&sbuf, buf, len);
1296
                                        int protected = len;
1297
                                        int res = srtp_protect(session->media.audio_srtp_out, &sbuf, &protected);
1298 871c362e Lorenzo Miniero
                                        if(res != srtp_err_status_ok) {
1299 91bc289d Lorenzo Miniero
                                                rtp_header *header = (rtp_header *)&sbuf;
1300
                                                guint32 timestamp = ntohl(header->timestamp);
1301
                                                guint16 seq = ntohs(header->seq_number);
1302
                                                JANUS_LOG(LOG_ERR, "[SIP-%s] Audio SRTP protect error... %s (len=%d-->%d, ts=%"SCNu32", seq=%"SCNu16")...\n",
1303
                                                        session->account.username, janus_sip_get_srtp_error(res), len, protected, timestamp, seq);
1304
                                        } else {
1305
                                                /* Forward the frame to the peer */
1306
                                                send(session->media.audio_rtp_fd, sbuf, protected, 0);
1307
                                        }
1308
                                } else {
1309
                                        /* Forward the frame to the peer */
1310
                                        send(session->media.audio_rtp_fd, buf, len, 0);
1311
                                }
1312 be35facb meetecho
                        }
1313
                }
1314
        }
1315
}
1316
1317 cfd5c0d6 meetecho
void janus_sip_incoming_rtcp(janus_plugin_session *handle, int video, char *buf, int len) {
1318 8878e296 meetecho
        if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
1319 be35facb meetecho
                return;
1320
        if(gateway) {
1321 eeabd833 Saúl Ibarra Corretgé
                janus_sip_session *session = (janus_sip_session *)handle->plugin_handle;
1322 5fa9a305 meetecho
                if(!session || session->destroyed) {
1323 3a26e009 meetecho
                        JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1324 be35facb meetecho
                        return;
1325
                }
1326 ad872005 Saúl Ibarra Corretgé
                if(session->status != janus_sip_call_status_incall)
1327 a37dd8a2 meetecho
                        return;
1328 be35facb meetecho
                /* Forward to our SIP peer */
1329
                if(video) {
1330
                        if(session->media.has_video && session->media.video_rtcp_fd) {
1331 bcfe81e9 Lorenzo Miniero
                                /* Fix SSRCs as the gateway does */
1332
                                JANUS_LOG(LOG_HUGE, "[SIP] Fixing SSRCs (local %u, peer %u)\n",
1333
                                        session->media.video_ssrc, session->media.video_ssrc_peer);
1334
                                janus_rtcp_fix_ssrc(NULL, (char *)buf, len, 1, session->media.video_ssrc, session->media.video_ssrc_peer);
1335 91bc289d Lorenzo Miniero
                                /* Is SRTP involved? */
1336
                                if(session->media.has_srtp_local) {
1337
                                        char sbuf[2048];
1338
                                        memcpy(&sbuf, buf, len);
1339
                                        int protected = len;
1340
                                        int res = srtp_protect_rtcp(session->media.video_srtp_out, &sbuf, &protected);
1341 871c362e Lorenzo Miniero
                                        if(res != srtp_err_status_ok) {
1342 91bc289d Lorenzo Miniero
                                                JANUS_LOG(LOG_ERR, "[SIP-%s] Video SRTCP protect error... %s (len=%d-->%d)...\n",
1343
                                                        session->account.username, janus_sip_get_srtp_error(res), len, protected);
1344
                                        } else {
1345
                                                /* Forward the message to the peer */
1346
                                                send(session->media.video_rtcp_fd, sbuf, protected, 0);
1347
                                        }
1348
                                } else {
1349
                                        /* Forward the message to the peer */
1350
                                        send(session->media.video_rtcp_fd, buf, len, 0);
1351
                                }
1352 be35facb meetecho
                        }
1353
                } else {
1354
                        if(session->media.has_audio && session->media.audio_rtcp_fd) {
1355 bcfe81e9 Lorenzo Miniero
                                /* Fix SSRCs as the gateway does */
1356
                                JANUS_LOG(LOG_HUGE, "[SIP] Fixing SSRCs (local %u, peer %u)\n",
1357
                                        session->media.audio_ssrc, session->media.audio_ssrc_peer);
1358
                                janus_rtcp_fix_ssrc(NULL, (char *)buf, len, 1, session->media.audio_ssrc, session->media.audio_ssrc_peer);
1359 91bc289d Lorenzo Miniero
                                /* Is SRTP involved? */
1360
                                if(session->media.has_srtp_local) {
1361
                                        char sbuf[2048];
1362
                                        memcpy(&sbuf, buf, len);
1363
                                        int protected = len;
1364
                                        int res = srtp_protect_rtcp(session->media.audio_srtp_out, &sbuf, &protected);
1365 871c362e Lorenzo Miniero
                                        if(res != srtp_err_status_ok) {
1366 91bc289d Lorenzo Miniero
                                                JANUS_LOG(LOG_ERR, "[SIP-%s] Audio SRTCP protect error... %s (len=%d-->%d)...\n",
1367
                                                        session->account.username, janus_sip_get_srtp_error(res), len, protected);
1368
                                        } else {
1369
                                                /* Forward the message to the peer */
1370
                                                send(session->media.audio_rtcp_fd, sbuf, protected, 0);
1371
                                        }
1372
                                } else {
1373
                                        /* Forward the message to the peer */
1374
                                        send(session->media.audio_rtcp_fd, buf, len, 0);
1375
                                }
1376 be35facb meetecho
                        }
1377
                }
1378
        }
1379
}
1380
1381 cfd5c0d6 meetecho
void janus_sip_hangup_media(janus_plugin_session *handle) {
1382 3a26e009 meetecho
        JANUS_LOG(LOG_INFO, "No WebRTC media anymore\n");
1383 8878e296 meetecho
        if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
1384 be35facb meetecho
                return;
1385 eeabd833 Saúl Ibarra Corretgé
        janus_sip_session *session = (janus_sip_session *)handle->plugin_handle;
1386 be35facb meetecho
        if(!session) {
1387 3a26e009 meetecho
                JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1388 be35facb meetecho
                return;
1389
        }
1390 3a3cc054 meetecho
        if(session->destroyed)
1391
                return;
1392
        if(g_atomic_int_add(&session->hangingup, 1))
1393 be35facb meetecho
                return;
1394 ad872005 Saúl Ibarra Corretgé
        if(!(session->status == janus_sip_call_status_inviting ||
1395
                 session->status == janus_sip_call_status_invited ||
1396
                 session->status == janus_sip_call_status_incall))
1397 be196340 meetecho
                return;
1398 6089eb4e Lorenzo Miniero
        /* Get rid of the recorders, if available */
1399 d223cef1 Lorenzo Miniero
        janus_mutex_lock(&session->rec_mutex);
1400 6089eb4e Lorenzo Miniero
        if(session->arc) {
1401
                janus_recorder_close(session->arc);
1402
                JANUS_LOG(LOG_INFO, "Closed user's audio recording %s\n", session->arc->filename ? session->arc->filename : "??");
1403
                janus_recorder_free(session->arc);
1404
        }
1405
        session->arc = NULL;
1406
        if(session->arc_peer) {
1407
                janus_recorder_close(session->arc_peer);
1408
                JANUS_LOG(LOG_INFO, "Closed peer's audio recording %s\n", session->arc_peer->filename ? session->arc_peer->filename : "??");
1409
                janus_recorder_free(session->arc_peer);
1410
        }
1411
        session->arc_peer = NULL;
1412
        if(session->vrc) {
1413
                janus_recorder_close(session->vrc);
1414
                JANUS_LOG(LOG_INFO, "Closed user's video recording %s\n", session->vrc->filename ? session->vrc->filename : "??");
1415
                janus_recorder_free(session->vrc);
1416
        }
1417
        session->vrc = NULL;
1418
        if(session->vrc_peer) {
1419
                janus_recorder_close(session->vrc_peer);
1420
                JANUS_LOG(LOG_INFO, "Closed peer's video recording %s\n", session->vrc_peer->filename ? session->vrc_peer->filename : "??");
1421
                janus_recorder_free(session->vrc_peer);
1422
        }
1423
        session->vrc_peer = NULL;
1424 d223cef1 Lorenzo Miniero
        janus_mutex_unlock(&session->rec_mutex);
1425 be35facb meetecho
        /* FIXME Simulate a "hangup" coming from the browser */
1426 17078397 Saúl Ibarra Corretgé
        janus_sip_message *msg = g_malloc0(sizeof(janus_sip_message));
1427 be35facb meetecho
        msg->handle = handle;
1428 dd11fa0a Lorenzo Miniero
        msg->message = json_pack("{ss}", "request", "hangup");
1429 be35facb meetecho
        msg->transaction = NULL;
1430 dd11fa0a Lorenzo Miniero
        msg->jsep = NULL;
1431 4d13c20d meetecho
        g_async_queue_push(messages, msg);
1432 be35facb meetecho
}
1433
1434
/* Thread to handle incoming messages */
1435
static void *janus_sip_handler(void *data) {
1436 febef1ea meetecho
        JANUS_LOG(LOG_VERB, "Joining SIP handler thread\n");
1437 be35facb meetecho
        janus_sip_message *msg = NULL;
1438 3cc3cab3 meetecho
        int error_code = 0;
1439 94926fcd Andreas Girgensohn
        char error_cause[512];
1440 ead45815 meetecho
        json_t *root = NULL;
1441 dbf63b61 meetecho
        while(g_atomic_int_get(&initialized) && !g_atomic_int_get(&stopping)) {
1442 2e28ee7b Lorenzo Miniero
                msg = g_async_queue_pop(messages);
1443
                if(msg == NULL)
1444
                        continue;
1445 b9e8b01f Lorenzo Miniero
                if(msg == &exit_message)
1446
                        break;
1447 2e28ee7b Lorenzo Miniero
                if(msg->handle == NULL) {
1448
                        janus_sip_message_free(msg);
1449 be35facb meetecho
                        continue;
1450
                }
1451 638695a1 Lorenzo Miniero
                janus_sip_session *session = NULL;
1452
                janus_mutex_lock(&sessions_mutex);
1453
                if(g_hash_table_lookup(sessions, msg->handle) != NULL ) {
1454
                        session = (janus_sip_session *)msg->handle->plugin_handle;
1455
                }
1456
                janus_mutex_unlock(&sessions_mutex);
1457 be35facb meetecho
                if(!session) {
1458 3a26e009 meetecho
                        JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
1459
                        janus_sip_message_free(msg);
1460 be35facb meetecho
                        continue;
1461
                }
1462 5fa9a305 meetecho
                if(session->destroyed) {
1463 3a26e009 meetecho
                        janus_sip_message_free(msg);
1464 be35facb meetecho
                        continue;
1465 3a26e009 meetecho
                }
1466 be35facb meetecho
                /* Handle request */
1467 3cc3cab3 meetecho
                error_code = 0;
1468 dd11fa0a Lorenzo Miniero
                root = msg->message;
1469 be35facb meetecho
                if(msg->message == NULL) {
1470 3a26e009 meetecho
                        JANUS_LOG(LOG_ERR, "No message??\n");
1471 3cc3cab3 meetecho
                        error_code = JANUS_SIP_ERROR_NO_MESSAGE;
1472 c94052c2 meetecho
                        g_snprintf(error_cause, 512, "%s", "No message??");
1473 be35facb meetecho
                        goto error;
1474
                }
1475
                if(!json_is_object(root)) {
1476 3a26e009 meetecho
                        JANUS_LOG(LOG_ERR, "JSON error: not an object\n");
1477 3cc3cab3 meetecho
                        error_code = JANUS_SIP_ERROR_INVALID_JSON;
1478 c94052c2 meetecho
                        g_snprintf(error_cause, 512, "JSON error: not an object");
1479 be35facb meetecho
                        goto error;
1480
                }
1481 94926fcd Andreas Girgensohn
                JANUS_VALIDATE_JSON_OBJECT(root, request_parameters,
1482
                        error_code, error_cause, TRUE,
1483
                        JANUS_SIP_ERROR_MISSING_ELEMENT, JANUS_SIP_ERROR_INVALID_ELEMENT);
1484
                if(error_code != 0)
1485 be35facb meetecho
                        goto error;
1486 94926fcd Andreas Girgensohn
                json_t *request = json_object_get(root, "request");
1487 be35facb meetecho
                const char *request_text = json_string_value(request);
1488
                json_t *result = NULL;
1489 a6079d3d richstorm
1490 be35facb meetecho
                if(!strcasecmp(request_text, "register")) {
1491
                        /* Send a REGISTER */
1492 ad872005 Saúl Ibarra Corretgé
                        if(session->account.registration_status > janus_sip_registration_status_unregistered) {
1493 3a26e009 meetecho
                                JANUS_LOG(LOG_ERR, "Already registered (%s)\n", session->account.username);
1494 3cc3cab3 meetecho
                                error_code = JANUS_SIP_ERROR_ALREADY_REGISTERED;
1495 c94052c2 meetecho
                                g_snprintf(error_cause, 512, "Already registered (%s)", session->account.username);
1496 be35facb meetecho
                                goto error;
1497
                        }
1498 5fafdeea Saúl Ibarra Corretgé
1499
                        /* Cleanup old values */
1500 fee76880 Lorenzo Miniero
                        if(session->account.identity != NULL) {
1501
                                g_hash_table_remove(identities, session->account.identity);
1502 5fafdeea Saúl Ibarra Corretgé
                                g_free(session->account.identity);
1503 fee76880 Lorenzo Miniero
                        }
1504 e362f8b4 Saúl Ibarra Corretgé
                        session->account.identity = NULL;
1505 43a3a2dc Lorenzo Miniero
                        session->account.sips = TRUE;
1506 5fafdeea Saúl Ibarra Corretgé
                        if(session->account.username != NULL)
1507
                                g_free(session->account.username);
1508 e362f8b4 Saúl Ibarra Corretgé
                        session->account.username = NULL;
1509 147173bd Saúl Ibarra Corretgé
                        if(session->account.display_name != NULL)
1510
                                g_free(session->account.display_name);
1511
                        session->account.display_name = NULL;
1512 86ba5bd2 tuijldert
                        if(session->account.authuser != NULL)
1513
                                g_free(session->account.authuser);
1514
                        session->account.authuser = NULL;
1515 5fafdeea Saúl Ibarra Corretgé
                        if(session->account.secret != NULL)
1516
                                g_free(session->account.secret);
1517 e362f8b4 Saúl Ibarra Corretgé
                        session->account.secret = NULL;
1518 6da4d93c Saúl Ibarra Corretgé
                        session->account.secret_type = janus_sip_secret_type_unknown;
1519 5fafdeea Saúl Ibarra Corretgé
                        if(session->account.proxy != NULL)
1520
                                g_free(session->account.proxy);
1521 e362f8b4 Saúl Ibarra Corretgé
                        session->account.proxy = NULL;
1522 372e28b5 Saúl Ibarra Corretgé
                        if(session->account.user_agent != NULL)
1523
                                g_free(session->account.user_agent);
1524
                        session->account.user_agent = NULL;
1525 ad872005 Saúl Ibarra Corretgé
                        session->account.registration_status = janus_sip_registration_status_unregistered;
1526 5fafdeea Saúl Ibarra Corretgé
1527 a37dd8a2 meetecho
                        gboolean guest = FALSE;
1528 94926fcd Andreas Girgensohn
                        JANUS_VALIDATE_JSON_OBJECT(root, register_parameters,
1529
                                error_code, error_cause, TRUE,
1530
                                JANUS_SIP_ERROR_MISSING_ELEMENT, JANUS_SIP_ERROR_INVALID_ELEMENT);
1531
                        if(error_code != 0)
1532
                                goto error;
1533 a37dd8a2 meetecho
                        json_t *type = json_object_get(root, "type");
1534
                        if(type != NULL) {
1535
                                const char *type_text = json_string_value(type);
1536
                                if(!strcmp(type_text, "guest")) {
1537
                                        JANUS_LOG(LOG_INFO, "Registering as a guest\n");
1538
                                        guest = TRUE;
1539
                                } else {
1540
                                        JANUS_LOG(LOG_WARN, "Unknown type '%s', ignoring...\n", type_text);
1541
                                }
1542 be35facb meetecho
                        }
1543 735be1e9 Saúl Ibarra Corretgé
1544
                        gboolean send_register = TRUE;
1545
                        json_t *do_register = json_object_get(root, "send_register");
1546
                        if(do_register != NULL) {
1547
                                if(guest) {
1548
                                        JANUS_LOG(LOG_ERR, "Conflicting elements: send_register cannot be true if guest is true\n");
1549
                                        error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
1550
                                        g_snprintf(error_cause, 512, "Conflicting elements: send_register cannot be true if guest is true");
1551
                                        goto error;
1552
                                }
1553
                                send_register = json_is_true(do_register);
1554
                        }
1555
1556 43a3a2dc Lorenzo Miniero
                        gboolean sips = TRUE;
1557
                        json_t *do_sips = json_object_get(root, "sips");
1558
                        if(do_sips != NULL) {
1559
                                sips = json_is_true(do_sips);
1560
                        }
1561
1562 a37dd8a2 meetecho
                        /* Parse address */
1563
                        json_t *proxy = json_object_get(root, "proxy");
1564 1d4a3e62 Saúl Ibarra Corretgé
                        const char *proxy_text = NULL;
1565
1566
                        if (proxy && !json_is_null(proxy)) {
1567 94926fcd Andreas Girgensohn
                                /* Has to be validated separately because it could be null */
1568
                                JANUS_VALIDATE_JSON_OBJECT(root, proxy_parameters,
1569
                                        error_code, error_cause, TRUE,
1570
                                        JANUS_SIP_ERROR_MISSING_ELEMENT, JANUS_SIP_ERROR_INVALID_ELEMENT);
1571
                                if(error_code != 0)
1572 1d4a3e62 Saúl Ibarra Corretgé
                                        goto error;
1573
                                proxy_text = json_string_value(proxy);
1574
                                janus_sip_uri_t proxy_uri;
1575
                                if (janus_sip_parse_proxy_uri(&proxy_uri, proxy_text) < 0) {
1576
                                        JANUS_LOG(LOG_ERR, "Invalid proxy address %s\n", proxy_text);
1577
                                        error_code = JANUS_SIP_ERROR_INVALID_ADDRESS;
1578
                                        g_snprintf(error_cause, 512, "Invalid proxy address %s\n", proxy_text);
1579
                                        goto error;
1580
                                }
1581 be35facb meetecho
                        }
1582 1d4a3e62 Saúl Ibarra Corretgé
1583 0270beb3 Saúl Ibarra Corretgé
                        /* Parse register TTL */
1584
                        int ttl = register_ttl;
1585
                        json_t *reg_ttl = json_object_get(root, "register_ttl");
1586
                        if (reg_ttl && json_is_integer(reg_ttl))
1587
                                ttl = json_integer_value(reg_ttl);
1588
                        if (ttl <= 0)
1589
                                ttl = JANUS_DEFAULT_REGISTER_TTL;
1590
1591 147173bd Saúl Ibarra Corretgé
                        /* Parse display name */
1592
                        const char* display_name_text = NULL;
1593
                        json_t *display_name = json_object_get(root, "display_name");
1594
                        if (display_name && json_is_string(display_name))
1595
                                display_name_text = json_string_value(display_name);
1596
1597 372e28b5 Saúl Ibarra Corretgé
                        /* Parse user agent */
1598
                        const char* user_agent_text = NULL;
1599
                        json_t *user_agent = json_object_get(root, "user_agent");
1600
                        if (user_agent && json_is_string(user_agent))
1601
                                user_agent_text = json_string_value(user_agent);
1602
1603 a37dd8a2 meetecho
                        /* Now the user part, if needed */
1604 3cc3cab3 meetecho
                        json_t *username = json_object_get(root, "username");
1605
                        if(!guest && !username) {
1606
                                /* The username is mandatory if we're not registering as guests */
1607
                                JANUS_LOG(LOG_ERR, "Missing element (username)\n");
1608
                                error_code = JANUS_SIP_ERROR_MISSING_ELEMENT;
1609 c94052c2 meetecho
                                g_snprintf(error_cause, 512, "Missing element (username)");
1610 3cc3cab3 meetecho
                                goto error;
1611
                        }
1612
                        const char *username_text = NULL;
1613 33f37af8 Saúl Ibarra Corretgé
                        janus_sip_uri_t username_uri;
1614 3cc3cab3 meetecho
                        char user_id[256];
1615
                        if(username) {
1616 a37dd8a2 meetecho
                                /* Parse address */
1617 8609111e Saúl Ibarra Corretgé
                                username_text = json_string_value(username);
1618 33f37af8 Saúl Ibarra Corretgé
                                if (janus_sip_parse_uri(&username_uri, username_text) < 0) {
1619 a37dd8a2 meetecho
                                        JANUS_LOG(LOG_ERR, "Invalid user address %s\n", username_text);
1620 3cc3cab3 meetecho
                                        error_code = JANUS_SIP_ERROR_INVALID_ADDRESS;
1621 c94052c2 meetecho
                                        g_snprintf(error_cause, 512, "Invalid user address %s\n", username_text);
1622 a37dd8a2 meetecho
                                        goto error;
1623
                                }
1624 33f37af8 Saúl Ibarra Corretgé
                                g_strlcpy(user_id, username_uri.url->url_user, sizeof(user_id));
1625 3cc3cab3 meetecho
                        }
1626
                        if(guest) {
1627
                                /* Not needed, we can stop here: just pick a random username if it wasn't provided and say we're registered */
1628 5fafdeea Saúl Ibarra Corretgé
                                if(!username)
1629 d236f0e9 Lorenzo Miniero
                                        g_snprintf(user_id, 255, "janus-sip-%"SCNu32"", janus_random_uint32());
1630 5fafdeea Saúl Ibarra Corretgé
                                JANUS_LOG(LOG_INFO, "Guest will have username %s\n", user_id);
1631 735be1e9 Saúl Ibarra Corretgé
                                send_register = FALSE;
1632 3cc3cab3 meetecho
                        } else {
1633 a37dd8a2 meetecho
                                json_t *secret = json_object_get(root, "secret");
1634 6da4d93c Saúl Ibarra Corretgé
                                json_t *ha1_secret = json_object_get(root, "ha1_secret");
1635 99f4b957 tuijldert
                                json_t *authuser = json_object_get(root, "authuser");
1636 6da4d93c Saúl Ibarra Corretgé
                                if(!secret && !ha1_secret) {
1637
                                        JANUS_LOG(LOG_ERR, "Missing element (secret or ha1_secret)\n");
1638 3cc3cab3 meetecho
                                        error_code = JANUS_SIP_ERROR_MISSING_ELEMENT;
1639 6da4d93c Saúl Ibarra Corretgé
                                        g_snprintf(error_cause, 512, "Missing element (secret or ha1_secret)");
1640 aff9f5c0 meetecho
                                        goto error;
1641
                                }
1642 6da4d93c Saúl Ibarra Corretgé
                                if(secret && ha1_secret) {
1643
                                        JANUS_LOG(LOG_ERR, "Conflicting elements specified (secret and ha1_secret)\n");
1644 3cc3cab3 meetecho
                                        error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
1645 6da4d93c Saúl Ibarra Corretgé
                                        g_snprintf(error_cause, 512, "Conflicting elements specified (secret and ha1_secret)");
1646 a37dd8a2 meetecho
                                        goto error;
1647
                                }
1648 6da4d93c Saúl Ibarra Corretgé
                                const char *secret_text;
1649
                                if(secret) {
1650
                                        secret_text = json_string_value(secret);
1651
                                        session->account.secret = g_strdup(secret_text);
1652
                                        session->account.secret_type = janus_sip_secret_type_plaintext;
1653
                                } else {
1654
                                        secret_text = json_string_value(ha1_secret);
1655
                                        session->account.secret = g_strdup(secret_text);
1656
                                        session->account.secret_type = janus_sip_secret_type_hashed;
1657
                                }
1658 99f4b957 tuijldert
                                if (authuser) {
1659
                                        const char *authuser_text;
1660
                                        authuser_text = json_string_value(authuser);
1661
                                        session->account.authuser = g_strdup(authuser_text);
1662
                                } else {
1663
                                        session->account.authuser = g_strdup(user_id);
1664
                                }
1665 5fafdeea Saúl Ibarra Corretgé
                                /* Got the values, try registering now */
1666
                                JANUS_LOG(LOG_VERB, "Registering user %s (secret %s) @ %s through %s\n",
1667 1d4a3e62 Saúl Ibarra Corretgé
                                        username_text, secret_text, username_uri.url->url_host, proxy_text != NULL ? proxy_text : "(null)");
1668 5fafdeea Saúl Ibarra Corretgé
                        }
1669
1670
                        session->account.identity = g_strdup(username_text);
1671 fee76880 Lorenzo Miniero
                        g_hash_table_insert(identities, session->account.identity, session);
1672 43a3a2dc Lorenzo Miniero
                        session->account.sips = sips;
1673 5fafdeea Saúl Ibarra Corretgé
                        session->account.username = g_strdup(user_id);
1674 147173bd Saúl Ibarra Corretgé
                        if (display_name_text) {
1675
                                session->account.display_name = g_strdup(display_name_text);
1676
                        }
1677 372e28b5 Saúl Ibarra Corretgé
                        if (user_agent_text) {
1678
                                session->account.user_agent = g_strdup(user_agent_text);
1679
                        }
1680 1d4a3e62 Saúl Ibarra Corretgé
                        if (proxy_text) {
1681
                                session->account.proxy = g_strdup(proxy_text);
1682
                        }
1683 5fafdeea Saúl Ibarra Corretgé
1684 ad872005 Saúl Ibarra Corretgé
                        session->account.registration_status = janus_sip_registration_status_registering;
1685 1d287e40 Lorenzo Miniero
                        if(session->stack == NULL) {
1686 5fafdeea Saúl Ibarra Corretgé
                                /* Start the thread first */
1687
                                GError *error = NULL;
1688 c7498fa9 Lorenzo Miniero
                                char tname[16];
1689
                                g_snprintf(tname, sizeof(tname), "sip %s", session->account.username);
1690
                                g_thread_try_new(tname, janus_sip_sofia_thread, session, &error);
1691 5fafdeea Saúl Ibarra Corretgé
                                if(error != NULL) {
1692
                                        JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the SIP Sofia thread...\n", error->code, error->message ? error->message : "??");
1693
                                        error_code = JANUS_SIP_ERROR_UNKNOWN_ERROR;
1694
                                        g_snprintf(error_cause, 512, "Got error %d (%s) trying to launch the SIP Sofia thread", error->code, error->message ? error->message : "??");
1695
                                        goto error;
1696
                                }
1697
                                long int timeout = 0;
1698 1d287e40 Lorenzo Miniero
                                while(session->stack == NULL || session->stack->s_nua == NULL) {
1699 5fafdeea Saúl Ibarra Corretgé
                                        g_usleep(100000);
1700
                                        timeout += 100000;
1701 a37dd8a2 meetecho
                                        if(timeout >= 2000000) {
1702 5fafdeea Saúl Ibarra Corretgé
                                                break;
1703 a37dd8a2 meetecho
                                        }
1704
                                }
1705 5fafdeea Saúl Ibarra Corretgé
                                if(timeout >= 2000000) {
1706
                                        JANUS_LOG(LOG_ERR, "Two seconds passed and still no NUA, problems with the thread?\n");
1707
                                        error_code = JANUS_SIP_ERROR_UNKNOWN_ERROR;
1708
                                        g_snprintf(error_cause, 512, "Two seconds passed and still no NUA, problems with the thread?");
1709
                                        goto error;
1710
                                }
1711
                        }
1712 735be1e9 Saúl Ibarra Corretgé
                        if(session->stack->s_nh_r != NULL) {
1713 5fafdeea Saúl Ibarra Corretgé
                                nua_handle_destroy(session->stack->s_nh_r);
1714 735be1e9 Saúl Ibarra Corretgé
                                session->stack->s_nh_r = NULL;
1715
                        }
1716 5fafdeea Saúl Ibarra Corretgé
1717 735be1e9 Saúl Ibarra Corretgé
                        if (send_register) {
1718 be35facb meetecho
                                session->stack->s_nh_r = nua_handle(session->stack->s_nua, session, TAG_END());
1719 a37dd8a2 meetecho
                                if(session->stack->s_nh_r == NULL) {
1720
                                        JANUS_LOG(LOG_ERR, "NUA Handle for REGISTER still null??\n");
1721 3cc3cab3 meetecho
                                        error_code = JANUS_SIP_ERROR_LIBSOFIA_ERROR;
1722 c94052c2 meetecho
                                        g_snprintf(error_cause, 512, "Invalid NUA Handle");
1723 a37dd8a2 meetecho
                                        goto error;
1724
                                }
1725 0270beb3 Saúl Ibarra Corretgé
                                char ttl_text[20];
1726
                                g_snprintf(ttl_text, sizeof(ttl_text), "%d", ttl);
1727 a37dd8a2 meetecho
                                nua_register(session->stack->s_nh_r,
1728 bccfd422 Saúl Ibarra Corretgé
                                        NUTAG_M_USERNAME(session->account.username),
1729
                                        SIPTAG_FROM_STR(username_text),
1730
                                        SIPTAG_TO_STR(username_text),
1731 0270beb3 Saúl Ibarra Corretgé
                                        SIPTAG_EXPIRES_STR(ttl_text),
1732 bccfd422 Saúl Ibarra Corretgé
                                        NUTAG_PROXY(proxy_text),
1733 a37dd8a2 meetecho
                                        TAG_END());
1734
                                result = json_object();
1735
                                json_object_set_new(result, "event", json_string("registering"));
1736 5fafdeea Saúl Ibarra Corretgé
                        } else {
1737 735be1e9 Saúl Ibarra Corretgé
                                JANUS_LOG(LOG_VERB, "Not sending a SIP REGISTER: either send_register was set to false or guest mode was enabled\n");
1738
                                session->account.registration_status = janus_sip_registration_status_disabled;
1739 5fafdeea Saúl Ibarra Corretgé
                                result = json_object();
1740
                                json_object_set_new(result, "event", json_string("registered"));
1741
                                json_object_set_new(result, "username", json_string(session->account.username));
1742 51db8a86 Lorenzo Miniero
                                json_object_set_new(result, "register_sent", json_false());
1743 4d8c7356 Lorenzo Miniero
                                /* Also notify event handlers */
1744 71a04f89 Lorenzo Miniero
                                if(notify_events && gateway->events_is_enabled()) {
1745 4d8c7356 Lorenzo Miniero
                                        json_t *info = json_object();
1746
                                        json_object_set_new(info, "event", json_string("registered"));
1747
                                        json_object_set_new(info, "identity", json_string(session->account.identity));
1748
                                        json_object_set_new(info, "type", json_string("guest"));
1749 c734a91a Lorenzo Miniero
                                        gateway->notify_event(&janus_sip_plugin, session->handle, info);
1750 4d8c7356 Lorenzo Miniero
                                }
1751 a37dd8a2 meetecho
                        }
1752 be35facb meetecho
                } else if(!strcasecmp(request_text, "call")) {
1753
                        /* Call another peer */
1754 1d287e40 Lorenzo Miniero
                        if(session->stack == NULL) {
1755
                                JANUS_LOG(LOG_ERR, "Wrong state (register first)\n");
1756
                                error_code = JANUS_SIP_ERROR_WRONG_STATE;
1757
                                g_snprintf(error_cause, 512, "Wrong state (register first)");
1758
                                goto error;
1759
                        }
1760 ad872005 Saúl Ibarra Corretgé
                        if(session->status >= janus_sip_call_status_inviting) {
1761
                                JANUS_LOG(LOG_ERR, "Wrong state (already in a call? status=%s)\n", janus_sip_call_status_string(session->status));
1762 3cc3cab3 meetecho
                                error_code = JANUS_SIP_ERROR_WRONG_STATE;
1763 ad872005 Saúl Ibarra Corretgé
                                g_snprintf(error_cause, 512, "Wrong state (already in a call? status=%s)", janus_sip_call_status_string(session->status));
1764 be35facb meetecho
                                goto error;
1765
                        }
1766 94926fcd Andreas Girgensohn
                        JANUS_VALIDATE_JSON_OBJECT(root, call_parameters,
1767
                                error_code, error_cause, TRUE,
1768
                                JANUS_SIP_ERROR_MISSING_ELEMENT, JANUS_SIP_ERROR_INVALID_ELEMENT);
1769
                        if(error_code != 0)
1770 a37dd8a2 meetecho
                                goto error;
1771 94926fcd Andreas Girgensohn
                        json_t *uri = json_object_get(root, "uri");
1772 1a4bc02f Lorenzo Miniero
                        /* Check if we need to ACK manually (e.g., for the Record-Route hack) */
1773
                        json_t *autoack = json_object_get(root, "autoack");
1774
                        gboolean do_autoack = autoack ? json_is_true(autoack) : TRUE;
1775 a78520c4 Lorenzo Miniero
                        /* Check if the INVITE needs to be enriched with custom headers */
1776
                        char custom_headers[2048];
1777
                        custom_headers[0] = '\0';
1778
                        json_t *headers = json_object_get(root, "headers");
1779
                        if(headers) {
1780
                                if(json_object_size(headers) > 0) {
1781
                                        /* Parse custom headers */
1782
                                        const char *key = NULL;
1783
                                        json_t *value = NULL;
1784 6d4c9338 Lorenzo Miniero
                                        void *iter = json_object_iter(headers);
1785
                                        while(iter != NULL) {
1786
                                                key = json_object_iter_key(iter);
1787
                                                value = json_object_get(headers, key);
1788 a78520c4 Lorenzo Miniero
                                                if(value == NULL || !json_is_string(value)) {
1789
                                                        JANUS_LOG(LOG_WARN, "Skipping header '%s': value is not a string\n", key);
1790 6d4c9338 Lorenzo Miniero
                                                        iter = json_object_iter_next(headers, iter);
1791 a78520c4 Lorenzo Miniero
                                                        continue;
1792
                                                }
1793
                                                char h[255];
1794
                                                g_snprintf(h, 255, "%s: %s\r\n", key, json_string_value(value));
1795
                                                JANUS_LOG(LOG_VERB, "Adding custom header, %s", h);
1796
                                                g_strlcat(custom_headers, h, 2048);
1797 6d4c9338 Lorenzo Miniero
                                                iter = json_object_iter_next(headers, iter);
1798 a78520c4 Lorenzo Miniero
                                        }
1799
                                }
1800
                        }
1801 ac36fd1d Lorenzo Miniero
                        /* SDES-SRTP is disabled by default, let's see if we need to enable it */
1802
                        gboolean offer_srtp = FALSE, require_srtp = FALSE;
1803 91bc289d Lorenzo Miniero
                        json_t *srtp = json_object_get(root, "srtp");
1804 ac36fd1d Lorenzo Miniero
                        if(srtp) {
1805
                                const char *srtp_text = json_string_value(srtp);
1806
                                if(!strcasecmp(srtp_text, "sdes_optional")) {
1807
                                        /* Negotiate SDES, but make it optional */
1808
                                        offer_srtp = TRUE;
1809
                                } else if(!strcasecmp(srtp_text, "sdes_mandatory")) {
1810
                                        /* Negotiate SDES, and require it */
1811
                                        offer_srtp = TRUE;
1812
                                        require_srtp = TRUE;
1813
                                } else {
1814
                                        JANUS_LOG(LOG_ERR, "Invalid element (srtp can only be sdes_optional or sdes_mandatory)\n");
1815
                                        error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
1816
                                        g_snprintf(error_cause, 512, "Invalid element (srtp can only be sdes_optional or sdes_mandatory)");
1817
                                        goto error;
1818
                                }
1819 91bc289d Lorenzo Miniero
                        }
1820 a37dd8a2 meetecho
                        /* Parse address */
1821
                        const char *uri_text = json_string_value(uri);
1822 33f37af8 Saúl Ibarra Corretgé
                        janus_sip_uri_t target_uri;
1823
                        if (janus_sip_parse_uri(&target_uri, uri_text) < 0) {
1824 a37dd8a2 meetecho
                                JANUS_LOG(LOG_ERR, "Invalid user address %s\n", uri_text);
1825 3cc3cab3 meetecho
                                error_code = JANUS_SIP_ERROR_INVALID_ADDRESS;
1826 c94052c2 meetecho
                                g_snprintf(error_cause, 512, "Invalid user address %s\n", uri_text);
1827 be35facb meetecho
                                goto error;
1828
                        }
1829
                        /* Any SDP to handle? if not, something's wrong */
1830 dd11fa0a Lorenzo Miniero
                        const char *msg_sdp_type = json_string_value(json_object_get(msg->jsep, "type"));
1831
                        const char *msg_sdp = json_string_value(json_object_get(msg->jsep, "sdp"));
1832
                        if(!msg_sdp) {
1833 3a26e009 meetecho
                                JANUS_LOG(LOG_ERR, "Missing SDP\n");
1834 3cc3cab3 meetecho
                                error_code = JANUS_SIP_ERROR_MISSING_SDP;
1835 c94052c2 meetecho
                                g_snprintf(error_cause, 512, "Missing SDP");
1836 be35facb meetecho
                                goto error;
1837
                        }
1838 db1e9a1f Lorenzo Miniero
                        if(strstr(msg_sdp, "m=application")) {
1839 1aee055e Lorenzo Miniero
                                JANUS_LOG(LOG_ERR, "The SIP plugin does not support DataChannels\n");
1840
                                error_code = JANUS_SIP_ERROR_MISSING_SDP;
1841
                                g_snprintf(error_cause, 512, "The SIP plugin does not support DataChannels");
1842
                                goto error;
1843
                        }
1844 a37dd8a2 meetecho
                        JANUS_LOG(LOG_VERB, "%s is calling %s\n", session->account.username, uri_text);
1845 dd11fa0a Lorenzo Miniero
                        JANUS_LOG(LOG_VERB, "This is involving a negotiation (%s) as well:\n%s\n", msg_sdp_type, msg_sdp);
1846 91bc289d Lorenzo Miniero
                        /* Clean up SRTP stuff from before first, in case it's still needed */
1847
                        janus_sip_srtp_cleanup(session);
1848 ac36fd1d Lorenzo Miniero
                        session->media.require_srtp = require_srtp;
1849 91bc289d Lorenzo Miniero
                        session->media.has_srtp_local = offer_srtp;
1850
                        if(offer_srtp) {
1851 ac36fd1d Lorenzo Miniero
                                JANUS_LOG(LOG_VERB, "Going to negotiate SDES-SRTP (%s)...\n", require_srtp ? "mandatory" : "optional");
1852 91bc289d Lorenzo Miniero
                        }
1853 203da285 Lorenzo Miniero
                        /* Parse the SDP we got, manipulate some things, and generate a new one */
1854 60e2d6d3 Lorenzo Miniero
                        char sdperror[100];
1855 cf0d7037 Lorenzo Miniero
                        janus_sdp *parsed_sdp = janus_sdp_parse(msg_sdp, sdperror, sizeof(sdperror));
1856 203da285 Lorenzo Miniero
                        if(!parsed_sdp) {
1857 60e2d6d3 Lorenzo Miniero
                                JANUS_LOG(LOG_ERR, "Error parsing SDP: %s\n", sdperror);
1858 203da285 Lorenzo Miniero
                                error_code = JANUS_SIP_ERROR_MISSING_SDP;
1859 60e2d6d3 Lorenzo Miniero
                                g_snprintf(error_cause, 512, "Error parsing SDP: %s", sdperror);
1860 203da285 Lorenzo Miniero
                                goto error;
1861
                        }
1862 be35facb meetecho
                        /* Allocate RTP ports and merge them with the anonymized SDP */
1863 be648eca Lorenzo Miniero
                        if(strstr(msg_sdp, "m=audio") && !strstr(msg_sdp, "m=audio 0")) {
1864 3a26e009 meetecho
                                JANUS_LOG(LOG_VERB, "Going to negotiate audio...\n");
1865 be35facb meetecho
                                session->media.has_audio = 1;        /* FIXME Maybe we need a better way to signal this */
1866
                        }
1867 be648eca Lorenzo Miniero
                        if(strstr(msg_sdp, "m=video") && !strstr(msg_sdp, "m=video 0")) {
1868 3a26e009 meetecho
                                JANUS_LOG(LOG_VERB, "Going to negotiate video...\n");
1869 be35facb meetecho
                                session->media.has_video = 1;        /* FIXME Maybe we need a better way to signal this */
1870
                        }
1871
                        if(janus_sip_allocate_local_ports(session) < 0) {
1872 3a26e009 meetecho
                                JANUS_LOG(LOG_ERR, "Could not allocate RTP/RTCP ports\n");
1873 60e2d6d3 Lorenzo Miniero
                                janus_sdp_free(parsed_sdp);
1874 3cc3cab3 meetecho
                                error_code = JANUS_SIP_ERROR_IO_ERROR;
1875 c94052c2 meetecho
                                g_snprintf(error_cause, 512, "Could not allocate RTP/RTCP ports");
1876 be35facb meetecho
                                goto error;
1877
                        }
1878 02eeeba4 Lorenzo Miniero
                        char *sdp = janus_sip_sdp_manipulate(session, parsed_sdp, FALSE);
1879 203da285 Lorenzo Miniero
                        if(sdp == NULL) {
1880
                                JANUS_LOG(LOG_ERR, "Could not allocate RTP/RTCP ports\n");
1881 60e2d6d3 Lorenzo Miniero
                                janus_sdp_free(parsed_sdp);
1882 203da285 Lorenzo Miniero
                                error_code = JANUS_SIP_ERROR_IO_ERROR;
1883
                                g_snprintf(error_cause, 512, "Could not allocate RTP/RTCP ports");
1884
                                goto error;
1885 be35facb meetecho
                        }
1886 4d8ee7e6 Lorenzo Miniero
                        /* Take note of the SDP (may be useful for UPDATEs or re-INVITEs) */
1887
                        janus_sdp_free(session->sdp);
1888
                        session->sdp = parsed_sdp;
1889 203da285 Lorenzo Miniero
                        JANUS_LOG(LOG_VERB, "Prepared SDP for INVITE:\n%s", sdp);
1890 147173bd Saúl Ibarra Corretgé
                        /* Prepare the From header */
1891
                        char from_hdr[1024];
1892
                        if (session->account.display_name) {
1893
                                g_snprintf(from_hdr, sizeof(from_hdr), "\"%s\" <%s>", session->account.display_name, session->account.identity);
1894
                        } else {
1895
                                g_snprintf(from_hdr, sizeof(from_hdr), "%s", session->account.identity);
1896
                        }
1897 a78520c4 Lorenzo Miniero
                        /* Prepare the stack */
1898 db175fd5 meetecho
                        if(session->stack->s_nh_i != NULL)
1899
                                nua_handle_destroy(session->stack->s_nh_i);
1900
                        session->stack->s_nh_i = nua_handle(session->stack->s_nua, session, TAG_END());
1901 3a26e009 meetecho
                        if(session->stack->s_nh_i == NULL) {
1902
                                JANUS_LOG(LOG_WARN, "NUA Handle for INVITE still null??\n");
1903 203da285 Lorenzo Miniero
                                g_free(sdp);
1904 4d8ee7e6 Lorenzo Miniero
                                session->sdp = NULL;
1905 60e2d6d3 Lorenzo Miniero
                                janus_sdp_free(parsed_sdp);
1906 3cc3cab3 meetecho
                                error_code = JANUS_SIP_ERROR_LIBSOFIA_ERROR;
1907 c94052c2 meetecho
                                g_snprintf(error_cause, 512, "Invalid NUA Handle");
1908 a37dd8a2 meetecho
                                goto error;
1909 3a26e009 meetecho
                        }
1910 c1bd6f7a Lorenzo Miniero
                        g_atomic_int_set(&session->hangingup, 0);
1911 ad872005 Saúl Ibarra Corretgé
                        session->status = janus_sip_call_status_inviting;
1912 4d8c7356 Lorenzo Miniero
                        /* Create a random call-id */
1913
                        char callid[24];
1914
                        janus_sip_random_string(24, (char *)&callid);
1915
                        /* Also notify event handlers */
1916 71a04f89 Lorenzo Miniero
                        if(notify_events && gateway->events_is_enabled()) {
1917 4d8c7356 Lorenzo Miniero
                                json_t *info = json_object();
1918
                                json_object_set_new(info, "event", json_string("calling"));
1919
                                json_object_set_new(info, "callee", json_string(uri_text));
1920
                                json_object_set_new(info, "call-id", json_string(callid));
1921
                                json_object_set_new(info, "sdp", json_string(sdp));
1922 c734a91a Lorenzo Miniero
                                gateway->notify_event(&janus_sip_plugin, session->handle, info);
1923 4d8c7356 Lorenzo Miniero
                        }
1924 a78520c4 Lorenzo Miniero
                        /* Send INVITE */
1925 4d8c7356 Lorenzo Miniero
                        session->callee = g_strdup(uri_text);
1926
                        session->callid = g_strdup(callid);
1927 fee76880 Lorenzo Miniero
                        g_hash_table_insert(callids, session->callid, session);
1928 1a4bc02f Lorenzo Miniero
                        session->media.autoack = do_autoack;
1929 be35facb meetecho
                        nua_invite(session->stack->s_nh_i,
1930 147173bd Saúl Ibarra Corretgé
                                SIPTAG_FROM_STR(from_hdr),
1931 bccfd422 Saúl Ibarra Corretgé
                                SIPTAG_TO_STR(uri_text),
1932 4d8c7356 Lorenzo Miniero
                                SIPTAG_CALL_ID_STR(callid),
1933 bccfd422 Saúl Ibarra Corretgé
                                SOATAG_USER_SDP_STR(sdp),
1934
                                NUTAG_PROXY(session->account.proxy),
1935 a78520c4 Lorenzo Miniero
                                TAG_IF(strlen(custom_headers) > 0, SIPTAG_HEADER_STR(custom_headers)),
1936 7f774183 Saúl Ibarra Corretgé
                                NUTAG_AUTOANSWER(0),
1937 1a4bc02f Lorenzo Miniero
                                NUTAG_AUTOACK(do_autoack),
1938 be35facb meetecho
                                TAG_END());
1939 a37dd8a2 meetecho
                        g_free(sdp);
1940 91b1c78a meetecho
                        if(session->transaction)
1941
                                g_free(session->transaction);
1942
                        session->transaction = msg->transaction ? g_strdup(msg->transaction) : NULL;
1943 be35facb meetecho
                        /* Send an ack back */
1944
                        result = json_object();
1945
                        json_object_set_new(result, "event", json_string("calling"));
1946
                } else if(!strcasecmp(request_text, "accept")) {
1947 ad872005 Saúl Ibarra Corretgé
                        if(session->status != janus_sip_call_status_invited) {
1948
                                JANUS_LOG(LOG_ERR, "Wrong state (not invited? status=%s)\n", janus_sip_call_status_string(session->status));
1949 3cc3cab3 meetecho
                                error_code = JANUS_SIP_ERROR_WRONG_STATE;
1950 ad872005 Saúl Ibarra Corretgé
                                g_snprintf(error_cause, 512, "Wrong state (not invited? status=%s)", janus_sip_call_status_string(session->status));
1951 be35facb meetecho
                                goto error;
1952
                        }
1953
                        if(session->callee == NULL) {
1954 3a26e009 meetecho
                                JANUS_LOG(LOG_ERR, "Wrong state (no caller?)\n");
1955 3cc3cab3 meetecho
                                error_code = JANUS_SIP_ERROR_WRONG_STATE;
1956 c94052c2 meetecho
                                g_snprintf(error_cause, 512, "Wrong state (no caller?)");
1957 be35facb meetecho
                                goto error;
1958
                        }
1959 94926fcd Andreas Girgensohn
                        JANUS_VALIDATE_JSON_OBJECT(root, accept_parameters,
1960
                                error_code, error_cause, TRUE,
1961
                                JANUS_SIP_ERROR_MISSING_ELEMENT, JANUS_SIP_ERROR_INVALID_ELEMENT);
1962
                        if(error_code != 0)
1963
                                goto error;
1964 91bc289d Lorenzo Miniero
                        json_t *srtp = json_object_get(root, "srtp");
1965 ac36fd1d Lorenzo Miniero
                        gboolean answer_srtp = FALSE;
1966
                        if(srtp) {
1967
                                const char *srtp_text = json_string_value(srtp);
1968
                                if(!strcasecmp(srtp_text, "sdes_optional")) {
1969
                                        /* Negotiate SDES, but make it optional */
1970
                                        answer_srtp = TRUE;
1971
                                } else if(!strcasecmp(srtp_text, "sdes_mandatory")) {
1972
                                        /* Negotiate SDES, and require it */
1973
                                        answer_srtp = TRUE;
1974
                                        session->media.require_srtp = TRUE;
1975
                                } else {
1976
                                        JANUS_LOG(LOG_ERR, "Invalid element (srtp can only be sdes_optional or sdes_mandatory)\n");
1977
                                        error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
1978
                                        g_snprintf(error_cause, 512, "Invalid element (srtp can only be sdes_optional or sdes_mandatory)");
1979
                                        goto error;
1980
                                }
1981
                        }
1982
                        if(session->media.require_srtp && !session->media.has_srtp_remote) {
1983
                                JANUS_LOG(LOG_ERR, "Can't accept the call: SDES-SRTP required, but caller didn't offer it\n");
1984
                                error_code = JANUS_SIP_ERROR_TOO_STRICT;
1985
                                g_snprintf(error_cause, 512, "Can't accept the call: SDES-SRTP required, but caller didn't offer it");
1986 91bc289d Lorenzo Miniero
                                goto error;
1987
                        }
1988 203da285 Lorenzo Miniero
                        answer_srtp = answer_srtp || session->media.has_srtp_remote;
1989 be35facb meetecho
                        /* Any SDP to handle? if not, something's wrong */
1990 dd11fa0a Lorenzo Miniero
                        const char *msg_sdp_type = json_string_value(json_object_get(msg->jsep, "type"));
1991
                        const char *msg_sdp = json_string_value(json_object_get(msg->jsep, "sdp"));
1992
                        if(!msg_sdp) {
1993 3a26e009 meetecho
                                JANUS_LOG(LOG_ERR, "Missing SDP\n");
1994 3cc3cab3 meetecho
                                error_code = JANUS_SIP_ERROR_MISSING_SDP;
1995 c94052c2 meetecho
                                g_snprintf(error_cause, 512, "Missing SDP");
1996 be35facb meetecho
                                goto error;
1997
                        }
1998
                        /* Accept a call from another peer */
1999 3a26e009 meetecho
                        JANUS_LOG(LOG_VERB, "We're accepting the call from %s\n", session->callee);
2000 dd11fa0a Lorenzo Miniero
                        JANUS_LOG(LOG_VERB, "This is involving a negotiation (%s) as well:\n%s\n", msg_sdp_type, msg_sdp);
2001 91bc289d Lorenzo Miniero
                        session->media.has_srtp_local = answer_srtp;
2002
                        if(answer_srtp) {
2003 ac36fd1d Lorenzo Miniero
                                JANUS_LOG(LOG_VERB, "Going to negotiate SDES-SRTP (%s)...\n", session->media.require_srtp ? "mandatory" : "optional");
2004 91bc289d Lorenzo Miniero
                        }
2005 203da285 Lorenzo Miniero
                        /* Parse the SDP we got, manipulate some things, and generate a new one */
2006 60e2d6d3 Lorenzo Miniero
                        char sdperror[100];
2007 cf0d7037 Lorenzo Miniero
                        janus_sdp *parsed_sdp = janus_sdp_parse(msg_sdp, sdperror, sizeof(sdperror));
2008 203da285 Lorenzo Miniero
                        if(!parsed_sdp) {
2009 60e2d6d3 Lorenzo Miniero
                                JANUS_LOG(LOG_ERR, "Error parsing SDP: %s\n", sdperror);
2010 203da285 Lorenzo Miniero
                                error_code = JANUS_SIP_ERROR_MISSING_SDP;
2011 60e2d6d3 Lorenzo Miniero
                                g_snprintf(error_cause, 512, "Error parsing SDP: %s", sdperror);
2012 203da285 Lorenzo Miniero
                                goto error;
2013
                        }
2014 be35facb meetecho
                        /* Allocate RTP ports and merge them with the anonymized SDP */
2015 be648eca Lorenzo Miniero
                        if(strstr(msg_sdp, "m=audio") && !strstr(msg_sdp, "m=audio 0")) {
2016 3a26e009 meetecho
                                JANUS_LOG(LOG_VERB, "Going to negotiate audio...\n");
2017 be35facb meetecho
                                session->media.has_audio = 1;        /* FIXME Maybe we need a better way to signal this */
2018
                        }
2019 be648eca Lorenzo Miniero
                        if(strstr(msg_sdp, "m=video") && !strstr(msg_sdp, "m=video 0")) {
2020 3a26e009 meetecho
                                JANUS_LOG(LOG_VERB, "Going to negotiate video...\n");
2021 be35facb meetecho
                                session->media.has_video = 1;        /* FIXME Maybe we need a better way to signal this */
2022
                        }
2023
                        if(janus_sip_allocate_local_ports(session) < 0) {
2024 3a26e009 meetecho
                                JANUS_LOG(LOG_ERR, "Could not allocate RTP/RTCP ports\n");
2025 60e2d6d3 Lorenzo Miniero
                                janus_sdp_free(parsed_sdp);
2026 3cc3cab3 meetecho
                                error_code = JANUS_SIP_ERROR_IO_ERROR;
2027 c94052c2 meetecho
                                g_snprintf(error_cause, 512, "Could not allocate RTP/RTCP ports");
2028 be35facb meetecho
                                goto error;
2029
                        }
2030 02eeeba4 Lorenzo Miniero
                        char *sdp = janus_sip_sdp_manipulate(session, parsed_sdp, TRUE);
2031 203da285 Lorenzo Miniero
                        if(sdp == NULL) {
2032
                                JANUS_LOG(LOG_ERR, "Could not allocate RTP/RTCP ports\n");
2033 60e2d6d3 Lorenzo Miniero
                                janus_sdp_free(parsed_sdp);
2034 203da285 Lorenzo Miniero
                                error_code = JANUS_SIP_ERROR_IO_ERROR;
2035
                                g_snprintf(error_cause, 512, "Could not allocate RTP/RTCP ports");
2036
                                goto error;
2037 be35facb meetecho
                        }
2038 02eeeba4 Lorenzo Miniero
                        if(session->media.audio_pt > -1) {
2039
                                session->media.audio_pt_name = janus_get_codec_from_pt(sdp, session->media.audio_pt);
2040 62f02b26 Lorenzo Miniero
                                JANUS_LOG(LOG_VERB, "Detected audio codec: %d (%s)\n", session->media.audio_pt, session->media.audio_pt_name);
2041 02eeeba4 Lorenzo Miniero
                        }
2042
                        if(session->media.video_pt > -1) {
2043
                                session->media.video_pt_name = janus_get_codec_from_pt(sdp, session->media.video_pt);
2044 62f02b26 Lorenzo Miniero
                                JANUS_LOG(LOG_VERB, "Detected video codec: %d (%s)\n", session->media.video_pt, session->media.video_pt_name);
2045 02eeeba4 Lorenzo Miniero
                        }
2046 4d8ee7e6 Lorenzo Miniero
                        /* Take note of the SDP (may be useful for UPDATEs or re-INVITEs) */
2047
                        janus_sdp_free(session->sdp);
2048
                        session->sdp = parsed_sdp;
2049 203da285 Lorenzo Miniero
                        JANUS_LOG(LOG_VERB, "Prepared SDP for 200 OK:\n%s", sdp);
2050 4d8c7356 Lorenzo Miniero
                        /* Also notify event handlers */
2051 71a04f89 Lorenzo Miniero
                        if(notify_events && gateway->events_is_enabled()) {
2052 4d8c7356 Lorenzo Miniero
                                json_t *info = json_object();
2053
                                json_object_set_new(info, "event", json_string("accepted"));
2054
                                if(session->callid)
2055
                                        json_object_set_new(info, "call-id", json_string(session->callid));
2056 c734a91a Lorenzo Miniero
                                gateway->notify_event(&janus_sip_plugin, session->handle, info);
2057 4d8c7356 Lorenzo Miniero
                        }
2058 be35facb meetecho
                        /* Send 200 OK */
2059 c1bd6f7a Lorenzo Miniero
                        g_atomic_int_set(&session->hangingup, 0);
2060 ad872005 Saúl Ibarra Corretgé
                        session->status = janus_sip_call_status_incall;
2061 3a26e009 meetecho
                        if(session->stack->s_nh_i == NULL) {
2062
                                JANUS_LOG(LOG_WARN, "NUA Handle for 200 OK still null??\n");
2063
                        }
2064 be35facb meetecho
                        nua_respond(session->stack->s_nh_i,
2065
                                200, sip_status_phrase(200),
2066 bccfd422 Saúl Ibarra Corretgé
                                SOATAG_USER_SDP_STR(sdp),
2067 7f774183 Saúl Ibarra Corretgé
                                NUTAG_AUTOANSWER(0),
2068 be35facb meetecho
                                TAG_END());
2069 a37dd8a2 meetecho
                        g_free(sdp);
2070 be35facb meetecho
                        /* Send an ack back */
2071
                        result = json_object();
2072
                        json_object_set_new(result, "event", json_string("accepted"));
2073 a37dd8a2 meetecho
                        /* Start the media */
2074
                        session->media.ready = 1;        /* FIXME Maybe we need a better way to signal this */
2075
                        GError *error = NULL;
2076 c7498fa9 Lorenzo Miniero
                        char tname[16];
2077
                        g_snprintf(tname, sizeof(tname), "siprtp %s", session->account.username);
2078
                        g_thread_try_new(tname, janus_sip_relay_thread, session, &error);
2079 dbf63b61 meetecho
                        if(error != NULL) {
2080
                                JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch the RTP/RTCP thread...\n", error->code, error->message ? error->message : "??");
2081 a37dd8a2 meetecho
                        }
2082
                } else if(!strcasecmp(request_text, "decline")) {
2083
                        /* Reject an incoming call */
2084 ad872005 Saúl Ibarra Corretgé
                        if(session->status != janus_sip_call_status_invited) {
2085
                                JANUS_LOG(LOG_ERR, "Wrong state (not invited? status=%s)\n", janus_sip_call_status_string(session->status));
2086 a37dd8a2 meetecho
                                /* Ignore */
2087 8f691b0e Lorenzo Miniero
                                janus_sip_message_free(msg);
2088 a37dd8a2 meetecho
                                continue;
2089 c94052c2 meetecho
                                //~ g_snprintf(error_cause, 512, "Wrong state (not in a call?)");
2090 a37dd8a2 meetecho
                                //~ goto error;
2091
                        }
2092
                        if(session->callee == NULL) {
2093
                                JANUS_LOG(LOG_ERR, "Wrong state (no callee?)\n");
2094 3cc3cab3 meetecho
                                error_code = JANUS_SIP_ERROR_WRONG_STATE;
2095 c94052c2 meetecho
                                g_snprintf(error_cause, 512, "Wrong state (no callee?)");
2096 a37dd8a2 meetecho
                                goto error;
2097
                        }
2098 ad872005 Saúl Ibarra Corretgé
                        session->status = janus_sip_call_status_closing;
2099 a37dd8a2 meetecho
                        if(session->stack->s_nh_i == NULL) {
2100
                                JANUS_LOG(LOG_WARN, "NUA Handle for 200 OK still null??\n");
2101
                        }
2102 8694c1a0 Saúl Ibarra Corretgé
                        int response_code = 486;
2103
                        json_t *code_json = json_object_get(root, "code");
2104
                        if (code_json && json_is_integer(code_json))
2105
                                response_code = json_integer_value(code_json);
2106
                        if (response_code <= 399) {
2107
                                JANUS_LOG(LOG_WARN, "Invalid SIP response code specified, using 486 to decline call\n");
2108
                                response_code = 486;
2109
                        }
2110
                        nua_respond(session->stack->s_nh_i, response_code, sip_status_phrase(response_code), TAG_END());
2111 4d8c7356 Lorenzo Miniero
                        /* Also notify event handlers */
2112 71a04f89 Lorenzo Miniero
                        if(notify_events && gateway->events_is_enabled()) {
2113 4d8c7356 Lorenzo Miniero
                                json_t *info = json_object();
2114
                                json_object_set_new(info, "event", json_string("declined"));
2115
                                json_object_set_new(info, "callee", json_string(session->callee));
2116
                                if(session->callid)
2117
                                        json_object_set_new(info, "call-id", json_string(session->callid));
2118
                                json_object_set_new(info, "code", json_integer(response_code));
2119 c734a91a Lorenzo Miniero
                                gateway->notify_event(&janus_sip_plugin, session->handle, info);
2120 4d8c7356 Lorenzo Miniero
                        }
2121 a37dd8a2 meetecho
                        g_free(session->callee);
2122
                        session->callee = NULL;
2123
                        /* Notify the operation */
2124
                        result = json_object();
2125 8694c1a0 Saúl Ibarra Corretgé
                        json_object_set_new(result, "event", json_string("declining"));
2126
                        json_object_set_new(result, "code", json_integer(response_code));
2127 be35facb meetecho
                } else if(!strcasecmp(request_text, "hangup")) {
2128 a37dd8a2 meetecho
                        /* Hangup an ongoing call */
2129 ad872005 Saúl Ibarra Corretgé
                        if(!(session->status == janus_sip_call_status_inviting || session->status == janus_sip_call_status_incall)) {
2130
                                JANUS_LOG(LOG_ERR, "Wrong state (not in a call? status=%s)\n", janus_sip_call_status_string(session->status));
2131 a37dd8a2 meetecho
                                /* Ignore */
2132 8f691b0e Lorenzo Miniero
                                janus_sip_message_free(msg);
2133 a37dd8a2 meetecho
                                continue;
2134 c94052c2 meetecho
                                //~ g_snprintf(error_cause, 512, "Wrong state (not in a call?)");
2135 a37dd8a2 meetecho
                                //~ goto error;
2136 be35facb meetecho
                        }
2137
                        if(session->callee == NULL) {
2138 3a26e009 meetecho
                                JANUS_LOG(LOG_ERR, "Wrong state (no callee?)\n");
2139 3cc3cab3 meetecho
                                error_code = JANUS_SIP_ERROR_WRONG_STATE;
2140 c94052c2 meetecho
                                g_snprintf(error_cause, 512, "Wrong state (no callee?)");
2141 be35facb meetecho
                                goto error;
2142
                        }
2143 ad872005 Saúl Ibarra Corretgé
                        session->status = janus_sip_call_status_closing;
2144 744a2865 Saúl Ibarra Corretgé
                        nua_bye(session->stack->s_nh_i, TAG_END());
2145 be35facb meetecho
                        g_free(session->callee);
2146
                        session->callee = NULL;
2147
                        /* Notify the operation */
2148
                        result = json_object();
2149
                        json_object_set_new(result, "event", json_string("hangingup"));
2150 6089eb4e Lorenzo Miniero
                } else if(!strcasecmp(request_text, "recording")) {
2151
                        /* Start or stop recording */
2152
                        if(!(session->status == janus_sip_call_status_inviting || session->status == janus_sip_call_status_incall)) {
2153
                                JANUS_LOG(LOG_ERR, "Wrong state (not in a call? status=%s)\n", janus_sip_call_status_string(session->status));
2154
                                g_snprintf(error_cause, 512, "Wrong state (not in a call?)");
2155
                                goto error;
2156
                        }
2157
                        if(session->callee == NULL) {
2158
                                JANUS_LOG(LOG_ERR, "Wrong state (no callee?)\n");
2159
                                error_code = JANUS_SIP_ERROR_WRONG_STATE;
2160
                                g_snprintf(error_cause, 512, "Wrong state (no callee?)");
2161
                                goto error;
2162
                        }
2163 94926fcd Andreas Girgensohn
                        JANUS_VALIDATE_JSON_OBJECT(root, recording_parameters,
2164
                                error_code, error_cause, TRUE,
2165
                                JANUS_SIP_ERROR_MISSING_ELEMENT, JANUS_SIP_ERROR_INVALID_ELEMENT);
2166
                        if(error_code != 0)
2167 6089eb4e Lorenzo Miniero
                                goto error;
2168 94926fcd Andreas Girgensohn
                        json_t *action = json_object_get(root, "action");
2169 6089eb4e Lorenzo Miniero
                        const char *action_text = json_string_value(action);
2170
                        if(strcasecmp(action_text, "start") && strcasecmp(action_text, "stop")) {
2171
                                JANUS_LOG(LOG_ERR, "Invalid action (should be start|stop)\n");
2172
                                error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
2173
                                g_snprintf(error_cause, 512, "Invalid action (should be start|stop)");
2174
                                goto error;
2175
                        }
2176
                        gboolean record_audio = FALSE, record_video = FALSE,        /* No media is recorded by default */
2177
                                record_peer_audio = FALSE, record_peer_video = FALSE;
2178
                        json_t *audio = json_object_get(root, "audio");
2179
                        record_audio = audio ? json_is_true(audio) : FALSE;
2180
                        json_t *video = json_object_get(root, "video");
2181
                        record_video = video ? json_is_true(video) : FALSE;
2182
                        json_t *peer_audio = json_object_get(root, "peer_audio");
2183
                        record_peer_audio = peer_audio ? json_is_true(peer_audio) : FALSE;
2184
                        json_t *peer_video = json_object_get(root, "peer_video");
2185
                        record_peer_video = peer_video ? json_is_true(peer_video) : FALSE;
2186
                        if(!record_audio && !record_video && !record_peer_audio && !record_peer_video) {
2187
                                JANUS_LOG(LOG_ERR, "Invalid request (at least one of audio, video, peer_audio and peer_video should be true)\n");
2188
                                error_code = JANUS_SIP_ERROR_RECORDING_ERROR;
2189
                                g_snprintf(error_cause, 512, "Invalid request (at least one of audio, video, peer_audio and peer_video should be true)");
2190
                                goto error;
2191
                        }
2192
                        json_t *recfile = json_object_get(root, "filename");
2193
                        const char *recording_base = json_string_value(recfile);
2194 d223cef1 Lorenzo Miniero
                        janus_mutex_lock(&session->rec_mutex);
2195 6089eb4e Lorenzo Miniero
                        if(!strcasecmp(action_text, "start")) {
2196
                                /* Start recording something */
2197
                                char filename[255];
2198 a41aab17 Lorenzo Miniero
                                gint64 now = janus_get_real_time();
2199 6089eb4e Lorenzo Miniero
                                if(record_peer_audio || record_peer_video) {
2200
                                        JANUS_LOG(LOG_INFO, "Starting recording of peer's %s (user %s, call %s)\n",
2201
                                                (record_peer_audio && record_peer_video ? "audio and video" : (record_peer_audio ? "audio" : "video")),
2202
                                                session->account.username, session->transaction);
2203
                                        /* Start recording this peer's audio and/or video */
2204
                                        if(record_peer_audio) {
2205
                                                memset(filename, 0, 255);
2206
                                                if(recording_base) {
2207
                                                        /* Use the filename and path we have been provided */
2208 4f9e455c Lorenzo Miniero
                                                        g_snprintf(filename, 255, "%s-peer-audio", recording_base);
2209 02eeeba4 Lorenzo Miniero
                                                        /* FIXME This only works if offer/answer happened */
2210
                                                        session->arc_peer = janus_recorder_create(NULL, session->media.audio_pt_name, filename);
2211 6089eb4e Lorenzo Miniero
                                                        if(session->arc_peer == NULL) {
2212
                                                                /* FIXME We should notify the fact the recorder could not be created */
2213
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an audio recording file for this peer!\n");
2214
                                                        }
2215
                                                } else {
2216
                                                        /* Build a filename */
2217
                                                        g_snprintf(filename, 255, "sip-%s-%s-%"SCNi64"-peer-audio",
2218
                                                                session->account.username ? session->account.username : "unknown",
2219
                                                                session->transaction ? session->transaction : "unknown",
2220
                                                                now);
2221 02eeeba4 Lorenzo Miniero
                                                        /* FIXME This only works if offer/answer happened */
2222
                                                        session->arc_peer = janus_recorder_create(NULL, session->media.audio_pt_name, filename);
2223 6089eb4e Lorenzo Miniero
                                                        if(session->arc_peer == NULL) {
2224
                                                                /* FIXME We should notify the fact the recorder could not be created */
2225
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an audio recording file for this peer!\n");
2226
                                                        }
2227
                                                }
2228
                                        }
2229
                                        if(record_peer_video) {
2230
                                                memset(filename, 0, 255);
2231
                                                if(recording_base) {
2232
                                                        /* Use the filename and path we have been provided */
2233 4f9e455c Lorenzo Miniero
                                                        g_snprintf(filename, 255, "%s-peer-video", recording_base);
2234 02eeeba4 Lorenzo Miniero
                                                        /* FIXME This only works if offer/answer happened */
2235
                                                        session->vrc_peer = janus_recorder_create(NULL, session->media.video_pt_name, filename);
2236 6089eb4e Lorenzo Miniero
                                                        if(session->vrc_peer == NULL) {
2237
                                                                /* FIXME We should notify the fact the recorder could not be created */
2238
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an video recording file for this peer!\n");
2239
                                                        }
2240
                                                } else {
2241
                                                        /* Build a filename */
2242
                                                        g_snprintf(filename, 255, "sip-%s-%s-%"SCNi64"-peer-video",
2243
                                                                session->account.username ? session->account.username : "unknown",
2244
                                                                session->transaction ? session->transaction : "unknown",
2245
                                                                now);
2246 02eeeba4 Lorenzo Miniero
                                                        /* FIXME This only works if offer/answer happened */
2247
                                                        session->vrc_peer = janus_recorder_create(NULL, session->media.video_pt_name, filename);
2248 6089eb4e Lorenzo Miniero
                                                        if(session->vrc_peer == NULL) {
2249
                                                                /* FIXME We should notify the fact the recorder could not be created */
2250
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an video recording file for this peer!\n");
2251
                                                        }
2252
                                                }
2253
                                                /* TODO We should send a FIR/PLI to this peer... */
2254
                                        }
2255
                                }
2256
                                if(record_audio || record_video) {
2257
                                        /* Start recording the user's audio and/or video */
2258
                                        JANUS_LOG(LOG_INFO, "Starting recording of user's %s (user %s, call %s)\n",
2259
                                                (record_audio && record_video ? "audio and video" : (record_audio ? "audio" : "video")),
2260
                                                session->account.username, session->transaction);
2261
                                        if(record_audio) {
2262
                                                memset(filename, 0, 255);
2263
                                                if(recording_base) {
2264
                                                        /* Use the filename and path we have been provided */
2265 4f9e455c Lorenzo Miniero
                                                        g_snprintf(filename, 255, "%s-user-audio", recording_base);
2266 02eeeba4 Lorenzo Miniero
                                                        /* FIXME This only works if offer/answer happened */
2267
                                                        session->arc = janus_recorder_create(NULL, session->media.audio_pt_name, filename);
2268 6089eb4e Lorenzo Miniero
                                                        if(session->arc == NULL) {
2269
                                                                /* FIXME We should notify the fact the recorder could not be created */
2270
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an audio recording file for this peer!\n");
2271
                                                        }
2272
                                                } else {
2273
                                                        /* Build a filename */
2274
                                                        g_snprintf(filename, 255, "sip-%s-%s-%"SCNi64"-own-audio",
2275
                                                                session->account.username ? session->account.username : "unknown",
2276
                                                                session->transaction ? session->transaction : "unknown",
2277
                                                                now);
2278 02eeeba4 Lorenzo Miniero
                                                        /* FIXME This only works if offer/answer happened */
2279
                                                        session->arc = janus_recorder_create(NULL, session->media.audio_pt_name, filename);
2280 6089eb4e Lorenzo Miniero
                                                        if(session->arc == NULL) {
2281
                                                                /* FIXME We should notify the fact the recorder could not be created */
2282
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an audio recording file for this peer!\n");
2283
                                                        }
2284
                                                }
2285
                                        }
2286
                                        if(record_video) {
2287
                                                memset(filename, 0, 255);
2288
                                                if(recording_base) {
2289
                                                        /* Use the filename and path we have been provided */
2290 4f9e455c Lorenzo Miniero
                                                        g_snprintf(filename, 255, "%s-user-video", recording_base);
2291 02eeeba4 Lorenzo Miniero
                                                        /* FIXME This only works if offer/answer happened */
2292
                                                        session->vrc = janus_recorder_create(NULL, session->media.video_pt_name, filename);
2293 6089eb4e Lorenzo Miniero
                                                        if(session->vrc == NULL) {
2294
                                                                /* FIXME We should notify the fact the recorder could not be created */
2295
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an video recording file for this user!\n");
2296
                                                        }
2297
                                                } else {
2298
                                                        /* Build a filename */
2299
                                                        g_snprintf(filename, 255, "sip-%s-%s-%"SCNi64"-own-video",
2300
                                                                session->account.username ? session->account.username : "unknown",
2301
                                                                session->transaction ? session->transaction : "unknown",
2302
                                                                now);
2303 02eeeba4 Lorenzo Miniero
                                                        /* FIXME This only works if offer/answer happened */
2304
                                                        session->vrc = janus_recorder_create(NULL, session->media.video_pt_name, filename);
2305 6089eb4e Lorenzo Miniero
                                                        if(session->vrc == NULL) {
2306
                                                                /* FIXME We should notify the fact the recorder could not be created */
2307
                                                                JANUS_LOG(LOG_ERR, "Couldn't open an video recording file for this user!\n");
2308
                                                        }
2309
                                                }
2310
                                                /* Send a PLI */
2311
                                                JANUS_LOG(LOG_VERB, "Recording video, sending a PLI to kickstart it\n");
2312
                                                char buf[12];
2313
                                                memset(buf, 0, 12);
2314
                                                janus_rtcp_pli((char *)&buf, 12);
2315
                                                gateway->relay_rtcp(session->handle, 1, buf, 12);
2316
                                        }
2317
                                }
2318
                        } else {
2319
                                /* Stop recording something: notice that this never returns an error, even when we were not recording anything */
2320
                                if(record_audio) {
2321
                                        if(session->arc) {
2322
                                                janus_recorder_close(session->arc);
2323
                                                JANUS_LOG(LOG_INFO, "Closed user's audio recording %s\n", session->arc->filename ? session->arc->filename : "??");
2324
                                                janus_recorder_free(session->arc);
2325
                                        }
2326
                                        session->arc = NULL;
2327
                                }
2328
                                if(record_video) {
2329
                                        if(session->vrc) {
2330
                                                janus_recorder_close(session->vrc);
2331
                                                JANUS_LOG(LOG_INFO, "Closed user's video recording %s\n", session->vrc->filename ? session->vrc->filename : "??");
2332
                                                janus_recorder_free(session->vrc);
2333
                                        }
2334
                                        session->vrc = NULL;
2335
                                }
2336
                                if(record_peer_audio) {
2337
                                        if(session->arc_peer) {
2338
                                                janus_recorder_close(session->arc_peer);
2339
                                                JANUS_LOG(LOG_INFO, "Closed peer's audio recording %s\n", session->arc_peer->filename ? session->arc_peer->filename : "??");
2340
                                                janus_recorder_free(session->arc_peer);
2341
                                        }
2342
                                        session->arc_peer = NULL;
2343
                                }
2344
                                if(record_peer_video) {
2345
                                        if(session->vrc_peer) {
2346
                                                janus_recorder_close(session->vrc_peer);
2347
                                                JANUS_LOG(LOG_INFO, "Closed peer's video recording %s\n", session->vrc_peer->filename ? session->vrc_peer->filename : "??");
2348
                                                janus_recorder_free(session->vrc_peer);
2349
                                        }
2350
                                        session->vrc_peer = NULL;
2351
                                }
2352
                        }
2353 d223cef1 Lorenzo Miniero
                        janus_mutex_unlock(&session->rec_mutex);
2354 6089eb4e Lorenzo Miniero
                        /* Notify the result */
2355
                        result = json_object();
2356
                        json_object_set_new(result, "event", json_string("recordingupdated"));
2357 e4ced382 Filip Jenicek
                } else if(!strcasecmp(request_text, "dtmf_info")) {
2358 77083ea4 Filip Jenicek
                        /* Send DMTF tones using SIP INFO
2359
                         * (https://tools.ietf.org/html/draft-kaplan-dispatch-info-dtmf-package-00)
2360
                         */
2361
                        if(!(session->status == janus_sip_call_status_inviting || session->status == janus_sip_call_status_incall)) {
2362
                                JANUS_LOG(LOG_ERR, "Wrong state (not in a call? status=%s)\n", janus_sip_call_status_string(session->status));
2363
                                g_snprintf(error_cause, 512, "Wrong state (not in a call?)");
2364
                                goto error;
2365
                        }
2366
                        if(session->callee == NULL) {
2367
                                JANUS_LOG(LOG_ERR, "Wrong state (no callee?)\n");
2368
                                error_code = JANUS_SIP_ERROR_WRONG_STATE;
2369
                                g_snprintf(error_cause, 512, "Wrong state (no callee?)");
2370
                                goto error;
2371
                        }
2372 94926fcd Andreas Girgensohn
                        JANUS_VALIDATE_JSON_OBJECT(root, dtmf_info_parameters,
2373
                                error_code, error_cause, TRUE,
2374
                                JANUS_SIP_ERROR_MISSING_ELEMENT, JANUS_SIP_ERROR_INVALID_ELEMENT);
2375
                        if(error_code != 0)
2376 77083ea4 Filip Jenicek
                                goto error;
2377 94926fcd Andreas Girgensohn
                        json_t *digit = json_object_get(root, "digit");
2378 77083ea4 Filip Jenicek
                        const char *digit_text = json_string_value(digit);
2379
                        if(strlen(digit_text) != 1) {
2380
                                JANUS_LOG(LOG_ERR, "Invalid element (digit should be one character))\n");
2381
                                error_code = JANUS_SIP_ERROR_INVALID_ELEMENT;
2382
                                g_snprintf(error_cause, 512, "Invalid element (digit should be one character)");
2383
                                goto error;
2384
                        }
2385 e4ced382 Filip Jenicek
                        int duration_ms = 0;
2386
                        json_t *duration = json_object_get(root, "duration");
2387 976bec15 Lorenzo Miniero
                        duration_ms = duration ? json_integer_value(duration) : 0;
2388 e4ced382 Filip Jenicek
                        if (duration_ms <= 0 || duration_ms > 5000) {
2389
                                duration_ms = 160; /* default value */
2390
                        }
2391 77083ea4 Filip Jenicek
2392
                        char payload[64];
2393 e4ced382 Filip Jenicek
                        g_snprintf(payload, sizeof(payload), "Signal=%s\r\nDuration=%d", digit_text, duration_ms);
2394 77083ea4 Filip Jenicek
                        nua_info(session->stack->s_nh_i,
2395
                                SIPTAG_CONTENT_TYPE_STR("application/dtmf-relay"),
2396
                                SIPTAG_PAYLOAD_STR(payload),
2397
                                TAG_END());
2398 be35facb meetecho
                } else {
2399 3a26e009 meetecho
                        JANUS_LOG(LOG_ERR, "Unknown request (%s)\n", request_text);
2400 3cc3cab3 meetecho
                        error_code = JANUS_SIP_ERROR_INVALID_REQUEST;
2401 c94052c2 meetecho
                        g_snprintf(error_cause, 512, "Unknown request (%s)", request_text);
2402 be35facb meetecho
                        goto error;
2403
                }
2404
2405
                /* Prepare JSON event */
2406
                json_t *event = json_object();
2407 3a26e009 meetecho
                json_object_set_new(event, "sip", json_string("event"));
2408 be35facb meetecho
                if(result != NULL)
2409 5c9efb24 meetecho
                        json_object_set_new(event, "result", result);
2410 dd11fa0a Lorenzo Miniero
                int ret = gateway->push_event(msg->handle, &janus_sip_plugin, msg->transaction, event, NULL);
2411
                JANUS_LOG(LOG_VERB, "  >> Pushing event: %d (%s)\n", ret, janus_get_api_error(ret));
2412 be35facb meetecho
                json_decref(event);
2413 3a26e009 meetecho
                janus_sip_message_free(msg);
2414 be35facb meetecho
                continue;
2415 eeabd833 Saúl Ibarra Corretgé
2416 be35facb meetecho
error:
2417
                {
2418
                        /* Prepare JSON error event */
2419
                        json_t *event = json_object();
2420 3a26e009 meetecho
                        json_object_set_new(event, "sip", json_string("event"));
2421 3cc3cab3 meetecho
                        json_object_set_new(event, "error_code", json_integer(error_code));
2422 3a26e009 meetecho
                        json_object_set_new(event, "error", json_string(error_cause));
2423 dd11fa0a Lorenzo Miniero
                        int ret = gateway->push_event(msg->handle, &janus_sip_plugin, msg->transaction, event, NULL);
2424
                        JANUS_LOG(LOG_VERB, "  >> Pushing event: %d (%s)\n", ret, janus_get_api_error(ret));
2425 be35facb meetecho
                        json_decref(event);
2426 3a26e009 meetecho
                        janus_sip_message_free(msg);
2427 be35facb meetecho
                }
2428
        }
2429 febef1ea meetecho
        JANUS_LOG(LOG_VERB, "Leaving SIP handler thread\n");
2430 be35facb meetecho
        return NULL;
2431
}
2432
2433
2434
/* Sofia callbacks */
2435
void janus_sip_sofia_callback(nua_event_t event, int status, char const *phrase, nua_t *nua, nua_magic_t *magic, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tags[])
2436
{
2437
        janus_sip_session *session = (janus_sip_session *)magic;
2438
        ssip_t *ssip = session->stack;
2439 a1557c3f Lorenzo Miniero
2440
        /* Notify event handlers about the content of the whole incoming SIP message, if any */
2441
        if(gateway->events_is_enabled() && ssip) {
2442
                /* Print the incoming message */
2443
                size_t msg_size = 0;
2444
                msg_t* msg = nua_current_request(nua);
2445
                if(msg) {
2446
                        char *msg_str = msg_as_string(ssip->s_home, msg, NULL, 0, &msg_size);
2447
                        json_t *info = json_object();
2448
                        json_object_set_new(info, "event", json_string("sip-in"));
2449
                        json_object_set_new(info, "sip", json_string(msg_str));
2450 c734a91a Lorenzo Miniero
                        gateway->notify_event(&janus_sip_plugin, session->handle, info);
2451 a1557c3f Lorenzo Miniero
                }
2452
        }
2453
2454 ee73d1e6 meetecho
        switch (event) {
2455 be35facb meetecho
        /* Status or Error Indications */
2456
                case nua_i_active:
2457 577e3939 Lorenzo Miniero
                        JANUS_LOG(LOG_VERB, "[%s][%s]: %d %s\n", session->account.username, nua_event_name(event), status, phrase ? phrase : "??");
2458 be35facb meetecho
                        break;
2459
                case nua_i_error:
2460