ad74b574e0bce7d1a553042256b23142cc75a754
[asterisk/asterisk.git] / channels / chan_pjsip.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2013, Digium, Inc.
5  *
6  * Joshua Colp <jcolp@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \author Joshua Colp <jcolp@digium.com>
22  *
23  * \brief PSJIP SIP Channel Driver
24  *
25  * \ingroup channel_drivers
26  */
27
28 /*** MODULEINFO
29         <depend>pjproject</depend>
30         <depend>res_pjsip</depend>
31         <depend>res_pjsip_session</depend>
32         <support_level>core</support_level>
33  ***/
34
35 #include "asterisk.h"
36
37 #include <pjsip.h>
38 #include <pjsip_ua.h>
39 #include <pjlib.h>
40
41 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
42
43 #include "asterisk/lock.h"
44 #include "asterisk/channel.h"
45 #include "asterisk/module.h"
46 #include "asterisk/pbx.h"
47 #include "asterisk/rtp_engine.h"
48 #include "asterisk/acl.h"
49 #include "asterisk/callerid.h"
50 #include "asterisk/file.h"
51 #include "asterisk/cli.h"
52 #include "asterisk/app.h"
53 #include "asterisk/musiconhold.h"
54 #include "asterisk/causes.h"
55 #include "asterisk/taskprocessor.h"
56 #include "asterisk/dsp.h"
57 #include "asterisk/stasis_endpoints.h"
58 #include "asterisk/stasis_channels.h"
59 #include "asterisk/indications.h"
60
61 #include "asterisk/res_pjsip.h"
62 #include "asterisk/res_pjsip_session.h"
63
64 /*** DOCUMENTATION
65         <function name="PJSIP_DIAL_CONTACTS" language="en_US">
66                 <synopsis>
67                         Return a dial string for dialing all contacts on an AOR.
68                 </synopsis>
69                 <syntax>
70                         <parameter name="endpoint" required="true">
71                                 <para>Name of the endpoint</para>
72                         </parameter>
73                         <parameter name="aor" required="false">
74                                 <para>Name of an AOR to use, if not specified the configured AORs on the endpoint are used</para>
75                         </parameter>
76                         <parameter name="request_user" required="false">
77                                 <para>Optional request user to use in the request URI</para>
78                         </parameter>
79                 </syntax>
80                 <description>
81                         <para>Returns a properly formatted dial string for dialing all contacts on an AOR.</para>
82                 </description>
83         </function>
84         <function name="PJSIP_MEDIA_OFFER" language="en_US">
85                 <synopsis>
86                         Media and codec offerings to be set on an outbound SIP channel prior to dialing.
87                 </synopsis>
88                 <syntax>
89                         <parameter name="media" required="true">
90                                 <para>types of media offered</para>
91                         </parameter>
92                 </syntax>
93                 <description>
94                         <para>Returns the codecs offered based upon the media choice</para>
95                 </description>
96         </function>
97  ***/
98
99 static const char desc[] = "PJSIP Channel";
100 static const char channel_type[] = "PJSIP";
101
102 static unsigned int chan_idx;
103
104 /*!
105  * \brief Positions of various media
106  */
107 enum sip_session_media_position {
108         /*! \brief First is audio */
109         SIP_MEDIA_AUDIO = 0,
110         /*! \brief Second is video */
111         SIP_MEDIA_VIDEO,
112         /*! \brief Last is the size for media details */
113         SIP_MEDIA_SIZE,
114 };
115
116 struct chan_pjsip_pvt {
117         struct ast_sip_session_media *media[SIP_MEDIA_SIZE];
118 };
119
120 static void chan_pjsip_pvt_dtor(void *obj)
121 {
122         struct chan_pjsip_pvt *pvt = obj;
123         int i;
124
125         for (i = 0; i < SIP_MEDIA_SIZE; ++i) {
126                 ao2_cleanup(pvt->media[i]);
127                 pvt->media[i] = NULL;
128         }
129 }
130
131 /* \brief Asterisk core interaction functions */
132 static struct ast_channel *chan_pjsip_request(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, const char *data, int *cause);
133 static int chan_pjsip_sendtext(struct ast_channel *ast, const char *text);
134 static int chan_pjsip_digit_begin(struct ast_channel *ast, char digit);
135 static int chan_pjsip_digit_end(struct ast_channel *ast, char digit, unsigned int duration);
136 static int chan_pjsip_call(struct ast_channel *ast, const char *dest, int timeout);
137 static int chan_pjsip_hangup(struct ast_channel *ast);
138 static int chan_pjsip_answer(struct ast_channel *ast);
139 static struct ast_frame *chan_pjsip_read(struct ast_channel *ast);
140 static int chan_pjsip_write(struct ast_channel *ast, struct ast_frame *f);
141 static int chan_pjsip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
142 static int chan_pjsip_transfer(struct ast_channel *ast, const char *target);
143 static int chan_pjsip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
144 static int chan_pjsip_devicestate(const char *data);
145 static int chan_pjsip_queryoption(struct ast_channel *ast, int option, void *data, int *datalen);
146
147 /*! \brief PBX interface structure for channel registration */
148 static struct ast_channel_tech chan_pjsip_tech = {
149         .type = channel_type,
150         .description = "PJSIP Channel Driver",
151         .requester = chan_pjsip_request,
152         .send_text = chan_pjsip_sendtext,
153         .send_digit_begin = chan_pjsip_digit_begin,
154         .send_digit_end = chan_pjsip_digit_end,
155         .call = chan_pjsip_call,
156         .hangup = chan_pjsip_hangup,
157         .answer = chan_pjsip_answer,
158         .read = chan_pjsip_read,
159         .write = chan_pjsip_write,
160         .write_video = chan_pjsip_write,
161         .exception = chan_pjsip_read,
162         .indicate = chan_pjsip_indicate,
163         .transfer = chan_pjsip_transfer,
164         .fixup = chan_pjsip_fixup,
165         .devicestate = chan_pjsip_devicestate,
166         .queryoption = chan_pjsip_queryoption,
167         .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER
168 };
169
170 /*! \brief SIP session interaction functions */
171 static void chan_pjsip_session_begin(struct ast_sip_session *session);
172 static void chan_pjsip_session_end(struct ast_sip_session *session);
173 static int chan_pjsip_incoming_request(struct ast_sip_session *session, struct pjsip_rx_data *rdata);
174 static void chan_pjsip_incoming_response(struct ast_sip_session *session, struct pjsip_rx_data *rdata);
175
176 /*! \brief SIP session supplement structure */
177 static struct ast_sip_session_supplement chan_pjsip_supplement = {
178         .method = "INVITE",
179         .priority = AST_SIP_SESSION_SUPPLEMENT_PRIORITY_CHANNEL,
180         .session_begin = chan_pjsip_session_begin,
181         .session_end = chan_pjsip_session_end,
182         .incoming_request = chan_pjsip_incoming_request,
183         .incoming_response = chan_pjsip_incoming_response,
184 };
185
186 static int chan_pjsip_incoming_ack(struct ast_sip_session *session, struct pjsip_rx_data *rdata);
187
188 static struct ast_sip_session_supplement chan_pjsip_ack_supplement = {
189         .method = "ACK",
190         .priority = AST_SIP_SESSION_SUPPLEMENT_PRIORITY_CHANNEL,
191         .incoming_request = chan_pjsip_incoming_ack,
192 };
193
194 /*! \brief Dialplan function for constructing a dial string for calling all contacts */
195 static int chan_pjsip_dial_contacts(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
196 {
197         RAII_VAR(struct ast_sip_endpoint *, endpoint, NULL, ao2_cleanup);
198         RAII_VAR(struct ast_str *, dial, NULL, ast_free_ptr);
199         const char *aor_name;
200         char *rest;
201
202         AST_DECLARE_APP_ARGS(args,
203                 AST_APP_ARG(endpoint_name);
204                 AST_APP_ARG(aor_name);
205                 AST_APP_ARG(request_user);
206         );
207
208         AST_STANDARD_APP_ARGS(args, data);
209
210         if (ast_strlen_zero(args.endpoint_name)) {
211                 ast_log(LOG_WARNING, "An endpoint name must be specified when using the '%s' dialplan function\n", cmd);
212                 return -1;
213         } else if (!(endpoint = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint", args.endpoint_name))) {
214                 ast_log(LOG_WARNING, "Specified endpoint '%s' was not found\n", args.endpoint_name);
215                 return -1;
216         }
217
218         aor_name = S_OR(args.aor_name, endpoint->aors);
219
220         if (ast_strlen_zero(aor_name)) {
221                 ast_log(LOG_WARNING, "No AOR has been provided and no AORs are configured on endpoint '%s'\n", args.endpoint_name);
222                 return -1;
223         } else if (!(dial = ast_str_create(len))) {
224                 ast_log(LOG_WARNING, "Could not get enough buffer space for dialing contacts\n");
225                 return -1;
226         } else if (!(rest = ast_strdupa(aor_name))) {
227                 ast_log(LOG_WARNING, "Could not duplicate provided AORs\n");
228                 return -1;
229         }
230
231         while ((aor_name = strsep(&rest, ","))) {
232                 RAII_VAR(struct ast_sip_aor *, aor, ast_sip_location_retrieve_aor(aor_name), ao2_cleanup);
233                 RAII_VAR(struct ao2_container *, contacts, NULL, ao2_cleanup);
234                 struct ao2_iterator it_contacts;
235                 struct ast_sip_contact *contact;
236
237                 if (!aor) {
238                         /* If the AOR provided is not found skip it, there may be more */
239                         continue;
240                 } else if (!(contacts = ast_sip_location_retrieve_aor_contacts(aor))) {
241                         /* No contacts are available, skip it as well */
242                         continue;
243                 } else if (!ao2_container_count(contacts)) {
244                         /* We were given a container but no contacts are in it... */
245                         continue;
246                 }
247
248                 it_contacts = ao2_iterator_init(contacts, 0);
249                 for (; (contact = ao2_iterator_next(&it_contacts)); ao2_ref(contact, -1)) {
250                         ast_str_append(&dial, -1, "PJSIP/");
251
252                         if (!ast_strlen_zero(args.request_user)) {
253                                 ast_str_append(&dial, -1, "%s@", args.request_user);
254                         }
255                         ast_str_append(&dial, -1, "%s/%s&", args.endpoint_name, contact->uri);
256                 }
257                 ao2_iterator_destroy(&it_contacts);
258         }
259
260         /* Trim the '&' at the end off */
261         ast_str_truncate(dial, ast_str_strlen(dial) - 1);
262
263         ast_copy_string(buf, ast_str_buffer(dial), len);
264
265         return 0;
266 }
267
268 static struct ast_custom_function chan_pjsip_dial_contacts_function = {
269         .name = "PJSIP_DIAL_CONTACTS",
270         .read = chan_pjsip_dial_contacts,
271 };
272
273 static int media_offer_read_av(struct ast_sip_session *session, char *buf,
274                                size_t len, enum ast_format_type media_type)
275 {
276         int i, size = 0;
277         struct ast_format fmt;
278         const char *name;
279
280         for (i = 0; ast_codec_pref_index(&session->override_prefs, i, &fmt); ++i) {
281                 if (AST_FORMAT_GET_TYPE(fmt.id) != media_type) {
282                         continue;
283                 }
284
285                 name = ast_getformatname(&fmt);
286
287                 if (ast_strlen_zero(name)) {
288                         ast_log(LOG_WARNING, "PJSIP_MEDIA_OFFER unrecognized format %s\n", name);
289                         continue;
290                 }
291
292                 /* add one since we'll include a comma */
293                 size = strlen(name) + 1;
294                 len -= size;
295                 if ((len) < 0) {
296                         break;
297                 }
298
299                 /* no reason to use strncat here since we have already ensured buf has
300                    enough space, so strcat can be safely used */
301                 strcat(buf, name);
302                 strcat(buf, ",");
303         }
304
305         if (size) {
306                 /* remove the extra comma */
307                 buf[strlen(buf) - 1] = '\0';
308         }
309         return 0;
310 }
311
312 struct media_offer_data {
313         struct ast_sip_session *session;
314         enum ast_format_type media_type;
315         const char *value;
316 };
317
318 static int media_offer_write_av(void *obj)
319 {
320         struct media_offer_data *data = obj;
321         int i;
322         struct ast_format fmt;
323         /* remove all of the given media type first */
324         for (i = 0; ast_codec_pref_index(&data->session->override_prefs, i, &fmt); ++i) {
325                 if (AST_FORMAT_GET_TYPE(fmt.id) == data->media_type) {
326                         ast_codec_pref_remove(&data->session->override_prefs, &fmt);
327                 }
328         }
329         ast_format_cap_remove_bytype(data->session->req_caps, data->media_type);
330         ast_parse_allow_disallow(&data->session->override_prefs, data->session->req_caps, data->value, 1);
331
332         return 0;
333 }
334
335 static int media_offer_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
336 {
337         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
338
339         if (!strcmp(data, "audio")) {
340                 return media_offer_read_av(channel->session, buf, len, AST_FORMAT_TYPE_AUDIO);
341         } else if (!strcmp(data, "video")) {
342                 return media_offer_read_av(channel->session, buf, len, AST_FORMAT_TYPE_VIDEO);
343         }
344
345         return 0;
346 }
347
348 static int media_offer_write(struct ast_channel *chan, const char *cmd, char *data, const char *value)
349 {
350         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
351
352         struct media_offer_data mdata = {
353                 .session = channel->session,
354                 .value = value
355         };
356
357         if (!strcmp(data, "audio")) {
358                 mdata.media_type = AST_FORMAT_TYPE_AUDIO;
359         } else if (!strcmp(data, "video")) {
360                 mdata.media_type = AST_FORMAT_TYPE_VIDEO;
361         }
362
363         return ast_sip_push_task_synchronous(channel->session->serializer, media_offer_write_av, &mdata);
364 }
365
366 static struct ast_custom_function media_offer_function = {
367         .name = "PJSIP_MEDIA_OFFER",
368         .read = media_offer_read,
369         .write = media_offer_write
370 };
371
372 /*! \brief Function called by RTP engine to get local audio RTP peer */
373 static enum ast_rtp_glue_result chan_pjsip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
374 {
375         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
376         struct chan_pjsip_pvt *pvt = channel->pvt;
377         struct ast_sip_endpoint *endpoint;
378
379         if (!pvt || !channel->session || !pvt->media[SIP_MEDIA_AUDIO]->rtp) {
380                 return AST_RTP_GLUE_RESULT_FORBID;
381         }
382
383         endpoint = channel->session->endpoint;
384
385         *instance = pvt->media[SIP_MEDIA_AUDIO]->rtp;
386         ao2_ref(*instance, +1);
387
388         ast_assert(endpoint != NULL);
389         if (endpoint->media.rtp.encryption != AST_SIP_MEDIA_ENCRYPT_NONE) {
390                 return AST_RTP_GLUE_RESULT_FORBID;
391         }
392
393         if (endpoint->media.direct_media.enabled) {
394                 return AST_RTP_GLUE_RESULT_REMOTE;
395         }
396
397         return AST_RTP_GLUE_RESULT_LOCAL;
398 }
399
400 /*! \brief Function called by RTP engine to get local video RTP peer */
401 static enum ast_rtp_glue_result chan_pjsip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
402 {
403         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
404         struct chan_pjsip_pvt *pvt = channel->pvt;
405         struct ast_sip_endpoint *endpoint;
406
407         if (!pvt || !channel->session || !pvt->media[SIP_MEDIA_VIDEO]->rtp) {
408                 return AST_RTP_GLUE_RESULT_FORBID;
409         }
410
411         endpoint = channel->session->endpoint;
412
413         *instance = pvt->media[SIP_MEDIA_VIDEO]->rtp;
414         ao2_ref(*instance, +1);
415
416         ast_assert(endpoint != NULL);
417         if (endpoint->media.rtp.encryption != AST_SIP_MEDIA_ENCRYPT_NONE) {
418                 return AST_RTP_GLUE_RESULT_FORBID;
419         }
420
421         return AST_RTP_GLUE_RESULT_LOCAL;
422 }
423
424 /*! \brief Function called by RTP engine to get peer capabilities */
425 static void chan_pjsip_get_codec(struct ast_channel *chan, struct ast_format_cap *result)
426 {
427         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
428
429         ast_format_cap_copy(result, channel->session->endpoint->media.codecs);
430 }
431
432 static int send_direct_media_request(void *data)
433 {
434         RAII_VAR(struct ast_sip_session *, session, data, ao2_cleanup);
435
436         return ast_sip_session_refresh(session, NULL, NULL, NULL,
437                         session->endpoint->media.direct_media.method, 1);
438 }
439
440 static struct ast_datastore_info direct_media_mitigation_info = { };
441
442 static int direct_media_mitigate_glare(struct ast_sip_session *session)
443 {
444         RAII_VAR(struct ast_datastore *, datastore, NULL, ao2_cleanup);
445
446         if (session->endpoint->media.direct_media.glare_mitigation ==
447                         AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_NONE) {
448                 return 0;
449         }
450
451         datastore = ast_sip_session_get_datastore(session, "direct_media_glare_mitigation");
452         if (!datastore) {
453                 return 0;
454         }
455
456         /* Removing the datastore ensures we won't try to mitigate glare on subsequent reinvites */
457         ast_sip_session_remove_datastore(session, "direct_media_glare_mitigation");
458
459         if ((session->endpoint->media.direct_media.glare_mitigation ==
460                         AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_OUTGOING &&
461                         session->inv_session->role == PJSIP_ROLE_UAC) ||
462                         (session->endpoint->media.direct_media.glare_mitigation ==
463                         AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_INCOMING &&
464                         session->inv_session->role == PJSIP_ROLE_UAS)) {
465                 return 1;
466         }
467
468         return 0;
469 }
470
471 static int check_for_rtp_changes(struct ast_channel *chan, struct ast_rtp_instance *rtp,
472                 struct ast_sip_session_media *media, int rtcp_fd)
473 {
474         int changed = 0;
475
476         if (rtp) {
477                 changed = ast_rtp_instance_get_and_cmp_remote_address(rtp, &media->direct_media_addr);
478                 if (media->rtp) {
479                         ast_channel_set_fd(chan, rtcp_fd, -1);
480                         ast_rtp_instance_set_prop(media->rtp, AST_RTP_PROPERTY_RTCP, 0);
481                 }
482         } else if (!ast_sockaddr_isnull(&media->direct_media_addr)){
483                 ast_sockaddr_setnull(&media->direct_media_addr);
484                 changed = 1;
485                 if (media->rtp) {
486                         ast_rtp_instance_set_prop(media->rtp, AST_RTP_PROPERTY_RTCP, 1);
487                         ast_channel_set_fd(chan, rtcp_fd, ast_rtp_instance_fd(media->rtp, 1));
488                 }
489         }
490
491         return changed;
492 }
493
494 /*! \brief Function called by RTP engine to change where the remote party should send media */
495 static int chan_pjsip_set_rtp_peer(struct ast_channel *chan,
496                 struct ast_rtp_instance *rtp,
497                 struct ast_rtp_instance *vrtp,
498                 struct ast_rtp_instance *tpeer,
499                 const struct ast_format_cap *cap,
500                 int nat_active)
501 {
502         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
503         struct chan_pjsip_pvt *pvt = channel->pvt;
504         struct ast_sip_session *session = channel->session;
505         int changed = 0;
506         struct ast_channel *bridge_peer;
507
508         /* Don't try to do any direct media shenanigans on early bridges */
509         bridge_peer = ast_channel_bridge_peer(chan);
510         if ((rtp || vrtp || tpeer) && !bridge_peer) {
511                 return 0;
512         }
513         ast_channel_cleanup(bridge_peer);
514
515         if (nat_active && session->endpoint->media.direct_media.disable_on_nat) {
516                 return 0;
517         }
518
519         if (pvt->media[SIP_MEDIA_AUDIO]) {
520                 changed |= check_for_rtp_changes(chan, rtp, pvt->media[SIP_MEDIA_AUDIO], 1);
521         }
522         if (pvt->media[SIP_MEDIA_VIDEO]) {
523                 changed |= check_for_rtp_changes(chan, vrtp, pvt->media[SIP_MEDIA_VIDEO], 3);
524         }
525
526         if (direct_media_mitigate_glare(session)) {
527                 return 0;
528         }
529
530         if (cap && !ast_format_cap_is_empty(cap) && !ast_format_cap_identical(session->direct_media_cap, cap)) {
531                 ast_format_cap_copy(session->direct_media_cap, cap);
532                 changed = 1;
533         }
534
535         if (changed) {
536                 ao2_ref(session, +1);
537
538
539                 if (ast_sip_push_task(session->serializer, send_direct_media_request, session)) {
540                         ao2_cleanup(session);
541                 }
542         }
543
544         return 0;
545 }
546
547 /*! \brief Local glue for interacting with the RTP engine core */
548 static struct ast_rtp_glue chan_pjsip_rtp_glue = {
549         .type = "PJSIP",
550         .get_rtp_info = chan_pjsip_get_rtp_peer,
551         .get_vrtp_info = chan_pjsip_get_vrtp_peer,
552         .get_codec = chan_pjsip_get_codec,
553         .update_peer = chan_pjsip_set_rtp_peer,
554 };
555
556 /*! \brief Function called to create a new PJSIP Asterisk channel */
557 static struct ast_channel *chan_pjsip_new(struct ast_sip_session *session, int state, const char *exten, const char *title, const char *linkedid, const char *cid_name)
558 {
559         struct ast_channel *chan;
560         struct ast_format fmt;
561         RAII_VAR(struct chan_pjsip_pvt *, pvt, NULL, ao2_cleanup);
562         struct ast_sip_channel_pvt *channel;
563
564         if (!(pvt = ao2_alloc(sizeof(*pvt), chan_pjsip_pvt_dtor))) {
565                 return NULL;
566         }
567
568         if (!(chan = ast_channel_alloc(1, state, S_OR(session->id.number.str, ""), S_OR(session->id.name.str, ""), "", "", "", linkedid, 0, "PJSIP/%s-%08x", ast_sorcery_object_get_id(session->endpoint),
569                 ast_atomic_fetchadd_int((int *)&chan_idx, +1)))) {
570                 return NULL;
571         }
572
573         ast_channel_tech_set(chan, &chan_pjsip_tech);
574
575         if (!(channel = ast_sip_channel_pvt_alloc(pvt, session))) {
576                 ast_hangup(chan);
577                 return NULL;
578         }
579
580         ast_channel_stage_snapshot(chan);
581
582         /* If res_pjsip_session is ever updated to create/destroy ast_sip_session_media
583          * during a call such as if multiple same-type stream support is introduced,
584          * these will need to be recaptured as well */
585         pvt->media[SIP_MEDIA_AUDIO] = ao2_find(session->media, "audio", OBJ_KEY);
586         pvt->media[SIP_MEDIA_VIDEO] = ao2_find(session->media, "video", OBJ_KEY);
587         ast_channel_tech_pvt_set(chan, channel);
588         if (pvt->media[SIP_MEDIA_AUDIO] && pvt->media[SIP_MEDIA_AUDIO]->rtp) {
589                 ast_rtp_instance_set_channel_id(pvt->media[SIP_MEDIA_AUDIO]->rtp, ast_channel_uniqueid(chan));
590         }
591         if (pvt->media[SIP_MEDIA_VIDEO] && pvt->media[SIP_MEDIA_VIDEO]->rtp) {
592                 ast_rtp_instance_set_channel_id(pvt->media[SIP_MEDIA_VIDEO]->rtp, ast_channel_uniqueid(chan));
593         }
594
595         if (ast_format_cap_is_empty(session->req_caps) || !ast_format_cap_has_joint(session->req_caps, session->endpoint->media.codecs)) {
596                 ast_format_cap_copy(ast_channel_nativeformats(chan), session->endpoint->media.codecs);
597         } else {
598                 ast_format_cap_copy(ast_channel_nativeformats(chan), session->req_caps);
599         }
600
601         ast_codec_choose(&session->endpoint->media.prefs, ast_channel_nativeformats(chan), 1, &fmt);
602         ast_format_copy(ast_channel_writeformat(chan), &fmt);
603         ast_format_copy(ast_channel_rawwriteformat(chan), &fmt);
604         ast_format_copy(ast_channel_readformat(chan), &fmt);
605         ast_format_copy(ast_channel_rawreadformat(chan), &fmt);
606
607         if (state == AST_STATE_RING) {
608                 ast_channel_rings_set(chan, 1);
609         }
610
611         ast_channel_adsicpe_set(chan, AST_ADSI_UNAVAILABLE);
612
613         ast_channel_context_set(chan, session->endpoint->context);
614         ast_channel_exten_set(chan, S_OR(exten, "s"));
615         ast_channel_priority_set(chan, 1);
616
617         ast_channel_callgroup_set(chan, session->endpoint->pickup.callgroup);
618         ast_channel_pickupgroup_set(chan, session->endpoint->pickup.pickupgroup);
619
620         ast_channel_named_callgroups_set(chan, session->endpoint->pickup.named_callgroups);
621         ast_channel_named_pickupgroups_set(chan, session->endpoint->pickup.named_pickupgroups);
622
623         if (!ast_strlen_zero(session->endpoint->language)) {
624                 ast_channel_language_set(chan, session->endpoint->language);
625         }
626
627         if (!ast_strlen_zero(session->endpoint->zone)) {
628                 struct ast_tone_zone *zone = ast_get_indication_zone(session->endpoint->zone);
629                 if (!zone) {
630                         ast_log(LOG_ERROR, "Unknown country code '%s' for tonezone. Check indications.conf for available country codes.\n", session->endpoint->zone);
631                 }
632                 ast_channel_zone_set(chan, zone);
633         }
634
635         ast_endpoint_add_channel(session->endpoint->persistent, chan);
636
637         ast_channel_stage_snapshot_done(chan);
638
639         return chan;
640 }
641
642 static int answer(void *data)
643 {
644         pj_status_t status = PJ_SUCCESS;
645         pjsip_tx_data *packet;
646         struct ast_sip_session *session = data;
647
648         pjsip_dlg_inc_lock(session->inv_session->dlg);
649         if (session->inv_session->invite_tsx) {
650                 status = pjsip_inv_answer(session->inv_session, 200, NULL, NULL, &packet);
651         }
652         pjsip_dlg_dec_lock(session->inv_session->dlg);
653
654         if (status == PJ_SUCCESS && packet) {
655                 ast_sip_session_send_response(session, packet);
656         }
657
658         ao2_ref(session, -1);
659
660         return (status == PJ_SUCCESS) ? 0 : -1;
661 }
662
663 /*! \brief Function called by core when we should answer a PJSIP session */
664 static int chan_pjsip_answer(struct ast_channel *ast)
665 {
666         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
667
668         if (ast_channel_state(ast) == AST_STATE_UP) {
669                 return 0;
670         }
671
672         ast_setstate(ast, AST_STATE_UP);
673
674         ao2_ref(channel->session, +1);
675         if (ast_sip_push_task(channel->session->serializer, answer, channel->session)) {
676                 ast_log(LOG_WARNING, "Unable to push answer task to the threadpool. Cannot answer call\n");
677                 ao2_cleanup(channel->session);
678                 return -1;
679         }
680
681         return 0;
682 }
683
684 /*! \brief Internal helper function called when CNG tone is detected */
685 static struct ast_frame *chan_pjsip_cng_tone_detected(struct ast_sip_session *session, struct ast_frame *f)
686 {
687         const char *target_context;
688         int exists;
689
690         /* If we only needed this DSP for fax detection purposes we can just drop it now */
691         if (session->endpoint->dtmf == AST_SIP_DTMF_INBAND) {
692                 ast_dsp_set_features(session->dsp, DSP_FEATURE_DIGIT_DETECT);
693         } else {
694                 ast_dsp_free(session->dsp);
695                 session->dsp = NULL;
696         }
697
698         /* If already executing in the fax extension don't do anything */
699         if (!strcmp(ast_channel_exten(session->channel), "fax")) {
700                 return f;
701         }
702
703         target_context = S_OR(ast_channel_macrocontext(session->channel), ast_channel_context(session->channel));
704
705         /* We need to unlock the channel here because ast_exists_extension has the
706          * potential to start and stop an autoservice on the channel. Such action
707          * is prone to deadlock if the channel is locked.
708          */
709         ast_channel_unlock(session->channel);
710         exists = ast_exists_extension(session->channel, target_context, "fax", 1,
711                 S_COR(ast_channel_caller(session->channel)->id.number.valid,
712                         ast_channel_caller(session->channel)->id.number.str, NULL));
713         ast_channel_lock(session->channel);
714
715         if (exists) {
716                 ast_verb(2, "Redirecting '%s' to fax extension due to CNG detection\n",
717                         ast_channel_name(session->channel));
718                 pbx_builtin_setvar_helper(session->channel, "FAXEXTEN", ast_channel_exten(session->channel));
719                 if (ast_async_goto(session->channel, target_context, "fax", 1)) {
720                         ast_log(LOG_ERROR, "Failed to async goto '%s' into fax extension in '%s'\n",
721                                 ast_channel_name(session->channel), target_context);
722                 }
723                 ast_frfree(f);
724                 f = &ast_null_frame;
725         } else {
726                 ast_log(LOG_NOTICE, "FAX CNG detected on '%s' but no fax extension in '%s'\n",
727                         ast_channel_name(session->channel), target_context);
728         }
729
730         return f;
731 }
732
733 /*! \brief Function called by core to read any waiting frames */
734 static struct ast_frame *chan_pjsip_read(struct ast_channel *ast)
735 {
736         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
737         struct chan_pjsip_pvt *pvt = channel->pvt;
738         struct ast_frame *f;
739         struct ast_sip_session_media *media = NULL;
740         int rtcp = 0;
741         int fdno = ast_channel_fdno(ast);
742
743         switch (fdno) {
744         case 0:
745                 media = pvt->media[SIP_MEDIA_AUDIO];
746                 break;
747         case 1:
748                 media = pvt->media[SIP_MEDIA_AUDIO];
749                 rtcp = 1;
750                 break;
751         case 2:
752                 media = pvt->media[SIP_MEDIA_VIDEO];
753                 break;
754         case 3:
755                 media = pvt->media[SIP_MEDIA_VIDEO];
756                 rtcp = 1;
757                 break;
758         }
759
760         if (!media || !media->rtp) {
761                 return &ast_null_frame;
762         }
763
764         if (!(f = ast_rtp_instance_read(media->rtp, rtcp))) {
765                 return f;
766         }
767
768         if (f->frametype != AST_FRAME_VOICE) {
769                 return f;
770         }
771
772         if (!(ast_format_cap_iscompatible(ast_channel_nativeformats(ast), &f->subclass.format))) {
773                 ast_debug(1, "Oooh, format changed to %s\n", ast_getformatname(&f->subclass.format));
774                 ast_format_cap_set(ast_channel_nativeformats(ast), &f->subclass.format);
775                 ast_set_read_format(ast, ast_channel_readformat(ast));
776                 ast_set_write_format(ast, ast_channel_writeformat(ast));
777         }
778
779         if (channel->session->dsp) {
780                 f = ast_dsp_process(ast, channel->session->dsp, f);
781
782                 if (f && (f->frametype == AST_FRAME_DTMF)) {
783                         if (f->subclass.integer == 'f') {
784                                 ast_debug(3, "Fax CNG detected on %s\n", ast_channel_name(ast));
785                                 f = chan_pjsip_cng_tone_detected(channel->session, f);
786                         } else {
787                                 ast_debug(3, "* Detected inband DTMF '%c' on '%s'\n", f->subclass.integer,
788                                         ast_channel_name(ast));
789                         }
790                 }
791         }
792
793         return f;
794 }
795
796 /*! \brief Function called by core to write frames */
797 static int chan_pjsip_write(struct ast_channel *ast, struct ast_frame *frame)
798 {
799         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
800         struct chan_pjsip_pvt *pvt = channel->pvt;
801         struct ast_sip_session_media *media;
802         int res = 0;
803
804         switch (frame->frametype) {
805         case AST_FRAME_VOICE:
806                 media = pvt->media[SIP_MEDIA_AUDIO];
807
808                 if (!media) {
809                         return 0;
810                 }
811                 if (!(ast_format_cap_iscompatible(ast_channel_nativeformats(ast), &frame->subclass.format))) {
812                         char buf[256];
813
814                         ast_log(LOG_WARNING,
815                                 "Asked to transmit frame type %s, while native formats is %s (read/write = %s/%s)\n",
816                                 ast_getformatname(&frame->subclass.format),
817                                 ast_getformatname_multiple(buf, sizeof(buf), ast_channel_nativeformats(ast)),
818                                 ast_getformatname(ast_channel_readformat(ast)),
819                                 ast_getformatname(ast_channel_writeformat(ast)));
820                         return 0;
821                 }
822                 if (media->rtp) {
823                         res = ast_rtp_instance_write(media->rtp, frame);
824                 }
825                 break;
826         case AST_FRAME_VIDEO:
827                 if ((media = pvt->media[SIP_MEDIA_VIDEO]) && media->rtp) {
828                         res = ast_rtp_instance_write(media->rtp, frame);
829                 }
830                 break;
831         case AST_FRAME_MODEM:
832                 break;
833         default:
834                 ast_log(LOG_WARNING, "Can't send %d type frames with PJSIP\n", frame->frametype);
835                 break;
836         }
837
838         return res;
839 }
840
841 struct fixup_data {
842         struct ast_sip_session *session;
843         struct ast_channel *chan;
844         struct ast_channel *oldchan;
845 };
846
847 static void fixup_data_destroy(struct fixup_data *fix_data)
848 {
849         ao2_cleanup(fix_data->session);
850         ast_channel_cleanup(fix_data->chan);
851         ast_channel_cleanup(fix_data->oldchan);
852         ast_free(fix_data);
853 }
854
855 static int fixup(void *data)
856 {
857         struct fixup_data *fix_data = data;
858         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(fix_data->chan);
859         struct chan_pjsip_pvt *pvt = channel->pvt;
860
861         if (channel->session->channel != fix_data->oldchan) {
862                 fixup_data_destroy(fix_data);
863                 return -1;
864         }
865
866         channel->session->channel = fix_data->chan;
867         if (pvt->media[SIP_MEDIA_AUDIO] && pvt->media[SIP_MEDIA_AUDIO]->rtp) {
868                 ast_rtp_instance_set_channel_id(pvt->media[SIP_MEDIA_AUDIO]->rtp, ast_channel_uniqueid(fix_data->chan));
869         }
870         if (pvt->media[SIP_MEDIA_VIDEO] && pvt->media[SIP_MEDIA_VIDEO]->rtp) {
871                 ast_rtp_instance_set_channel_id(pvt->media[SIP_MEDIA_VIDEO]->rtp, ast_channel_uniqueid(fix_data->chan));
872         }
873
874         fixup_data_destroy(fix_data);
875
876         return 0;
877 }
878
879 /*! \brief Function called by core to change the underlying owner channel */
880 static int chan_pjsip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
881 {
882         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(newchan);
883         struct fixup_data *fix_data = ast_calloc(1, sizeof(*fix_data));
884
885         if (!fix_data) {
886                 return -1;
887         }
888
889         fix_data->session = channel->session;
890         ao2_ref(fix_data->session, +1);
891
892         fix_data->chan = newchan;
893         ast_channel_ref(fix_data->chan);
894
895         fix_data->oldchan = oldchan;
896         ast_channel_ref(fix_data->oldchan);
897
898         if (ast_sip_push_task(channel->session->serializer, fixup, fix_data)) {
899                 fixup_data_destroy(fix_data);
900                 ast_log(LOG_WARNING, "Unable to perform channel fixup\n");
901                 return -1;
902         }
903
904         return 0;
905 }
906
907 /*! \brief Function called to get the device state of an endpoint */
908 static int chan_pjsip_devicestate(const char *data)
909 {
910         RAII_VAR(struct ast_sip_endpoint *, endpoint, ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint", data), ao2_cleanup);
911         enum ast_device_state state = AST_DEVICE_UNKNOWN;
912         RAII_VAR(struct ast_endpoint_snapshot *, endpoint_snapshot, NULL, ao2_cleanup);
913         RAII_VAR(struct stasis_cache *, cache, NULL, ao2_cleanup);
914         struct ast_devstate_aggregate aggregate;
915         int num, inuse = 0;
916
917         if (!endpoint) {
918                 return AST_DEVICE_INVALID;
919         }
920
921         endpoint_snapshot = ast_endpoint_latest_snapshot(ast_endpoint_get_tech(endpoint->persistent),
922                 ast_endpoint_get_resource(endpoint->persistent));
923
924         if (!endpoint_snapshot) {
925                 return AST_DEVICE_INVALID;
926         }
927
928         if (endpoint_snapshot->state == AST_ENDPOINT_OFFLINE) {
929                 state = AST_DEVICE_UNAVAILABLE;
930         } else if (endpoint_snapshot->state == AST_ENDPOINT_ONLINE) {
931                 state = AST_DEVICE_NOT_INUSE;
932         }
933
934         if (!endpoint_snapshot->num_channels || !(cache = ast_channel_cache())) {
935                 return state;
936         }
937
938         ast_devstate_aggregate_init(&aggregate);
939
940         ao2_ref(cache, +1);
941
942         for (num = 0; num < endpoint_snapshot->num_channels; num++) {
943                 RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
944                 struct ast_channel_snapshot *snapshot;
945
946                 msg = stasis_cache_get(cache, ast_channel_snapshot_type(),
947                         endpoint_snapshot->channel_ids[num]);
948
949                 if (!msg) {
950                         continue;
951                 }
952
953                 snapshot = stasis_message_data(msg);
954
955                 if (snapshot->state == AST_STATE_DOWN) {
956                         ast_devstate_aggregate_add(&aggregate, AST_DEVICE_NOT_INUSE);
957                 } else if (snapshot->state == AST_STATE_RINGING) {
958                         ast_devstate_aggregate_add(&aggregate, AST_DEVICE_RINGING);
959                 } else if ((snapshot->state == AST_STATE_UP) || (snapshot->state == AST_STATE_RING) ||
960                         (snapshot->state == AST_STATE_BUSY)) {
961                         ast_devstate_aggregate_add(&aggregate, AST_DEVICE_INUSE);
962                         inuse++;
963                 }
964         }
965
966         if (endpoint->devicestate_busy_at && (inuse == endpoint->devicestate_busy_at)) {
967                 state = AST_DEVICE_BUSY;
968         } else if (ast_devstate_aggregate_result(&aggregate) != AST_DEVICE_INVALID) {
969                 state = ast_devstate_aggregate_result(&aggregate);
970         }
971
972         return state;
973 }
974
975 /*! \brief Function called to query options on a channel */
976 static int chan_pjsip_queryoption(struct ast_channel *ast, int option, void *data, int *datalen)
977 {
978         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
979         struct ast_sip_session *session = channel->session;
980         int res = -1;
981         enum ast_sip_session_t38state state = T38_STATE_UNAVAILABLE;
982
983         switch (option) {
984         case AST_OPTION_T38_STATE:
985                 if (session->endpoint->media.t38.enabled) {
986                         switch (session->t38state) {
987                         case T38_LOCAL_REINVITE:
988                         case T38_PEER_REINVITE:
989                                 state = T38_STATE_NEGOTIATING;
990                                 break;
991                         case T38_ENABLED:
992                                 state = T38_STATE_NEGOTIATED;
993                                 break;
994                         case T38_REJECTED:
995                                 state = T38_STATE_REJECTED;
996                                 break;
997                         default:
998                                 state = T38_STATE_UNKNOWN;
999                                 break;
1000                         }
1001                 }
1002
1003                 *((enum ast_t38_state *) data) = state;
1004                 res = 0;
1005
1006                 break;
1007         default:
1008                 break;
1009         }
1010
1011         return res;
1012 }
1013
1014 struct indicate_data {
1015         struct ast_sip_session *session;
1016         int condition;
1017         int response_code;
1018         void *frame_data;
1019         size_t datalen;
1020 };
1021
1022 static void indicate_data_destroy(void *obj)
1023 {
1024         struct indicate_data *ind_data = obj;
1025
1026         ast_free(ind_data->frame_data);
1027         ao2_ref(ind_data->session, -1);
1028 }
1029
1030 static struct indicate_data *indicate_data_alloc(struct ast_sip_session *session,
1031                 int condition, int response_code, const void *frame_data, size_t datalen)
1032 {
1033         struct indicate_data *ind_data = ao2_alloc(sizeof(*ind_data), indicate_data_destroy);
1034
1035         if (!ind_data) {
1036                 return NULL;
1037         }
1038
1039         ind_data->frame_data = ast_malloc(datalen);
1040         if (!ind_data->frame_data) {
1041                 ao2_ref(ind_data, -1);
1042                 return NULL;
1043         }
1044
1045         memcpy(ind_data->frame_data, frame_data, datalen);
1046         ind_data->datalen = datalen;
1047         ind_data->condition = condition;
1048         ind_data->response_code = response_code;
1049         ao2_ref(session, +1);
1050         ind_data->session = session;
1051
1052         return ind_data;
1053 }
1054
1055 static int indicate(void *data)
1056 {
1057         pjsip_tx_data *packet = NULL;
1058         struct indicate_data *ind_data = data;
1059         struct ast_sip_session *session = ind_data->session;
1060         int response_code = ind_data->response_code;
1061
1062         if (pjsip_inv_answer(session->inv_session, response_code, NULL, NULL, &packet) == PJ_SUCCESS) {
1063                 ast_sip_session_send_response(session, packet);
1064         }
1065
1066         ao2_ref(ind_data, -1);
1067
1068         return 0;
1069 }
1070
1071 /*! \brief Send SIP INFO with video update request */
1072 static int transmit_info_with_vidupdate(void *data)
1073 {
1074         const char * xml =
1075                 "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
1076                 " <media_control>\r\n"
1077                 "  <vc_primitive>\r\n"
1078                 "   <to_encoder>\r\n"
1079                 "    <picture_fast_update/>\r\n"
1080                 "   </to_encoder>\r\n"
1081                 "  </vc_primitive>\r\n"
1082                 " </media_control>\r\n";
1083
1084         const struct ast_sip_body body = {
1085                 .type = "application",
1086                 .subtype = "media_control+xml",
1087                 .body_text = xml
1088         };
1089
1090         RAII_VAR(struct ast_sip_session *, session, data, ao2_cleanup);
1091         struct pjsip_tx_data *tdata;
1092
1093         if (ast_sip_create_request("INFO", session->inv_session->dlg, session->endpoint, NULL, &tdata)) {
1094                 ast_log(LOG_ERROR, "Could not create text video update INFO request\n");
1095                 return -1;
1096         }
1097         if (ast_sip_add_body(tdata, &body)) {
1098                 ast_log(LOG_ERROR, "Could not add body to text video update INFO request\n");
1099                 return -1;
1100         }
1101         ast_sip_session_send_request(session, tdata);
1102
1103         return 0;
1104 }
1105
1106 /*! \brief Update connected line information */
1107 static int update_connected_line_information(void *data)
1108 {
1109         RAII_VAR(struct ast_sip_session *, session, data, ao2_cleanup);
1110         struct ast_party_id connected_id;
1111
1112         if ((ast_channel_state(session->channel) != AST_STATE_UP) && (session->inv_session->role == PJSIP_UAS_ROLE)) {
1113                 int response_code = 0;
1114
1115                 if (ast_channel_state(session->channel) == AST_STATE_RING) {
1116                         response_code = !session->endpoint->inband_progress ? 180 : 183;
1117                 } else if (ast_channel_state(session->channel) == AST_STATE_RINGING) {
1118                         response_code = 183;
1119                 }
1120
1121                 if (response_code) {
1122                         struct pjsip_tx_data *packet = NULL;
1123
1124                         if (pjsip_inv_answer(session->inv_session, response_code, NULL, NULL, &packet) == PJ_SUCCESS) {
1125                                 ast_sip_session_send_response(session, packet);
1126                         }
1127                 }
1128         } else {
1129                 enum ast_sip_session_refresh_method method = session->endpoint->id.refresh_method;
1130
1131                 if (session->inv_session->invite_tsx && (session->inv_session->options & PJSIP_INV_SUPPORT_UPDATE)) {
1132                         method = AST_SIP_SESSION_REFRESH_METHOD_UPDATE;
1133                 }
1134
1135                 connected_id = ast_channel_connected_effective_id(session->channel);
1136                 if ((session->endpoint->id.send_pai || session->endpoint->id.send_rpid) &&
1137                     (session->endpoint->id.trust_outbound ||
1138                      ((connected_id.name.presentation & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED &&
1139                       (connected_id.number.presentation & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED))) {
1140                         ast_sip_session_refresh(session, NULL, NULL, NULL, method, 1);
1141                 }
1142         }
1143
1144         return 0;
1145 }
1146
1147 /*! \brief Function called by core to ask the channel to indicate some sort of condition */
1148 static int chan_pjsip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
1149 {
1150         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
1151         struct chan_pjsip_pvt *pvt = channel->pvt;
1152         struct ast_sip_session_media *media;
1153         int response_code = 0;
1154         int res = 0;
1155
1156         switch (condition) {
1157         case AST_CONTROL_RINGING:
1158                 if (ast_channel_state(ast) == AST_STATE_RING) {
1159                         if (channel->session->endpoint->inband_progress) {
1160                                 response_code = 183;
1161                                 res = -1;
1162                         } else {
1163                                 response_code = 180;
1164                         }
1165                 } else {
1166                         res = -1;
1167                 }
1168                 ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "PJSIP/%s", ast_sorcery_object_get_id(channel->session->endpoint));
1169                 break;
1170         case AST_CONTROL_BUSY:
1171                 if (ast_channel_state(ast) != AST_STATE_UP) {
1172                         response_code = 486;
1173                 } else {
1174                         res = -1;
1175                 }
1176                 break;
1177         case AST_CONTROL_CONGESTION:
1178                 if (ast_channel_state(ast) != AST_STATE_UP) {
1179                         response_code = 503;
1180                 } else {
1181                         res = -1;
1182                 }
1183                 break;
1184         case AST_CONTROL_INCOMPLETE:
1185                 if (ast_channel_state(ast) != AST_STATE_UP) {
1186                         response_code = 484;
1187                 } else {
1188                         res = -1;
1189                 }
1190                 break;
1191         case AST_CONTROL_PROCEEDING:
1192                 if (ast_channel_state(ast) != AST_STATE_UP) {
1193                         response_code = 100;
1194                 } else {
1195                         res = -1;
1196                 }
1197                 break;
1198         case AST_CONTROL_PROGRESS:
1199                 if (ast_channel_state(ast) != AST_STATE_UP) {
1200                         response_code = 183;
1201                 } else {
1202                         res = -1;
1203                 }
1204                 break;
1205         case AST_CONTROL_VIDUPDATE:
1206                 media = pvt->media[SIP_MEDIA_VIDEO];
1207                 if (media && media->rtp) {
1208                         /* FIXME: Only use this for VP8. Additional work would have to be done to
1209                          * fully support other video codecs */
1210                         struct ast_format_cap *fcap = ast_channel_nativeformats(ast);
1211                         struct ast_format vp8;
1212                         ast_format_set(&vp8, AST_FORMAT_VP8, 0);
1213                         if (ast_format_cap_iscompatible(fcap, &vp8)) {
1214                                 /* FIXME Fake RTP write, this will be sent as an RTCP packet. Ideally the
1215                                  * RTP engine would provide a way to externally write/schedule RTCP
1216                                  * packets */
1217                                 struct ast_frame fr;
1218                                 fr.frametype = AST_FRAME_CONTROL;
1219                                 fr.subclass.integer = AST_CONTROL_VIDUPDATE;
1220                                 res = ast_rtp_instance_write(media->rtp, &fr);
1221                         } else {
1222                                 ao2_ref(channel->session, +1);
1223
1224                                 if (ast_sip_push_task(channel->session->serializer, transmit_info_with_vidupdate, channel->session)) {
1225                                         ao2_cleanup(channel->session);
1226                                 }
1227                         }
1228                 } else {
1229                         res = -1;
1230                 }
1231                 break;
1232         case AST_CONTROL_CONNECTED_LINE:
1233                 ao2_ref(channel->session, +1);
1234                 if (ast_sip_push_task(channel->session->serializer, update_connected_line_information, channel->session)) {
1235                         ao2_cleanup(channel->session);
1236                 }
1237                 break;
1238         case AST_CONTROL_UPDATE_RTP_PEER:
1239                 break;
1240         case AST_CONTROL_PVT_CAUSE_CODE:
1241                 res = -1;
1242                 break;
1243         case AST_CONTROL_HOLD:
1244                 ast_moh_start(ast, data, NULL);
1245                 break;
1246         case AST_CONTROL_UNHOLD:
1247                 ast_moh_stop(ast);
1248                 break;
1249         case AST_CONTROL_SRCUPDATE:
1250                 break;
1251         case AST_CONTROL_SRCCHANGE:
1252                 break;
1253         case AST_CONTROL_REDIRECTING:
1254                 if (ast_channel_state(ast) != AST_STATE_UP) {
1255                         response_code = 181;
1256                 } else {
1257                         res = -1;
1258                 }
1259                 break;
1260         case AST_CONTROL_T38_PARAMETERS:
1261                 res = 0;
1262
1263                 if (channel->session->t38state == T38_PEER_REINVITE) {
1264                         const struct ast_control_t38_parameters *parameters = data;
1265
1266                         if (parameters->request_response == AST_T38_REQUEST_PARMS) {
1267                                 res = AST_T38_REQUEST_PARMS;
1268                         }
1269                 }
1270
1271                 break;
1272         case -1:
1273                 res = -1;
1274                 break;
1275         default:
1276                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
1277                 res = -1;
1278                 break;
1279         }
1280
1281         if (response_code) {
1282                 struct indicate_data *ind_data = indicate_data_alloc(channel->session, condition, response_code, data, datalen);
1283                 if (!ind_data || ast_sip_push_task(channel->session->serializer, indicate, ind_data)) {
1284                         ast_log(LOG_NOTICE, "Cannot send response code %d to endpoint %s. Could not queue task properly\n",
1285                                         response_code, ast_sorcery_object_get_id(channel->session->endpoint));
1286                         ao2_cleanup(ind_data);
1287                         res = -1;
1288                 }
1289         }
1290
1291         return res;
1292 }
1293
1294 struct transfer_data {
1295         struct ast_sip_session *session;
1296         char *target;
1297 };
1298
1299 static void transfer_data_destroy(void *obj)
1300 {
1301         struct transfer_data *trnf_data = obj;
1302
1303         ast_free(trnf_data->target);
1304         ao2_cleanup(trnf_data->session);
1305 }
1306
1307 static struct transfer_data *transfer_data_alloc(struct ast_sip_session *session, const char *target)
1308 {
1309         struct transfer_data *trnf_data = ao2_alloc(sizeof(*trnf_data), transfer_data_destroy);
1310
1311         if (!trnf_data) {
1312                 return NULL;
1313         }
1314
1315         if (!(trnf_data->target = ast_strdup(target))) {
1316                 ao2_ref(trnf_data, -1);
1317                 return NULL;
1318         }
1319
1320         ao2_ref(session, +1);
1321         trnf_data->session = session;
1322
1323         return trnf_data;
1324 }
1325
1326 static void transfer_redirect(struct ast_sip_session *session, const char *target)
1327 {
1328         pjsip_tx_data *packet;
1329         enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
1330         pjsip_contact_hdr *contact;
1331         pj_str_t tmp;
1332
1333         if (pjsip_inv_end_session(session->inv_session, 302, NULL, &packet) != PJ_SUCCESS) {
1334                 message = AST_TRANSFER_FAILED;
1335                 ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1336
1337                 return;
1338         }
1339
1340         if (!(contact = pjsip_msg_find_hdr(packet->msg, PJSIP_H_CONTACT, NULL))) {
1341                 contact = pjsip_contact_hdr_create(packet->pool);
1342         }
1343
1344         pj_strdup2_with_null(packet->pool, &tmp, target);
1345         if (!(contact->uri = pjsip_parse_uri(packet->pool, tmp.ptr, tmp.slen, PJSIP_PARSE_URI_AS_NAMEADDR))) {
1346                 message = AST_TRANSFER_FAILED;
1347                 ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1348                 pjsip_tx_data_dec_ref(packet);
1349
1350                 return;
1351         }
1352         pjsip_msg_add_hdr(packet->msg, (pjsip_hdr *) contact);
1353
1354         ast_sip_session_send_response(session, packet);
1355         ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1356 }
1357
1358 static void transfer_refer(struct ast_sip_session *session, const char *target)
1359 {
1360         pjsip_evsub *sub;
1361         enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
1362         pj_str_t tmp;
1363         pjsip_tx_data *packet;
1364
1365         if (pjsip_xfer_create_uac(session->inv_session->dlg, NULL, &sub) != PJ_SUCCESS) {
1366                 message = AST_TRANSFER_FAILED;
1367                 ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1368
1369                 return;
1370         }
1371
1372         if (pjsip_xfer_initiate(sub, pj_cstr(&tmp, target), &packet) != PJ_SUCCESS) {
1373                 message = AST_TRANSFER_FAILED;
1374                 ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1375                 pjsip_evsub_terminate(sub, PJ_FALSE);
1376
1377                 return;
1378         }
1379
1380         pjsip_xfer_send_request(sub, packet);
1381         ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1382 }
1383
1384 static int transfer(void *data)
1385 {
1386         struct transfer_data *trnf_data = data;
1387
1388         if (ast_channel_state(trnf_data->session->channel) == AST_STATE_RING) {
1389                 transfer_redirect(trnf_data->session, trnf_data->target);
1390         } else {
1391                 transfer_refer(trnf_data->session, trnf_data->target);
1392         }
1393
1394         ao2_ref(trnf_data, -1);
1395         return 0;
1396 }
1397
1398 /*! \brief Function called by core for Asterisk initiated transfer */
1399 static int chan_pjsip_transfer(struct ast_channel *chan, const char *target)
1400 {
1401         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
1402         struct transfer_data *trnf_data = transfer_data_alloc(channel->session, target);
1403
1404         if (!trnf_data) {
1405                 return -1;
1406         }
1407
1408         if (ast_sip_push_task(channel->session->serializer, transfer, trnf_data)) {
1409                 ast_log(LOG_WARNING, "Error requesting transfer\n");
1410                 ao2_cleanup(trnf_data);
1411                 return -1;
1412         }
1413
1414         return 0;
1415 }
1416
1417 /*! \brief Function called by core to start a DTMF digit */
1418 static int chan_pjsip_digit_begin(struct ast_channel *chan, char digit)
1419 {
1420         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
1421         struct chan_pjsip_pvt *pvt = channel->pvt;
1422         struct ast_sip_session_media *media = pvt->media[SIP_MEDIA_AUDIO];
1423         int res = 0;
1424
1425         switch (channel->session->endpoint->dtmf) {
1426         case AST_SIP_DTMF_RFC_4733:
1427                 if (!media || !media->rtp) {
1428                         return -1;
1429                 }
1430
1431                 ast_rtp_instance_dtmf_begin(media->rtp, digit);
1432         case AST_SIP_DTMF_NONE:
1433                 break;
1434         case AST_SIP_DTMF_INBAND:
1435                 res = -1;
1436                 break;
1437         default:
1438                 break;
1439         }
1440
1441         return res;
1442 }
1443
1444 struct info_dtmf_data {
1445         struct ast_sip_session *session;
1446         char digit;
1447         unsigned int duration;
1448 };
1449
1450 static void info_dtmf_data_destroy(void *obj)
1451 {
1452         struct info_dtmf_data *dtmf_data = obj;
1453         ao2_ref(dtmf_data->session, -1);
1454 }
1455
1456 static struct info_dtmf_data *info_dtmf_data_alloc(struct ast_sip_session *session, char digit, unsigned int duration)
1457 {
1458         struct info_dtmf_data *dtmf_data = ao2_alloc(sizeof(*dtmf_data), info_dtmf_data_destroy);
1459         if (!dtmf_data) {
1460                 return NULL;
1461         }
1462         ao2_ref(session, +1);
1463         dtmf_data->session = session;
1464         dtmf_data->digit = digit;
1465         dtmf_data->duration = duration;
1466         return dtmf_data;
1467 }
1468
1469 static int transmit_info_dtmf(void *data)
1470 {
1471         RAII_VAR(struct info_dtmf_data *, dtmf_data, data, ao2_cleanup);
1472
1473         struct ast_sip_session *session = dtmf_data->session;
1474         struct pjsip_tx_data *tdata;
1475
1476         RAII_VAR(struct ast_str *, body_text, NULL, ast_free_ptr);
1477
1478         struct ast_sip_body body = {
1479                 .type = "application",
1480                 .subtype = "dtmf-relay",
1481         };
1482
1483         if (!(body_text = ast_str_create(32))) {
1484                 ast_log(LOG_ERROR, "Could not allocate buffer for INFO DTMF.\n");
1485                 return -1;
1486         }
1487         ast_str_set(&body_text, 0, "Signal=%c\r\nDuration=%u\r\n", dtmf_data->digit, dtmf_data->duration);
1488
1489         body.body_text = ast_str_buffer(body_text);
1490
1491         if (ast_sip_create_request("INFO", session->inv_session->dlg, session->endpoint, NULL, &tdata)) {
1492                 ast_log(LOG_ERROR, "Could not create DTMF INFO request\n");
1493                 return -1;
1494         }
1495         if (ast_sip_add_body(tdata, &body)) {
1496                 ast_log(LOG_ERROR, "Could not add body to DTMF INFO request\n");
1497                 pjsip_tx_data_dec_ref(tdata);
1498                 return -1;
1499         }
1500         ast_sip_session_send_request(session, tdata);
1501
1502         return 0;
1503 }
1504
1505 /*! \brief Function called by core to stop a DTMF digit */
1506 static int chan_pjsip_digit_end(struct ast_channel *ast, char digit, unsigned int duration)
1507 {
1508         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
1509         struct chan_pjsip_pvt *pvt = channel->pvt;
1510         struct ast_sip_session_media *media = pvt->media[SIP_MEDIA_AUDIO];
1511         int res = 0;
1512
1513         switch (channel->session->endpoint->dtmf) {
1514         case AST_SIP_DTMF_INFO:
1515         {
1516                 struct info_dtmf_data *dtmf_data = info_dtmf_data_alloc(channel->session, digit, duration);
1517
1518                 if (!dtmf_data) {
1519                         return -1;
1520                 }
1521
1522                 if (ast_sip_push_task(channel->session->serializer, transmit_info_dtmf, dtmf_data)) {
1523                         ast_log(LOG_WARNING, "Error sending DTMF via INFO.\n");
1524                         ao2_cleanup(dtmf_data);
1525                         return -1;
1526                 }
1527                 break;
1528         }
1529         case AST_SIP_DTMF_RFC_4733:
1530                 if (!media || !media->rtp) {
1531                         return -1;
1532                 }
1533
1534                 ast_rtp_instance_dtmf_end_with_duration(media->rtp, digit, duration);
1535         case AST_SIP_DTMF_NONE:
1536                 break;
1537         case AST_SIP_DTMF_INBAND:
1538                 res = -1;
1539                 break;
1540         }
1541
1542         return res;
1543 }
1544
1545 static int call(void *data)
1546 {
1547         struct ast_sip_session *session = data;
1548         pjsip_tx_data *tdata;
1549
1550         int res = ast_sip_session_create_invite(session, &tdata);
1551
1552         if (res) {
1553                 ast_queue_hangup(session->channel);
1554         } else {
1555                 ast_sip_session_send_request(session, tdata);
1556         }
1557         ao2_ref(session, -1);
1558         return res;
1559 }
1560
1561 /*! \brief Function called by core to actually start calling a remote party */
1562 static int chan_pjsip_call(struct ast_channel *ast, const char *dest, int timeout)
1563 {
1564         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
1565
1566         ao2_ref(channel->session, +1);
1567         if (ast_sip_push_task(channel->session->serializer, call, channel->session)) {
1568                 ast_log(LOG_WARNING, "Error attempting to place outbound call to call '%s'\n", dest);
1569                 ao2_cleanup(channel->session);
1570                 return -1;
1571         }
1572
1573         return 0;
1574 }
1575
1576 /*! \brief Internal function which translates from Asterisk cause codes to SIP response codes */
1577 static int hangup_cause2sip(int cause)
1578 {
1579         switch (cause) {
1580         case AST_CAUSE_UNALLOCATED:             /* 1 */
1581         case AST_CAUSE_NO_ROUTE_DESTINATION:    /* 3 IAX2: Can't find extension in context */
1582         case AST_CAUSE_NO_ROUTE_TRANSIT_NET:    /* 2 */
1583                 return 404;
1584         case AST_CAUSE_CONGESTION:              /* 34 */
1585         case AST_CAUSE_SWITCH_CONGESTION:       /* 42 */
1586                 return 503;
1587         case AST_CAUSE_NO_USER_RESPONSE:        /* 18 */
1588                 return 408;
1589         case AST_CAUSE_NO_ANSWER:               /* 19 */
1590         case AST_CAUSE_UNREGISTERED:        /* 20 */
1591                 return 480;
1592         case AST_CAUSE_CALL_REJECTED:           /* 21 */
1593                 return 403;
1594         case AST_CAUSE_NUMBER_CHANGED:          /* 22 */
1595                 return 410;
1596         case AST_CAUSE_NORMAL_UNSPECIFIED:      /* 31 */
1597                 return 480;
1598         case AST_CAUSE_INVALID_NUMBER_FORMAT:
1599                 return 484;
1600         case AST_CAUSE_USER_BUSY:
1601                 return 486;
1602         case AST_CAUSE_FAILURE:
1603                 return 500;
1604         case AST_CAUSE_FACILITY_REJECTED:       /* 29 */
1605                 return 501;
1606         case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
1607                 return 503;
1608         case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
1609                 return 502;
1610         case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL:       /* Can't find codec to connect to host */
1611                 return 488;
1612         case AST_CAUSE_INTERWORKING:    /* Unspecified Interworking issues */
1613                 return 500;
1614         case AST_CAUSE_NOTDEFINED:
1615         default:
1616                 ast_debug(1, "AST hangup cause %d (no match found in PJSIP)\n", cause);
1617                 return 0;
1618         }
1619
1620         /* Never reached */
1621         return 0;
1622 }
1623
1624 struct hangup_data {
1625         int cause;
1626         struct ast_channel *chan;
1627 };
1628
1629 static void hangup_data_destroy(void *obj)
1630 {
1631         struct hangup_data *h_data = obj;
1632
1633         h_data->chan = ast_channel_unref(h_data->chan);
1634 }
1635
1636 static struct hangup_data *hangup_data_alloc(int cause, struct ast_channel *chan)
1637 {
1638         struct hangup_data *h_data = ao2_alloc(sizeof(*h_data), hangup_data_destroy);
1639
1640         if (!h_data) {
1641                 return NULL;
1642         }
1643
1644         h_data->cause = cause;
1645         h_data->chan = ast_channel_ref(chan);
1646
1647         return h_data;
1648 }
1649
1650 /*! \brief Clear a channel from a session along with its PVT */
1651 static void clear_session_and_channel(struct ast_sip_session *session, struct ast_channel *ast, struct chan_pjsip_pvt *pvt)
1652 {
1653         session->channel = NULL;
1654         if (pvt->media[SIP_MEDIA_AUDIO] && pvt->media[SIP_MEDIA_AUDIO]->rtp) {
1655                 ast_rtp_instance_set_channel_id(pvt->media[SIP_MEDIA_AUDIO]->rtp, "");
1656         }
1657         if (pvt->media[SIP_MEDIA_VIDEO] && pvt->media[SIP_MEDIA_VIDEO]->rtp) {
1658                 ast_rtp_instance_set_channel_id(pvt->media[SIP_MEDIA_VIDEO]->rtp, "");
1659         }
1660         ast_channel_tech_pvt_set(ast, NULL);
1661 }
1662
1663 static int hangup(void *data)
1664 {
1665         pj_status_t status;
1666         pjsip_tx_data *packet = NULL;
1667         struct hangup_data *h_data = data;
1668         struct ast_channel *ast = h_data->chan;
1669         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
1670         struct chan_pjsip_pvt *pvt = channel->pvt;
1671         struct ast_sip_session *session = channel->session;
1672         int cause = h_data->cause;
1673
1674         if (!session->defer_terminate &&
1675                 ((status = pjsip_inv_end_session(session->inv_session, cause ? cause : 603, NULL, &packet)) == PJ_SUCCESS) && packet) {
1676                 if (packet->msg->type == PJSIP_RESPONSE_MSG) {
1677                         ast_sip_session_send_response(session, packet);
1678                 } else {
1679                         ast_sip_session_send_request(session, packet);
1680                 }
1681         }
1682
1683         clear_session_and_channel(session, ast, pvt);
1684         ao2_cleanup(channel);
1685         ao2_cleanup(h_data);
1686
1687         return 0;
1688 }
1689
1690 /*! \brief Function called by core to hang up a PJSIP session */
1691 static int chan_pjsip_hangup(struct ast_channel *ast)
1692 {
1693         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
1694         struct chan_pjsip_pvt *pvt = channel->pvt;
1695         int cause = hangup_cause2sip(ast_channel_hangupcause(channel->session->channel));
1696         struct hangup_data *h_data = hangup_data_alloc(cause, ast);
1697
1698         if (!h_data) {
1699                 goto failure;
1700         }
1701
1702         if (ast_sip_push_task(channel->session->serializer, hangup, h_data)) {
1703                 ast_log(LOG_WARNING, "Unable to push hangup task to the threadpool. Expect bad things\n");
1704                 goto failure;
1705         }
1706
1707         return 0;
1708
1709 failure:
1710         /* Go ahead and do our cleanup of the session and channel even if we're not going
1711          * to be able to send our SIP request/response
1712          */
1713         clear_session_and_channel(channel->session, ast, pvt);
1714         ao2_cleanup(channel);
1715         ao2_cleanup(h_data);
1716
1717         return -1;
1718 }
1719
1720 struct request_data {
1721         struct ast_sip_session *session;
1722         struct ast_format_cap *caps;
1723         const char *dest;
1724         int cause;
1725 };
1726
1727 static int request(void *obj)
1728 {
1729         struct request_data *req_data = obj;
1730         struct ast_sip_session *session = NULL;
1731         char *tmp = ast_strdupa(req_data->dest), *endpoint_name = NULL, *request_user = NULL;
1732         RAII_VAR(struct ast_sip_endpoint *, endpoint, NULL, ao2_cleanup);
1733
1734         AST_DECLARE_APP_ARGS(args,
1735                 AST_APP_ARG(endpoint);
1736                 AST_APP_ARG(aor);
1737         );
1738
1739         if (ast_strlen_zero(tmp)) {
1740                 ast_log(LOG_ERROR, "Unable to create PJSIP channel with empty destination\n");
1741                 req_data->cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
1742                 return -1;
1743         }
1744
1745         AST_NONSTANDARD_APP_ARGS(args, tmp, '/');
1746
1747         /* If a request user has been specified extract it from the endpoint name portion */
1748         if ((endpoint_name = strchr(args.endpoint, '@'))) {
1749                 request_user = args.endpoint;
1750                 *endpoint_name++ = '\0';
1751         } else {
1752                 endpoint_name = args.endpoint;
1753         }
1754
1755         if (ast_strlen_zero(endpoint_name)) {
1756                 ast_log(LOG_ERROR, "Unable to create PJSIP channel with empty endpoint name\n");
1757                 req_data->cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
1758         } else if (!(endpoint = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint", endpoint_name))) {
1759                 ast_log(LOG_ERROR, "Unable to create PJSIP channel - endpoint '%s' was not found\n", endpoint_name);
1760                 req_data->cause = AST_CAUSE_NO_ROUTE_DESTINATION;
1761                 return -1;
1762         }
1763
1764         if (!(session = ast_sip_session_create_outgoing(endpoint, args.aor, request_user, req_data->caps))) {
1765                 req_data->cause = AST_CAUSE_NO_ROUTE_DESTINATION;
1766                 return -1;
1767         }
1768
1769         req_data->session = session;
1770
1771         return 0;
1772 }
1773
1774 /*! \brief Function called by core to create a new outgoing PJSIP session */
1775 static struct ast_channel *chan_pjsip_request(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, const char *data, int *cause)
1776 {
1777         struct request_data req_data;
1778         RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);
1779
1780         req_data.caps = cap;
1781         req_data.dest = data;
1782
1783         if (ast_sip_push_task_synchronous(NULL, request, &req_data)) {
1784                 *cause = req_data.cause;
1785                 return NULL;
1786         }
1787
1788         session = req_data.session;
1789
1790         if (!(session->channel = chan_pjsip_new(session, AST_STATE_DOWN, NULL, NULL, requestor ? ast_channel_linkedid(requestor) : NULL, NULL))) {
1791                 /* Session needs to be terminated prematurely */
1792                 return NULL;
1793         }
1794
1795         return session->channel;
1796 }
1797
1798 struct sendtext_data {
1799         struct ast_sip_session *session;
1800         char text[0];
1801 };
1802
1803 static void sendtext_data_destroy(void *obj)
1804 {
1805         struct sendtext_data *data = obj;
1806         ao2_ref(data->session, -1);
1807 }
1808
1809 static struct sendtext_data* sendtext_data_create(struct ast_sip_session *session, const char *text)
1810 {
1811         int size = strlen(text) + 1;
1812         struct sendtext_data *data = ao2_alloc(sizeof(*data)+size, sendtext_data_destroy);
1813
1814         if (!data) {
1815                 return NULL;
1816         }
1817
1818         data->session = session;
1819         ao2_ref(data->session, +1);
1820         ast_copy_string(data->text, text, size);
1821         return data;
1822 }
1823
1824 static int sendtext(void *obj)
1825 {
1826         RAII_VAR(struct sendtext_data *, data, obj, ao2_cleanup);
1827         pjsip_tx_data *tdata;
1828
1829         const struct ast_sip_body body = {
1830                 .type = "text",
1831                 .subtype = "plain",
1832                 .body_text = data->text
1833         };
1834
1835         /* NOT ast_strlen_zero, because a zero-length message is specifically
1836          * allowed by RFC 3428 (See section 10, Examples) */
1837         if (!data->text) {
1838                 return 0;
1839         }
1840
1841         ast_debug(3, "Sending in dialog SIP message\n");
1842
1843         ast_sip_create_request("MESSAGE", data->session->inv_session->dlg, data->session->endpoint, NULL, &tdata);
1844         ast_sip_add_body(tdata, &body);
1845         ast_sip_send_request(tdata, data->session->inv_session->dlg, data->session->endpoint);
1846
1847         return 0;
1848 }
1849
1850 /*! \brief Function called by core to send text on PJSIP session */
1851 static int chan_pjsip_sendtext(struct ast_channel *ast, const char *text)
1852 {
1853         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
1854         struct sendtext_data *data = sendtext_data_create(channel->session, text);
1855
1856         if (!data || ast_sip_push_task(channel->session->serializer, sendtext, data)) {
1857                 ao2_ref(data, -1);
1858                 return -1;
1859         }
1860         return 0;
1861 }
1862
1863 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
1864 static int hangup_sip2cause(int cause)
1865 {
1866         /* Possible values taken from causes.h */
1867
1868         switch(cause) {
1869         case 401:       /* Unauthorized */
1870                 return AST_CAUSE_CALL_REJECTED;
1871         case 403:       /* Not found */
1872                 return AST_CAUSE_CALL_REJECTED;
1873         case 404:       /* Not found */
1874                 return AST_CAUSE_UNALLOCATED;
1875         case 405:       /* Method not allowed */
1876                 return AST_CAUSE_INTERWORKING;
1877         case 407:       /* Proxy authentication required */
1878                 return AST_CAUSE_CALL_REJECTED;
1879         case 408:       /* No reaction */
1880                 return AST_CAUSE_NO_USER_RESPONSE;
1881         case 409:       /* Conflict */
1882                 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
1883         case 410:       /* Gone */
1884                 return AST_CAUSE_NUMBER_CHANGED;
1885         case 411:       /* Length required */
1886                 return AST_CAUSE_INTERWORKING;
1887         case 413:       /* Request entity too large */
1888                 return AST_CAUSE_INTERWORKING;
1889         case 414:       /* Request URI too large */
1890                 return AST_CAUSE_INTERWORKING;
1891         case 415:       /* Unsupported media type */
1892                 return AST_CAUSE_INTERWORKING;
1893         case 420:       /* Bad extension */
1894                 return AST_CAUSE_NO_ROUTE_DESTINATION;
1895         case 480:       /* No answer */
1896                 return AST_CAUSE_NO_ANSWER;
1897         case 481:       /* No answer */
1898                 return AST_CAUSE_INTERWORKING;
1899         case 482:       /* Loop detected */
1900                 return AST_CAUSE_INTERWORKING;
1901         case 483:       /* Too many hops */
1902                 return AST_CAUSE_NO_ANSWER;
1903         case 484:       /* Address incomplete */
1904                 return AST_CAUSE_INVALID_NUMBER_FORMAT;
1905         case 485:       /* Ambiguous */
1906                 return AST_CAUSE_UNALLOCATED;
1907         case 486:       /* Busy everywhere */
1908                 return AST_CAUSE_BUSY;
1909         case 487:       /* Request terminated */
1910                 return AST_CAUSE_INTERWORKING;
1911         case 488:       /* No codecs approved */
1912                 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
1913         case 491:       /* Request pending */
1914                 return AST_CAUSE_INTERWORKING;
1915         case 493:       /* Undecipherable */
1916                 return AST_CAUSE_INTERWORKING;
1917         case 500:       /* Server internal failure */
1918                 return AST_CAUSE_FAILURE;
1919         case 501:       /* Call rejected */
1920                 return AST_CAUSE_FACILITY_REJECTED;
1921         case 502:
1922                 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
1923         case 503:       /* Service unavailable */
1924                 return AST_CAUSE_CONGESTION;
1925         case 504:       /* Gateway timeout */
1926                 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
1927         case 505:       /* SIP version not supported */
1928                 return AST_CAUSE_INTERWORKING;
1929         case 600:       /* Busy everywhere */
1930                 return AST_CAUSE_USER_BUSY;
1931         case 603:       /* Decline */
1932                 return AST_CAUSE_CALL_REJECTED;
1933         case 604:       /* Does not exist anywhere */
1934                 return AST_CAUSE_UNALLOCATED;
1935         case 606:       /* Not acceptable */
1936                 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
1937         default:
1938                 if (cause < 500 && cause >= 400) {
1939                         /* 4xx class error that is unknown - someting wrong with our request */
1940                         return AST_CAUSE_INTERWORKING;
1941                 } else if (cause < 600 && cause >= 500) {
1942                         /* 5xx class error - problem in the remote end */
1943                         return AST_CAUSE_CONGESTION;
1944                 } else if (cause < 700 && cause >= 600) {
1945                         /* 6xx - global errors in the 4xx class */
1946                         return AST_CAUSE_INTERWORKING;
1947                 }
1948                 return AST_CAUSE_NORMAL;
1949         }
1950         /* Never reached */
1951         return 0;
1952 }
1953
1954 static void chan_pjsip_session_begin(struct ast_sip_session *session)
1955 {
1956         RAII_VAR(struct ast_datastore *, datastore, NULL, ao2_cleanup);
1957
1958         if (session->endpoint->media.direct_media.glare_mitigation ==
1959                         AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_NONE) {
1960                 return;
1961         }
1962
1963         datastore = ast_sip_session_alloc_datastore(&direct_media_mitigation_info,
1964                         "direct_media_glare_mitigation");
1965
1966         if (!datastore) {
1967                 return;
1968         }
1969
1970         ast_sip_session_add_datastore(session, datastore);
1971 }
1972
1973 /*! \brief Function called when the session ends */
1974 static void chan_pjsip_session_end(struct ast_sip_session *session)
1975 {
1976         if (!session->channel) {
1977                 return;
1978         }
1979
1980         if (!ast_channel_hangupcause(session->channel) && session->inv_session) {
1981                 int cause = hangup_sip2cause(session->inv_session->cause);
1982
1983                 ast_queue_hangup_with_cause(session->channel, cause);
1984         } else {
1985                 ast_queue_hangup(session->channel);
1986         }
1987 }
1988
1989 /*! \brief Function called when a request is received on the session */
1990 static int chan_pjsip_incoming_request(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
1991 {
1992         pjsip_tx_data *packet = NULL;
1993
1994         if (session->channel) {
1995                 return 0;
1996         }
1997
1998         if (!(session->channel = chan_pjsip_new(session, AST_STATE_RING, session->exten, NULL, NULL, NULL))) {
1999                 if (pjsip_inv_end_session(session->inv_session, 503, NULL, &packet) == PJ_SUCCESS) {
2000                         ast_sip_session_send_response(session, packet);
2001                 }
2002
2003                 ast_log(LOG_ERROR, "Failed to allocate new PJSIP channel on incoming SIP INVITE\n");
2004                 return -1;
2005         }
2006         /* channel gets created on incoming request, but we wait to call start
2007            so other supplements have a chance to run */
2008         return 0;
2009 }
2010
2011 static int pbx_start_incoming_request(struct ast_sip_session *session, pjsip_rx_data *rdata)
2012 {
2013         int res;
2014
2015         res = ast_pbx_start(session->channel);
2016
2017         switch (res) {
2018         case AST_PBX_FAILED:
2019                 ast_log(LOG_WARNING, "Failed to start PBX ;(\n");
2020                 ast_channel_hangupcause_set(session->channel, AST_CAUSE_SWITCH_CONGESTION);
2021                 ast_hangup(session->channel);
2022                 break;
2023         case AST_PBX_CALL_LIMIT:
2024                 ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
2025                 ast_channel_hangupcause_set(session->channel, AST_CAUSE_SWITCH_CONGESTION);
2026                 ast_hangup(session->channel);
2027                 break;
2028         case AST_PBX_SUCCESS:
2029         default:
2030                 break;
2031         }
2032
2033         ast_debug(3, "Started PBX on new PJSIP channel %s\n", ast_channel_name(session->channel));
2034
2035         return (res == AST_PBX_SUCCESS) ? 0 : -1;
2036 }
2037
2038 static struct ast_sip_session_supplement pbx_start_supplement = {
2039         .method = "INVITE",
2040         .priority = AST_SIP_SESSION_SUPPLEMENT_PRIORITY_LAST,
2041         .incoming_request = pbx_start_incoming_request,
2042 };
2043
2044 /*! \brief Function called when a response is received on the session */
2045 static void chan_pjsip_incoming_response(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
2046 {
2047         struct pjsip_status_line status = rdata->msg_info.msg->line.status;
2048
2049         if (!session->channel) {
2050                 return;
2051         }
2052
2053         switch (status.code) {
2054         case 180:
2055                 ast_queue_control(session->channel, AST_CONTROL_RINGING);
2056                 if (ast_channel_state(session->channel) != AST_STATE_UP) {
2057                         ast_setstate(session->channel, AST_STATE_RINGING);
2058                 }
2059                 break;
2060         case 183:
2061                 ast_queue_control(session->channel, AST_CONTROL_PROGRESS);
2062                 break;
2063         case 200:
2064                 ast_queue_control(session->channel, AST_CONTROL_ANSWER);
2065                 break;
2066         default:
2067                 break;
2068         }
2069 }
2070
2071 static int chan_pjsip_incoming_ack(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
2072 {
2073         if (rdata->msg_info.msg->line.req.method.id == PJSIP_ACK_METHOD) {
2074                 if (session->endpoint->media.direct_media.enabled && session->channel) {
2075                         ast_queue_control(session->channel, AST_CONTROL_SRCCHANGE);
2076                 }
2077         }
2078         return 0;
2079 }
2080
2081 /*!
2082  * \brief Load the module
2083  *
2084  * Module loading including tests for configuration or dependencies.
2085  * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
2086  * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
2087  * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
2088  * configuration file or other non-critical problem return
2089  * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
2090  */
2091 static int load_module(void)
2092 {
2093         if (!(chan_pjsip_tech.capabilities = ast_format_cap_alloc(0))) {
2094                 return AST_MODULE_LOAD_DECLINE;
2095         }
2096
2097         ast_format_cap_add_all_by_type(chan_pjsip_tech.capabilities, AST_FORMAT_TYPE_AUDIO);
2098
2099         ast_rtp_glue_register(&chan_pjsip_rtp_glue);
2100
2101         if (ast_channel_register(&chan_pjsip_tech)) {
2102                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", channel_type);
2103                 goto end;
2104         }
2105
2106         if (ast_custom_function_register(&chan_pjsip_dial_contacts_function)) {
2107                 ast_log(LOG_ERROR, "Unable to register PJSIP_DIAL_CONTACTS dialplan function\n");
2108                 goto end;
2109         }
2110
2111         if (ast_custom_function_register(&media_offer_function)) {
2112                 ast_log(LOG_WARNING, "Unable to register PJSIP_MEDIA_OFFER dialplan function\n");
2113         }
2114
2115         if (ast_sip_session_register_supplement(&chan_pjsip_supplement)) {
2116                 ast_log(LOG_ERROR, "Unable to register PJSIP supplement\n");
2117                 goto end;
2118         }
2119
2120         if (ast_sip_session_register_supplement(&pbx_start_supplement)) {
2121                 ast_log(LOG_ERROR, "Unable to register PJSIP pbx start supplement\n");
2122                 ast_sip_session_unregister_supplement(&chan_pjsip_supplement);
2123                 goto end;
2124         }
2125
2126         if (ast_sip_session_register_supplement(&chan_pjsip_ack_supplement)) {
2127                 ast_log(LOG_ERROR, "Unable to register PJSIP ACK supplement\n");
2128                 ast_sip_session_unregister_supplement(&pbx_start_supplement);
2129                 ast_sip_session_unregister_supplement(&chan_pjsip_supplement);
2130                 goto end;
2131         }
2132
2133         return 0;
2134
2135 end:
2136         ast_custom_function_unregister(&media_offer_function);
2137         ast_custom_function_unregister(&chan_pjsip_dial_contacts_function);
2138         ast_channel_unregister(&chan_pjsip_tech);
2139         ast_rtp_glue_unregister(&chan_pjsip_rtp_glue);
2140
2141         return AST_MODULE_LOAD_FAILURE;
2142 }
2143
2144 /*! \brief Reload module */
2145 static int reload(void)
2146 {
2147         return -1;
2148 }
2149
2150 /*! \brief Unload the PJSIP channel from Asterisk */
2151 static int unload_module(void)
2152 {
2153         ast_custom_function_unregister(&media_offer_function);
2154
2155         ast_sip_session_unregister_supplement(&chan_pjsip_supplement);
2156         ast_sip_session_unregister_supplement(&pbx_start_supplement);
2157         ast_sip_session_unregister_supplement(&chan_pjsip_ack_supplement);
2158
2159         ast_custom_function_unregister(&chan_pjsip_dial_contacts_function);
2160         ast_channel_unregister(&chan_pjsip_tech);
2161         ast_rtp_glue_unregister(&chan_pjsip_rtp_glue);
2162
2163         return 0;
2164 }
2165
2166 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP Channel Driver",
2167                 .load = load_module,
2168                 .unload = unload_module,
2169                 .reload = reload,
2170                 .load_pri = AST_MODPRI_CHANNEL_DRIVER,
2171                );