Fix refcounting of sip_pvt in test_sip_rtpqos test and unlink it from the list of...
[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         /* If res_pjsip_session is ever updated to create/destroy ast_sip_session_media
581          * during a call such as if multiple same-type stream support is introduced,
582          * these will need to be recaptured as well */
583         pvt->media[SIP_MEDIA_AUDIO] = ao2_find(session->media, "audio", OBJ_KEY);
584         pvt->media[SIP_MEDIA_VIDEO] = ao2_find(session->media, "video", OBJ_KEY);
585         ast_channel_tech_pvt_set(chan, channel);
586         if (pvt->media[SIP_MEDIA_AUDIO] && pvt->media[SIP_MEDIA_AUDIO]->rtp) {
587                 ast_rtp_instance_set_channel_id(pvt->media[SIP_MEDIA_AUDIO]->rtp, ast_channel_uniqueid(chan));
588         }
589         if (pvt->media[SIP_MEDIA_VIDEO] && pvt->media[SIP_MEDIA_VIDEO]->rtp) {
590                 ast_rtp_instance_set_channel_id(pvt->media[SIP_MEDIA_VIDEO]->rtp, ast_channel_uniqueid(chan));
591         }
592
593         if (ast_format_cap_is_empty(session->req_caps) || !ast_format_cap_has_joint(session->req_caps, session->endpoint->media.codecs)) {
594                 ast_format_cap_copy(ast_channel_nativeformats(chan), session->endpoint->media.codecs);
595         } else {
596                 ast_format_cap_copy(ast_channel_nativeformats(chan), session->req_caps);
597         }
598
599         ast_codec_choose(&session->endpoint->media.prefs, ast_channel_nativeformats(chan), 1, &fmt);
600         ast_format_copy(ast_channel_writeformat(chan), &fmt);
601         ast_format_copy(ast_channel_rawwriteformat(chan), &fmt);
602         ast_format_copy(ast_channel_readformat(chan), &fmt);
603         ast_format_copy(ast_channel_rawreadformat(chan), &fmt);
604
605         if (state == AST_STATE_RING) {
606                 ast_channel_rings_set(chan, 1);
607         }
608
609         ast_channel_adsicpe_set(chan, AST_ADSI_UNAVAILABLE);
610
611         ast_channel_context_set(chan, session->endpoint->context);
612         ast_channel_exten_set(chan, S_OR(exten, "s"));
613         ast_channel_priority_set(chan, 1);
614
615         ast_channel_callgroup_set(chan, session->endpoint->pickup.callgroup);
616         ast_channel_pickupgroup_set(chan, session->endpoint->pickup.pickupgroup);
617
618         ast_channel_named_callgroups_set(chan, session->endpoint->pickup.named_callgroups);
619         ast_channel_named_pickupgroups_set(chan, session->endpoint->pickup.named_pickupgroups);
620
621         if (!ast_strlen_zero(session->endpoint->language)) {
622                 ast_channel_language_set(chan, session->endpoint->language);
623         }
624
625         if (!ast_strlen_zero(session->endpoint->zone)) {
626                 struct ast_tone_zone *zone = ast_get_indication_zone(session->endpoint->zone);
627                 if (!zone) {
628                         ast_log(LOG_ERROR, "Unknown country code '%s' for tonezone. Check indications.conf for available country codes.\n", session->endpoint->zone);
629                 }
630                 ast_channel_zone_set(chan, zone);
631         }
632
633         ast_endpoint_add_channel(session->endpoint->persistent, chan);
634
635         return chan;
636 }
637
638 static int answer(void *data)
639 {
640         pj_status_t status;
641         pjsip_tx_data *packet;
642         struct ast_sip_session *session = data;
643
644         if ((status = pjsip_inv_answer(session->inv_session, 200, NULL, NULL, &packet)) == PJ_SUCCESS) {
645                 ast_sip_session_send_response(session, packet);
646         }
647
648         ao2_ref(session, -1);
649
650         return (status == PJ_SUCCESS) ? 0 : -1;
651 }
652
653 /*! \brief Function called by core when we should answer a PJSIP session */
654 static int chan_pjsip_answer(struct ast_channel *ast)
655 {
656         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
657
658         if (ast_channel_state(ast) == AST_STATE_UP) {
659                 return 0;
660         }
661
662         ast_setstate(ast, AST_STATE_UP);
663
664         ao2_ref(channel->session, +1);
665         if (ast_sip_push_task(channel->session->serializer, answer, channel->session)) {
666                 ast_log(LOG_WARNING, "Unable to push answer task to the threadpool. Cannot answer call\n");
667                 ao2_cleanup(channel->session);
668                 return -1;
669         }
670
671         return 0;
672 }
673
674 /*! \brief Internal helper function called when CNG tone is detected */
675 static struct ast_frame *chan_pjsip_cng_tone_detected(struct ast_sip_session *session, struct ast_frame *f)
676 {
677         const char *target_context;
678         int exists;
679
680         /* If we only needed this DSP for fax detection purposes we can just drop it now */
681         if (session->endpoint->dtmf == AST_SIP_DTMF_INBAND) {
682                 ast_dsp_set_features(session->dsp, DSP_FEATURE_DIGIT_DETECT);
683         } else {
684                 ast_dsp_free(session->dsp);
685                 session->dsp = NULL;
686         }
687
688         /* If already executing in the fax extension don't do anything */
689         if (!strcmp(ast_channel_exten(session->channel), "fax")) {
690                 return f;
691         }
692
693         target_context = S_OR(ast_channel_macrocontext(session->channel), ast_channel_context(session->channel));
694
695         /* We need to unlock the channel here because ast_exists_extension has the
696          * potential to start and stop an autoservice on the channel. Such action
697          * is prone to deadlock if the channel is locked.
698          */
699         ast_channel_unlock(session->channel);
700         exists = ast_exists_extension(session->channel, target_context, "fax", 1,
701                 S_COR(ast_channel_caller(session->channel)->id.number.valid,
702                         ast_channel_caller(session->channel)->id.number.str, NULL));
703         ast_channel_lock(session->channel);
704
705         if (exists) {
706                 ast_verb(2, "Redirecting '%s' to fax extension due to CNG detection\n",
707                         ast_channel_name(session->channel));
708                 pbx_builtin_setvar_helper(session->channel, "FAXEXTEN", ast_channel_exten(session->channel));
709                 if (ast_async_goto(session->channel, target_context, "fax", 1)) {
710                         ast_log(LOG_ERROR, "Failed to async goto '%s' into fax extension in '%s'\n",
711                                 ast_channel_name(session->channel), target_context);
712                 }
713                 ast_frfree(f);
714                 f = &ast_null_frame;
715         } else {
716                 ast_log(LOG_NOTICE, "FAX CNG detected on '%s' but no fax extension in '%s'\n",
717                         ast_channel_name(session->channel), target_context);
718         }
719
720         return f;
721 }
722
723 /*! \brief Function called by core to read any waiting frames */
724 static struct ast_frame *chan_pjsip_read(struct ast_channel *ast)
725 {
726         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
727         struct chan_pjsip_pvt *pvt = channel->pvt;
728         struct ast_frame *f;
729         struct ast_sip_session_media *media = NULL;
730         int rtcp = 0;
731         int fdno = ast_channel_fdno(ast);
732
733         switch (fdno) {
734         case 0:
735                 media = pvt->media[SIP_MEDIA_AUDIO];
736                 break;
737         case 1:
738                 media = pvt->media[SIP_MEDIA_AUDIO];
739                 rtcp = 1;
740                 break;
741         case 2:
742                 media = pvt->media[SIP_MEDIA_VIDEO];
743                 break;
744         case 3:
745                 media = pvt->media[SIP_MEDIA_VIDEO];
746                 rtcp = 1;
747                 break;
748         }
749
750         if (!media || !media->rtp) {
751                 return &ast_null_frame;
752         }
753
754         if (!(f = ast_rtp_instance_read(media->rtp, rtcp))) {
755                 return f;
756         }
757
758         if (f->frametype != AST_FRAME_VOICE) {
759                 return f;
760         }
761
762         if (!(ast_format_cap_iscompatible(ast_channel_nativeformats(ast), &f->subclass.format))) {
763                 ast_debug(1, "Oooh, format changed to %s\n", ast_getformatname(&f->subclass.format));
764                 ast_format_cap_set(ast_channel_nativeformats(ast), &f->subclass.format);
765                 ast_set_read_format(ast, ast_channel_readformat(ast));
766                 ast_set_write_format(ast, ast_channel_writeformat(ast));
767         }
768
769         if (channel->session->dsp) {
770                 f = ast_dsp_process(ast, channel->session->dsp, f);
771
772                 if (f && (f->frametype == AST_FRAME_DTMF)) {
773                         if (f->subclass.integer == 'f') {
774                                 ast_debug(3, "Fax CNG detected on %s\n", ast_channel_name(ast));
775                                 f = chan_pjsip_cng_tone_detected(channel->session, f);
776                         } else {
777                                 ast_debug(3, "* Detected inband DTMF '%c' on '%s'\n", f->subclass.integer,
778                                         ast_channel_name(ast));
779                         }
780                 }
781         }
782
783         return f;
784 }
785
786 /*! \brief Function called by core to write frames */
787 static int chan_pjsip_write(struct ast_channel *ast, struct ast_frame *frame)
788 {
789         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
790         struct chan_pjsip_pvt *pvt = channel->pvt;
791         struct ast_sip_session_media *media;
792         int res = 0;
793
794         switch (frame->frametype) {
795         case AST_FRAME_VOICE:
796                 media = pvt->media[SIP_MEDIA_AUDIO];
797
798                 if (!media) {
799                         return 0;
800                 }
801                 if (!(ast_format_cap_iscompatible(ast_channel_nativeformats(ast), &frame->subclass.format))) {
802                         char buf[256];
803
804                         ast_log(LOG_WARNING,
805                                 "Asked to transmit frame type %s, while native formats is %s (read/write = %s/%s)\n",
806                                 ast_getformatname(&frame->subclass.format),
807                                 ast_getformatname_multiple(buf, sizeof(buf), ast_channel_nativeformats(ast)),
808                                 ast_getformatname(ast_channel_readformat(ast)),
809                                 ast_getformatname(ast_channel_writeformat(ast)));
810                         return 0;
811                 }
812                 if (media->rtp) {
813                         res = ast_rtp_instance_write(media->rtp, frame);
814                 }
815                 break;
816         case AST_FRAME_VIDEO:
817                 if ((media = pvt->media[SIP_MEDIA_VIDEO]) && media->rtp) {
818                         res = ast_rtp_instance_write(media->rtp, frame);
819                 }
820                 break;
821         case AST_FRAME_MODEM:
822                 break;
823         default:
824                 ast_log(LOG_WARNING, "Can't send %d type frames with PJSIP\n", frame->frametype);
825                 break;
826         }
827
828         return res;
829 }
830
831 struct fixup_data {
832         struct ast_sip_session *session;
833         struct ast_channel *chan;
834 };
835
836 static int fixup(void *data)
837 {
838         struct fixup_data *fix_data = data;
839         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(fix_data->chan);
840         struct chan_pjsip_pvt *pvt = channel->pvt;
841
842         channel->session->channel = fix_data->chan;
843         if (pvt->media[SIP_MEDIA_AUDIO] && pvt->media[SIP_MEDIA_AUDIO]->rtp) {
844                 ast_rtp_instance_set_channel_id(pvt->media[SIP_MEDIA_AUDIO]->rtp, ast_channel_uniqueid(fix_data->chan));
845         }
846         if (pvt->media[SIP_MEDIA_VIDEO] && pvt->media[SIP_MEDIA_VIDEO]->rtp) {
847                 ast_rtp_instance_set_channel_id(pvt->media[SIP_MEDIA_VIDEO]->rtp, ast_channel_uniqueid(fix_data->chan));
848         }
849
850         return 0;
851 }
852
853 /*! \brief Function called by core to change the underlying owner channel */
854 static int chan_pjsip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
855 {
856         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(newchan);
857         struct fixup_data fix_data;
858
859         fix_data.session = channel->session;
860         fix_data.chan = newchan;
861
862         if (channel->session->channel != oldchan) {
863                 return -1;
864         }
865
866         if (ast_sip_push_task_synchronous(channel->session->serializer, fixup, &fix_data)) {
867                 ast_log(LOG_WARNING, "Unable to perform channel fixup\n");
868                 return -1;
869         }
870
871         return 0;
872 }
873
874 /*! \brief Function called to get the device state of an endpoint */
875 static int chan_pjsip_devicestate(const char *data)
876 {
877         RAII_VAR(struct ast_sip_endpoint *, endpoint, ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint", data), ao2_cleanup);
878         enum ast_device_state state = AST_DEVICE_UNKNOWN;
879         RAII_VAR(struct ast_endpoint_snapshot *, endpoint_snapshot, NULL, ao2_cleanup);
880         RAII_VAR(struct stasis_cache *, cache, NULL, ao2_cleanup);
881         struct ast_devstate_aggregate aggregate;
882         int num, inuse = 0;
883
884         if (!endpoint) {
885                 return AST_DEVICE_INVALID;
886         }
887
888         endpoint_snapshot = ast_endpoint_latest_snapshot(ast_endpoint_get_tech(endpoint->persistent),
889                 ast_endpoint_get_resource(endpoint->persistent), 1);
890
891         if (endpoint_snapshot->state == AST_ENDPOINT_OFFLINE) {
892                 state = AST_DEVICE_UNAVAILABLE;
893         } else if (endpoint_snapshot->state == AST_ENDPOINT_ONLINE) {
894                 state = AST_DEVICE_NOT_INUSE;
895         }
896
897         if (!endpoint_snapshot->num_channels || !(cache = ast_channel_cache())) {
898                 return state;
899         }
900
901         ast_devstate_aggregate_init(&aggregate);
902
903         ao2_ref(cache, +1);
904
905         for (num = 0; num < endpoint_snapshot->num_channels; num++) {
906                 RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
907                 struct ast_channel_snapshot *snapshot;
908
909                 stasis_topic_wait(ast_channel_topic_all_cached());
910                 msg = stasis_cache_get(cache, ast_channel_snapshot_type(),
911                         endpoint_snapshot->channel_ids[num]);
912
913                 if (!msg) {
914                         continue;
915                 }
916
917                 snapshot = stasis_message_data(msg);
918
919                 if (snapshot->state == AST_STATE_DOWN) {
920                         ast_devstate_aggregate_add(&aggregate, AST_DEVICE_NOT_INUSE);
921                 } else if (snapshot->state == AST_STATE_RINGING) {
922                         ast_devstate_aggregate_add(&aggregate, AST_DEVICE_RINGING);
923                 } else if ((snapshot->state == AST_STATE_UP) || (snapshot->state == AST_STATE_RING) ||
924                         (snapshot->state == AST_STATE_BUSY)) {
925                         ast_devstate_aggregate_add(&aggregate, AST_DEVICE_INUSE);
926                         inuse++;
927                 }
928         }
929
930         if (endpoint->devicestate_busy_at && (inuse == endpoint->devicestate_busy_at)) {
931                 state = AST_DEVICE_BUSY;
932         } else if (ast_devstate_aggregate_result(&aggregate) != AST_DEVICE_INVALID) {
933                 state = ast_devstate_aggregate_result(&aggregate);
934         }
935
936         return state;
937 }
938
939 /*! \brief Function called to query options on a channel */
940 static int chan_pjsip_queryoption(struct ast_channel *ast, int option, void *data, int *datalen)
941 {
942         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
943         struct ast_sip_session *session = channel->session;
944         int res = -1;
945         enum ast_sip_session_t38state state = T38_STATE_UNAVAILABLE;
946
947         switch (option) {
948         case AST_OPTION_T38_STATE:
949                 if (session->endpoint->media.t38.enabled) {
950                         switch (session->t38state) {
951                         case T38_LOCAL_REINVITE:
952                         case T38_PEER_REINVITE:
953                                 state = T38_STATE_NEGOTIATING;
954                                 break;
955                         case T38_ENABLED:
956                                 state = T38_STATE_NEGOTIATED;
957                                 break;
958                         case T38_REJECTED:
959                                 state = T38_STATE_REJECTED;
960                                 break;
961                         default:
962                                 state = T38_STATE_UNKNOWN;
963                                 break;
964                         }
965                 }
966
967                 *((enum ast_t38_state *) data) = state;
968                 res = 0;
969
970                 break;
971         default:
972                 break;
973         }
974
975         return res;
976 }
977
978 struct indicate_data {
979         struct ast_sip_session *session;
980         int condition;
981         int response_code;
982         void *frame_data;
983         size_t datalen;
984 };
985
986 static void indicate_data_destroy(void *obj)
987 {
988         struct indicate_data *ind_data = obj;
989
990         ast_free(ind_data->frame_data);
991         ao2_ref(ind_data->session, -1);
992 }
993
994 static struct indicate_data *indicate_data_alloc(struct ast_sip_session *session,
995                 int condition, int response_code, const void *frame_data, size_t datalen)
996 {
997         struct indicate_data *ind_data = ao2_alloc(sizeof(*ind_data), indicate_data_destroy);
998
999         if (!ind_data) {
1000                 return NULL;
1001         }
1002
1003         ind_data->frame_data = ast_malloc(datalen);
1004         if (!ind_data->frame_data) {
1005                 ao2_ref(ind_data, -1);
1006                 return NULL;
1007         }
1008
1009         memcpy(ind_data->frame_data, frame_data, datalen);
1010         ind_data->datalen = datalen;
1011         ind_data->condition = condition;
1012         ind_data->response_code = response_code;
1013         ao2_ref(session, +1);
1014         ind_data->session = session;
1015
1016         return ind_data;
1017 }
1018
1019 static int indicate(void *data)
1020 {
1021         pjsip_tx_data *packet = NULL;
1022         struct indicate_data *ind_data = data;
1023         struct ast_sip_session *session = ind_data->session;
1024         int response_code = ind_data->response_code;
1025
1026         if (pjsip_inv_answer(session->inv_session, response_code, NULL, NULL, &packet) == PJ_SUCCESS) {
1027                 ast_sip_session_send_response(session, packet);
1028         }
1029
1030         ao2_ref(ind_data, -1);
1031
1032         return 0;
1033 }
1034
1035 /*! \brief Send SIP INFO with video update request */
1036 static int transmit_info_with_vidupdate(void *data)
1037 {
1038         const char * xml =
1039                 "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
1040                 " <media_control>\r\n"
1041                 "  <vc_primitive>\r\n"
1042                 "   <to_encoder>\r\n"
1043                 "    <picture_fast_update/>\r\n"
1044                 "   </to_encoder>\r\n"
1045                 "  </vc_primitive>\r\n"
1046                 " </media_control>\r\n";
1047
1048         const struct ast_sip_body body = {
1049                 .type = "application",
1050                 .subtype = "media_control+xml",
1051                 .body_text = xml
1052         };
1053
1054         RAII_VAR(struct ast_sip_session *, session, data, ao2_cleanup);
1055         struct pjsip_tx_data *tdata;
1056
1057         if (ast_sip_create_request("INFO", session->inv_session->dlg, session->endpoint, NULL, &tdata)) {
1058                 ast_log(LOG_ERROR, "Could not create text video update INFO request\n");
1059                 return -1;
1060         }
1061         if (ast_sip_add_body(tdata, &body)) {
1062                 ast_log(LOG_ERROR, "Could not add body to text video update INFO request\n");
1063                 return -1;
1064         }
1065         ast_sip_session_send_request(session, tdata);
1066
1067         return 0;
1068 }
1069
1070 /*! \brief Update connected line information */
1071 static int update_connected_line_information(void *data)
1072 {
1073         RAII_VAR(struct ast_sip_session *, session, data, ao2_cleanup);
1074
1075         if ((ast_channel_state(session->channel) != AST_STATE_UP) && (session->inv_session->role == PJSIP_UAS_ROLE)) {
1076                 int response_code = 0;
1077
1078                 if (ast_channel_state(session->channel) == AST_STATE_RING) {
1079                         response_code = !session->endpoint->inband_progress ? 180 : 183;
1080                 } else if (ast_channel_state(session->channel) == AST_STATE_RINGING) {
1081                         response_code = 183;
1082                 }
1083
1084                 if (response_code) {
1085                         struct pjsip_tx_data *packet = NULL;
1086
1087                         if (pjsip_inv_answer(session->inv_session, response_code, NULL, NULL, &packet) == PJ_SUCCESS) {
1088                                 ast_sip_session_send_response(session, packet);
1089                         }
1090                 }
1091         } else {
1092                 enum ast_sip_session_refresh_method method = session->endpoint->id.refresh_method;
1093
1094                 if (session->inv_session->invite_tsx && (session->inv_session->options & PJSIP_INV_SUPPORT_UPDATE)) {
1095                         method = AST_SIP_SESSION_REFRESH_METHOD_UPDATE;
1096                 }
1097
1098                 ast_sip_session_refresh(session, NULL, NULL, NULL, method, 0);
1099         }
1100
1101         return 0;
1102 }
1103
1104 /*! \brief Function called by core to ask the channel to indicate some sort of condition */
1105 static int chan_pjsip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
1106 {
1107         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
1108         struct chan_pjsip_pvt *pvt = channel->pvt;
1109         struct ast_sip_session_media *media;
1110         int response_code = 0;
1111         int res = 0;
1112
1113         switch (condition) {
1114         case AST_CONTROL_RINGING:
1115                 if (ast_channel_state(ast) == AST_STATE_RING) {
1116                         if (channel->session->endpoint->inband_progress) {
1117                                 response_code = 183;
1118                                 res = -1;
1119                         } else {
1120                                 response_code = 180;
1121                         }
1122                 } else {
1123                         res = -1;
1124                 }
1125                 ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "PJSIP/%s", ast_sorcery_object_get_id(channel->session->endpoint));
1126                 break;
1127         case AST_CONTROL_BUSY:
1128                 if (ast_channel_state(ast) != AST_STATE_UP) {
1129                         response_code = 486;
1130                 } else {
1131                         res = -1;
1132                 }
1133                 break;
1134         case AST_CONTROL_CONGESTION:
1135                 if (ast_channel_state(ast) != AST_STATE_UP) {
1136                         response_code = 503;
1137                 } else {
1138                         res = -1;
1139                 }
1140                 break;
1141         case AST_CONTROL_INCOMPLETE:
1142                 if (ast_channel_state(ast) != AST_STATE_UP) {
1143                         response_code = 484;
1144                 } else {
1145                         res = -1;
1146                 }
1147                 break;
1148         case AST_CONTROL_PROCEEDING:
1149                 if (ast_channel_state(ast) != AST_STATE_UP) {
1150                         response_code = 100;
1151                 } else {
1152                         res = -1;
1153                 }
1154                 break;
1155         case AST_CONTROL_PROGRESS:
1156                 if (ast_channel_state(ast) != AST_STATE_UP) {
1157                         response_code = 183;
1158                 } else {
1159                         res = -1;
1160                 }
1161                 break;
1162         case AST_CONTROL_VIDUPDATE:
1163                 media = pvt->media[SIP_MEDIA_VIDEO];
1164                 if (media && media->rtp) {
1165                         ao2_ref(channel->session, +1);
1166
1167                         if (ast_sip_push_task(channel->session->serializer, transmit_info_with_vidupdate, channel->session)) {
1168                                 ao2_cleanup(channel->session);
1169                         }
1170                 } else {
1171                         res = -1;
1172                 }
1173                 break;
1174         case AST_CONTROL_CONNECTED_LINE:
1175                 ao2_ref(channel->session, +1);
1176                 if (ast_sip_push_task(channel->session->serializer, update_connected_line_information, channel->session)) {
1177                         ao2_cleanup(channel->session);
1178                 }
1179                 break;
1180         case AST_CONTROL_UPDATE_RTP_PEER:
1181                 break;
1182         case AST_CONTROL_PVT_CAUSE_CODE:
1183                 res = -1;
1184                 break;
1185         case AST_CONTROL_HOLD:
1186                 ast_moh_start(ast, data, NULL);
1187                 break;
1188         case AST_CONTROL_UNHOLD:
1189                 ast_moh_stop(ast);
1190                 break;
1191         case AST_CONTROL_SRCUPDATE:
1192                 break;
1193         case AST_CONTROL_SRCCHANGE:
1194                 break;
1195         case AST_CONTROL_REDIRECTING:
1196                 if (ast_channel_state(ast) != AST_STATE_UP) {
1197                         response_code = 181;
1198                 } else {
1199                         res = -1;
1200                 }
1201                 break;
1202         case AST_CONTROL_T38_PARAMETERS:
1203                 res = 0;
1204
1205                 if (channel->session->t38state == T38_PEER_REINVITE) {
1206                         const struct ast_control_t38_parameters *parameters = data;
1207
1208                         if (parameters->request_response == AST_T38_REQUEST_PARMS) {
1209                                 res = AST_T38_REQUEST_PARMS;
1210                         }
1211                 }
1212
1213                 break;
1214         case -1:
1215                 res = -1;
1216                 break;
1217         default:
1218                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
1219                 res = -1;
1220                 break;
1221         }
1222
1223         if (response_code) {
1224                 struct indicate_data *ind_data = indicate_data_alloc(channel->session, condition, response_code, data, datalen);
1225                 if (!ind_data || ast_sip_push_task(channel->session->serializer, indicate, ind_data)) {
1226                         ast_log(LOG_NOTICE, "Cannot send response code %d to endpoint %s. Could not queue task properly\n",
1227                                         response_code, ast_sorcery_object_get_id(channel->session->endpoint));
1228                         ao2_cleanup(ind_data);
1229                         res = -1;
1230                 }
1231         }
1232
1233         return res;
1234 }
1235
1236 struct transfer_data {
1237         struct ast_sip_session *session;
1238         char *target;
1239 };
1240
1241 static void transfer_data_destroy(void *obj)
1242 {
1243         struct transfer_data *trnf_data = obj;
1244
1245         ast_free(trnf_data->target);
1246         ao2_cleanup(trnf_data->session);
1247 }
1248
1249 static struct transfer_data *transfer_data_alloc(struct ast_sip_session *session, const char *target)
1250 {
1251         struct transfer_data *trnf_data = ao2_alloc(sizeof(*trnf_data), transfer_data_destroy);
1252
1253         if (!trnf_data) {
1254                 return NULL;
1255         }
1256
1257         if (!(trnf_data->target = ast_strdup(target))) {
1258                 ao2_ref(trnf_data, -1);
1259                 return NULL;
1260         }
1261
1262         ao2_ref(session, +1);
1263         trnf_data->session = session;
1264
1265         return trnf_data;
1266 }
1267
1268 static void transfer_redirect(struct ast_sip_session *session, const char *target)
1269 {
1270         pjsip_tx_data *packet;
1271         enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
1272         pjsip_contact_hdr *contact;
1273         pj_str_t tmp;
1274
1275         if (pjsip_inv_end_session(session->inv_session, 302, NULL, &packet) != PJ_SUCCESS) {
1276                 message = AST_TRANSFER_FAILED;
1277                 ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1278
1279                 return;
1280         }
1281
1282         if (!(contact = pjsip_msg_find_hdr(packet->msg, PJSIP_H_CONTACT, NULL))) {
1283                 contact = pjsip_contact_hdr_create(packet->pool);
1284         }
1285
1286         pj_strdup2_with_null(packet->pool, &tmp, target);
1287         if (!(contact->uri = pjsip_parse_uri(packet->pool, tmp.ptr, tmp.slen, PJSIP_PARSE_URI_AS_NAMEADDR))) {
1288                 message = AST_TRANSFER_FAILED;
1289                 ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1290                 pjsip_tx_data_dec_ref(packet);
1291
1292                 return;
1293         }
1294         pjsip_msg_add_hdr(packet->msg, (pjsip_hdr *) contact);
1295
1296         ast_sip_session_send_response(session, packet);
1297         ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1298 }
1299
1300 static void transfer_refer(struct ast_sip_session *session, const char *target)
1301 {
1302         pjsip_evsub *sub;
1303         enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
1304         pj_str_t tmp;
1305         pjsip_tx_data *packet;
1306
1307         if (pjsip_xfer_create_uac(session->inv_session->dlg, NULL, &sub) != PJ_SUCCESS) {
1308                 message = AST_TRANSFER_FAILED;
1309                 ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1310
1311                 return;
1312         }
1313
1314         if (pjsip_xfer_initiate(sub, pj_cstr(&tmp, target), &packet) != PJ_SUCCESS) {
1315                 message = AST_TRANSFER_FAILED;
1316                 ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1317                 pjsip_evsub_terminate(sub, PJ_FALSE);
1318
1319                 return;
1320         }
1321
1322         pjsip_xfer_send_request(sub, packet);
1323         ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1324 }
1325
1326 static int transfer(void *data)
1327 {
1328         struct transfer_data *trnf_data = data;
1329
1330         if (ast_channel_state(trnf_data->session->channel) == AST_STATE_RING) {
1331                 transfer_redirect(trnf_data->session, trnf_data->target);
1332         } else {
1333                 transfer_refer(trnf_data->session, trnf_data->target);
1334         }
1335
1336         ao2_ref(trnf_data, -1);
1337         return 0;
1338 }
1339
1340 /*! \brief Function called by core for Asterisk initiated transfer */
1341 static int chan_pjsip_transfer(struct ast_channel *chan, const char *target)
1342 {
1343         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
1344         struct transfer_data *trnf_data = transfer_data_alloc(channel->session, target);
1345
1346         if (!trnf_data) {
1347                 return -1;
1348         }
1349
1350         if (ast_sip_push_task(channel->session->serializer, transfer, trnf_data)) {
1351                 ast_log(LOG_WARNING, "Error requesting transfer\n");
1352                 ao2_cleanup(trnf_data);
1353                 return -1;
1354         }
1355
1356         return 0;
1357 }
1358
1359 /*! \brief Function called by core to start a DTMF digit */
1360 static int chan_pjsip_digit_begin(struct ast_channel *chan, char digit)
1361 {
1362         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
1363         struct chan_pjsip_pvt *pvt = channel->pvt;
1364         struct ast_sip_session_media *media = pvt->media[SIP_MEDIA_AUDIO];
1365         int res = 0;
1366
1367         switch (channel->session->endpoint->dtmf) {
1368         case AST_SIP_DTMF_RFC_4733:
1369                 if (!media || !media->rtp) {
1370                         return -1;
1371                 }
1372
1373                 ast_rtp_instance_dtmf_begin(media->rtp, digit);
1374         case AST_SIP_DTMF_NONE:
1375                 break;
1376         case AST_SIP_DTMF_INBAND:
1377                 res = -1;
1378                 break;
1379         default:
1380                 break;
1381         }
1382
1383         return res;
1384 }
1385
1386 struct info_dtmf_data {
1387         struct ast_sip_session *session;
1388         char digit;
1389         unsigned int duration;
1390 };
1391
1392 static void info_dtmf_data_destroy(void *obj)
1393 {
1394         struct info_dtmf_data *dtmf_data = obj;
1395         ao2_ref(dtmf_data->session, -1);
1396 }
1397
1398 static struct info_dtmf_data *info_dtmf_data_alloc(struct ast_sip_session *session, char digit, unsigned int duration)
1399 {
1400         struct info_dtmf_data *dtmf_data = ao2_alloc(sizeof(*dtmf_data), info_dtmf_data_destroy);
1401         if (!dtmf_data) {
1402                 return NULL;
1403         }
1404         ao2_ref(session, +1);
1405         dtmf_data->session = session;
1406         dtmf_data->digit = digit;
1407         dtmf_data->duration = duration;
1408         return dtmf_data;
1409 }
1410
1411 static int transmit_info_dtmf(void *data)
1412 {
1413         RAII_VAR(struct info_dtmf_data *, dtmf_data, data, ao2_cleanup);
1414
1415         struct ast_sip_session *session = dtmf_data->session;
1416         struct pjsip_tx_data *tdata;
1417
1418         RAII_VAR(struct ast_str *, body_text, NULL, ast_free_ptr);
1419
1420         struct ast_sip_body body = {
1421                 .type = "application",
1422                 .subtype = "dtmf-relay",
1423         };
1424
1425         if (!(body_text = ast_str_create(32))) {
1426                 ast_log(LOG_ERROR, "Could not allocate buffer for INFO DTMF.\n");
1427                 return -1;
1428         }
1429         ast_str_set(&body_text, 0, "Signal=%c\r\nDuration=%u\r\n", dtmf_data->digit, dtmf_data->duration);
1430
1431         body.body_text = ast_str_buffer(body_text);
1432
1433         if (ast_sip_create_request("INFO", session->inv_session->dlg, session->endpoint, NULL, &tdata)) {
1434                 ast_log(LOG_ERROR, "Could not create DTMF INFO request\n");
1435                 return -1;
1436         }
1437         if (ast_sip_add_body(tdata, &body)) {
1438                 ast_log(LOG_ERROR, "Could not add body to DTMF INFO request\n");
1439                 pjsip_tx_data_dec_ref(tdata);
1440                 return -1;
1441         }
1442         ast_sip_session_send_request(session, tdata);
1443
1444         return 0;
1445 }
1446
1447 /*! \brief Function called by core to stop a DTMF digit */
1448 static int chan_pjsip_digit_end(struct ast_channel *ast, char digit, unsigned int duration)
1449 {
1450         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
1451         struct chan_pjsip_pvt *pvt = channel->pvt;
1452         struct ast_sip_session_media *media = pvt->media[SIP_MEDIA_AUDIO];
1453         int res = 0;
1454
1455         switch (channel->session->endpoint->dtmf) {
1456         case AST_SIP_DTMF_INFO:
1457         {
1458                 struct info_dtmf_data *dtmf_data = info_dtmf_data_alloc(channel->session, digit, duration);
1459
1460                 if (!dtmf_data) {
1461                         return -1;
1462                 }
1463
1464                 if (ast_sip_push_task(channel->session->serializer, transmit_info_dtmf, dtmf_data)) {
1465                         ast_log(LOG_WARNING, "Error sending DTMF via INFO.\n");
1466                         ao2_cleanup(dtmf_data);
1467                         return -1;
1468                 }
1469                 break;
1470         }
1471         case AST_SIP_DTMF_RFC_4733:
1472                 if (!media || !media->rtp) {
1473                         return -1;
1474                 }
1475
1476                 ast_rtp_instance_dtmf_end_with_duration(media->rtp, digit, duration);
1477         case AST_SIP_DTMF_NONE:
1478                 break;
1479         case AST_SIP_DTMF_INBAND:
1480                 res = -1;
1481                 break;
1482         }
1483
1484         return res;
1485 }
1486
1487 static int call(void *data)
1488 {
1489         struct ast_sip_session *session = data;
1490         pjsip_tx_data *tdata;
1491
1492         int res = ast_sip_session_create_invite(session, &tdata);
1493
1494         if (res) {
1495                 ast_queue_hangup(session->channel);
1496         } else {
1497                 ast_sip_session_send_request(session, tdata);
1498         }
1499         ao2_ref(session, -1);
1500         return res;
1501 }
1502
1503 /*! \brief Function called by core to actually start calling a remote party */
1504 static int chan_pjsip_call(struct ast_channel *ast, const char *dest, int timeout)
1505 {
1506         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
1507
1508         ao2_ref(channel->session, +1);
1509         if (ast_sip_push_task(channel->session->serializer, call, channel->session)) {
1510                 ast_log(LOG_WARNING, "Error attempting to place outbound call to call '%s'\n", dest);
1511                 ao2_cleanup(channel->session);
1512                 return -1;
1513         }
1514
1515         return 0;
1516 }
1517
1518 /*! \brief Internal function which translates from Asterisk cause codes to SIP response codes */
1519 static int hangup_cause2sip(int cause)
1520 {
1521         switch (cause) {
1522         case AST_CAUSE_UNALLOCATED:             /* 1 */
1523         case AST_CAUSE_NO_ROUTE_DESTINATION:    /* 3 IAX2: Can't find extension in context */
1524         case AST_CAUSE_NO_ROUTE_TRANSIT_NET:    /* 2 */
1525                 return 404;
1526         case AST_CAUSE_CONGESTION:              /* 34 */
1527         case AST_CAUSE_SWITCH_CONGESTION:       /* 42 */
1528                 return 503;
1529         case AST_CAUSE_NO_USER_RESPONSE:        /* 18 */
1530                 return 408;
1531         case AST_CAUSE_NO_ANSWER:               /* 19 */
1532         case AST_CAUSE_UNREGISTERED:        /* 20 */
1533                 return 480;
1534         case AST_CAUSE_CALL_REJECTED:           /* 21 */
1535                 return 403;
1536         case AST_CAUSE_NUMBER_CHANGED:          /* 22 */
1537                 return 410;
1538         case AST_CAUSE_NORMAL_UNSPECIFIED:      /* 31 */
1539                 return 480;
1540         case AST_CAUSE_INVALID_NUMBER_FORMAT:
1541                 return 484;
1542         case AST_CAUSE_USER_BUSY:
1543                 return 486;
1544         case AST_CAUSE_FAILURE:
1545                 return 500;
1546         case AST_CAUSE_FACILITY_REJECTED:       /* 29 */
1547                 return 501;
1548         case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
1549                 return 503;
1550         case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
1551                 return 502;
1552         case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL:       /* Can't find codec to connect to host */
1553                 return 488;
1554         case AST_CAUSE_INTERWORKING:    /* Unspecified Interworking issues */
1555                 return 500;
1556         case AST_CAUSE_NOTDEFINED:
1557         default:
1558                 ast_debug(1, "AST hangup cause %d (no match found in PJSIP)\n", cause);
1559                 return 0;
1560         }
1561
1562         /* Never reached */
1563         return 0;
1564 }
1565
1566 struct hangup_data {
1567         int cause;
1568         struct ast_channel *chan;
1569 };
1570
1571 static void hangup_data_destroy(void *obj)
1572 {
1573         struct hangup_data *h_data = obj;
1574
1575         h_data->chan = ast_channel_unref(h_data->chan);
1576 }
1577
1578 static struct hangup_data *hangup_data_alloc(int cause, struct ast_channel *chan)
1579 {
1580         struct hangup_data *h_data = ao2_alloc(sizeof(*h_data), hangup_data_destroy);
1581
1582         if (!h_data) {
1583                 return NULL;
1584         }
1585
1586         h_data->cause = cause;
1587         h_data->chan = ast_channel_ref(chan);
1588
1589         return h_data;
1590 }
1591
1592 /*! \brief Clear a channel from a session along with its PVT */
1593 static void clear_session_and_channel(struct ast_sip_session *session, struct ast_channel *ast, struct chan_pjsip_pvt *pvt)
1594 {
1595         session->channel = NULL;
1596         if (pvt->media[SIP_MEDIA_AUDIO] && pvt->media[SIP_MEDIA_AUDIO]->rtp) {
1597                 ast_rtp_instance_set_channel_id(pvt->media[SIP_MEDIA_AUDIO]->rtp, "");
1598         }
1599         if (pvt->media[SIP_MEDIA_VIDEO] && pvt->media[SIP_MEDIA_VIDEO]->rtp) {
1600                 ast_rtp_instance_set_channel_id(pvt->media[SIP_MEDIA_VIDEO]->rtp, "");
1601         }
1602         ast_channel_tech_pvt_set(ast, NULL);
1603 }
1604
1605 static int hangup(void *data)
1606 {
1607         pj_status_t status;
1608         pjsip_tx_data *packet = NULL;
1609         struct hangup_data *h_data = data;
1610         struct ast_channel *ast = h_data->chan;
1611         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
1612         struct chan_pjsip_pvt *pvt = channel->pvt;
1613         struct ast_sip_session *session = channel->session;
1614         int cause = h_data->cause;
1615
1616         if (!session->defer_terminate &&
1617                 ((status = pjsip_inv_end_session(session->inv_session, cause ? cause : 603, NULL, &packet)) == PJ_SUCCESS) && packet) {
1618                 if (packet->msg->type == PJSIP_RESPONSE_MSG) {
1619                         ast_sip_session_send_response(session, packet);
1620                 } else {
1621                         ast_sip_session_send_request(session, packet);
1622                 }
1623         }
1624
1625         clear_session_and_channel(session, ast, pvt);
1626         ao2_cleanup(channel);
1627         ao2_cleanup(h_data);
1628
1629         return 0;
1630 }
1631
1632 /*! \brief Function called by core to hang up a PJSIP session */
1633 static int chan_pjsip_hangup(struct ast_channel *ast)
1634 {
1635         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
1636         struct chan_pjsip_pvt *pvt = channel->pvt;
1637         int cause = hangup_cause2sip(ast_channel_hangupcause(channel->session->channel));
1638         struct hangup_data *h_data = hangup_data_alloc(cause, ast);
1639
1640         if (!h_data) {
1641                 goto failure;
1642         }
1643
1644         if (ast_sip_push_task(channel->session->serializer, hangup, h_data)) {
1645                 ast_log(LOG_WARNING, "Unable to push hangup task to the threadpool. Expect bad things\n");
1646                 goto failure;
1647         }
1648
1649         return 0;
1650
1651 failure:
1652         /* Go ahead and do our cleanup of the session and channel even if we're not going
1653          * to be able to send our SIP request/response
1654          */
1655         clear_session_and_channel(channel->session, ast, pvt);
1656         ao2_cleanup(channel);
1657         ao2_cleanup(h_data);
1658
1659         return -1;
1660 }
1661
1662 struct request_data {
1663         struct ast_sip_session *session;
1664         struct ast_format_cap *caps;
1665         const char *dest;
1666         int cause;
1667 };
1668
1669 static int request(void *obj)
1670 {
1671         struct request_data *req_data = obj;
1672         struct ast_sip_session *session = NULL;
1673         char *tmp = ast_strdupa(req_data->dest), *endpoint_name = NULL, *request_user = NULL;
1674         RAII_VAR(struct ast_sip_endpoint *, endpoint, NULL, ao2_cleanup);
1675
1676         AST_DECLARE_APP_ARGS(args,
1677                 AST_APP_ARG(endpoint);
1678                 AST_APP_ARG(aor);
1679         );
1680
1681         if (ast_strlen_zero(tmp)) {
1682                 ast_log(LOG_ERROR, "Unable to create PJSIP channel with empty destination\n");
1683                 req_data->cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
1684                 return -1;
1685         }
1686
1687         AST_NONSTANDARD_APP_ARGS(args, tmp, '/');
1688
1689         /* If a request user has been specified extract it from the endpoint name portion */
1690         if ((endpoint_name = strchr(args.endpoint, '@'))) {
1691                 request_user = args.endpoint;
1692                 *endpoint_name++ = '\0';
1693         } else {
1694                 endpoint_name = args.endpoint;
1695         }
1696
1697         if (ast_strlen_zero(endpoint_name)) {
1698                 ast_log(LOG_ERROR, "Unable to create PJSIP channel with empty endpoint name\n");
1699                 req_data->cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
1700         } else if (!(endpoint = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint", endpoint_name))) {
1701                 ast_log(LOG_ERROR, "Unable to create PJSIP channel - endpoint '%s' was not found\n", endpoint_name);
1702                 req_data->cause = AST_CAUSE_NO_ROUTE_DESTINATION;
1703                 return -1;
1704         }
1705
1706         if (!(session = ast_sip_session_create_outgoing(endpoint, args.aor, request_user, req_data->caps))) {
1707                 req_data->cause = AST_CAUSE_NO_ROUTE_DESTINATION;
1708                 return -1;
1709         }
1710
1711         req_data->session = session;
1712
1713         return 0;
1714 }
1715
1716 /*! \brief Function called by core to create a new outgoing PJSIP session */
1717 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)
1718 {
1719         struct request_data req_data;
1720         RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);
1721
1722         req_data.caps = cap;
1723         req_data.dest = data;
1724
1725         if (ast_sip_push_task_synchronous(NULL, request, &req_data)) {
1726                 *cause = req_data.cause;
1727                 return NULL;
1728         }
1729
1730         session = req_data.session;
1731
1732         if (!(session->channel = chan_pjsip_new(session, AST_STATE_DOWN, NULL, NULL, requestor ? ast_channel_linkedid(requestor) : NULL, NULL))) {
1733                 /* Session needs to be terminated prematurely */
1734                 return NULL;
1735         }
1736
1737         return session->channel;
1738 }
1739
1740 struct sendtext_data {
1741         struct ast_sip_session *session;
1742         char text[0];
1743 };
1744
1745 static void sendtext_data_destroy(void *obj)
1746 {
1747         struct sendtext_data *data = obj;
1748         ao2_ref(data->session, -1);
1749 }
1750
1751 static struct sendtext_data* sendtext_data_create(struct ast_sip_session *session, const char *text)
1752 {
1753         int size = strlen(text) + 1;
1754         struct sendtext_data *data = ao2_alloc(sizeof(*data)+size, sendtext_data_destroy);
1755
1756         if (!data) {
1757                 return NULL;
1758         }
1759
1760         data->session = session;
1761         ao2_ref(data->session, +1);
1762         ast_copy_string(data->text, text, size);
1763         return data;
1764 }
1765
1766 static int sendtext(void *obj)
1767 {
1768         RAII_VAR(struct sendtext_data *, data, obj, ao2_cleanup);
1769         pjsip_tx_data *tdata;
1770
1771         const struct ast_sip_body body = {
1772                 .type = "text",
1773                 .subtype = "plain",
1774                 .body_text = data->text
1775         };
1776
1777         /* NOT ast_strlen_zero, because a zero-length message is specifically
1778          * allowed by RFC 3428 (See section 10, Examples) */
1779         if (!data->text) {
1780                 return 0;
1781         }
1782
1783         ast_sip_create_request("MESSAGE", data->session->inv_session->dlg, data->session->endpoint, NULL, &tdata);
1784         ast_sip_add_body(tdata, &body);
1785         ast_sip_send_request(tdata, data->session->inv_session->dlg, data->session->endpoint);
1786
1787         return 0;
1788 }
1789
1790 /*! \brief Function called by core to send text on PJSIP session */
1791 static int chan_pjsip_sendtext(struct ast_channel *ast, const char *text)
1792 {
1793         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
1794         struct sendtext_data *data = sendtext_data_create(channel->session, text);
1795
1796         if (!data || ast_sip_push_task(channel->session->serializer, sendtext, data)) {
1797                 ao2_ref(data, -1);
1798                 return -1;
1799         }
1800         return 0;
1801 }
1802
1803 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
1804 static int hangup_sip2cause(int cause)
1805 {
1806         /* Possible values taken from causes.h */
1807
1808         switch(cause) {
1809         case 401:       /* Unauthorized */
1810                 return AST_CAUSE_CALL_REJECTED;
1811         case 403:       /* Not found */
1812                 return AST_CAUSE_CALL_REJECTED;
1813         case 404:       /* Not found */
1814                 return AST_CAUSE_UNALLOCATED;
1815         case 405:       /* Method not allowed */
1816                 return AST_CAUSE_INTERWORKING;
1817         case 407:       /* Proxy authentication required */
1818                 return AST_CAUSE_CALL_REJECTED;
1819         case 408:       /* No reaction */
1820                 return AST_CAUSE_NO_USER_RESPONSE;
1821         case 409:       /* Conflict */
1822                 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
1823         case 410:       /* Gone */
1824                 return AST_CAUSE_NUMBER_CHANGED;
1825         case 411:       /* Length required */
1826                 return AST_CAUSE_INTERWORKING;
1827         case 413:       /* Request entity too large */
1828                 return AST_CAUSE_INTERWORKING;
1829         case 414:       /* Request URI too large */
1830                 return AST_CAUSE_INTERWORKING;
1831         case 415:       /* Unsupported media type */
1832                 return AST_CAUSE_INTERWORKING;
1833         case 420:       /* Bad extension */
1834                 return AST_CAUSE_NO_ROUTE_DESTINATION;
1835         case 480:       /* No answer */
1836                 return AST_CAUSE_NO_ANSWER;
1837         case 481:       /* No answer */
1838                 return AST_CAUSE_INTERWORKING;
1839         case 482:       /* Loop detected */
1840                 return AST_CAUSE_INTERWORKING;
1841         case 483:       /* Too many hops */
1842                 return AST_CAUSE_NO_ANSWER;
1843         case 484:       /* Address incomplete */
1844                 return AST_CAUSE_INVALID_NUMBER_FORMAT;
1845         case 485:       /* Ambiguous */
1846                 return AST_CAUSE_UNALLOCATED;
1847         case 486:       /* Busy everywhere */
1848                 return AST_CAUSE_BUSY;
1849         case 487:       /* Request terminated */
1850                 return AST_CAUSE_INTERWORKING;
1851         case 488:       /* No codecs approved */
1852                 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
1853         case 491:       /* Request pending */
1854                 return AST_CAUSE_INTERWORKING;
1855         case 493:       /* Undecipherable */
1856                 return AST_CAUSE_INTERWORKING;
1857         case 500:       /* Server internal failure */
1858                 return AST_CAUSE_FAILURE;
1859         case 501:       /* Call rejected */
1860                 return AST_CAUSE_FACILITY_REJECTED;
1861         case 502:
1862                 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
1863         case 503:       /* Service unavailable */
1864                 return AST_CAUSE_CONGESTION;
1865         case 504:       /* Gateway timeout */
1866                 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
1867         case 505:       /* SIP version not supported */
1868                 return AST_CAUSE_INTERWORKING;
1869         case 600:       /* Busy everywhere */
1870                 return AST_CAUSE_USER_BUSY;
1871         case 603:       /* Decline */
1872                 return AST_CAUSE_CALL_REJECTED;
1873         case 604:       /* Does not exist anywhere */
1874                 return AST_CAUSE_UNALLOCATED;
1875         case 606:       /* Not acceptable */
1876                 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
1877         default:
1878                 if (cause < 500 && cause >= 400) {
1879                         /* 4xx class error that is unknown - someting wrong with our request */
1880                         return AST_CAUSE_INTERWORKING;
1881                 } else if (cause < 600 && cause >= 500) {
1882                         /* 5xx class error - problem in the remote end */
1883                         return AST_CAUSE_CONGESTION;
1884                 } else if (cause < 700 && cause >= 600) {
1885                         /* 6xx - global errors in the 4xx class */
1886                         return AST_CAUSE_INTERWORKING;
1887                 }
1888                 return AST_CAUSE_NORMAL;
1889         }
1890         /* Never reached */
1891         return 0;
1892 }
1893
1894 static void chan_pjsip_session_begin(struct ast_sip_session *session)
1895 {
1896         RAII_VAR(struct ast_datastore *, datastore, NULL, ao2_cleanup);
1897
1898         if (session->endpoint->media.direct_media.glare_mitigation ==
1899                         AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_NONE) {
1900                 return;
1901         }
1902
1903         datastore = ast_sip_session_alloc_datastore(&direct_media_mitigation_info,
1904                         "direct_media_glare_mitigation");
1905
1906         if (!datastore) {
1907                 return;
1908         }
1909
1910         ast_sip_session_add_datastore(session, datastore);
1911 }
1912
1913 /*! \brief Function called when the session ends */
1914 static void chan_pjsip_session_end(struct ast_sip_session *session)
1915 {
1916         if (!session->channel) {
1917                 return;
1918         }
1919
1920         if (!ast_channel_hangupcause(session->channel) && session->inv_session) {
1921                 int cause = hangup_sip2cause(session->inv_session->cause);
1922
1923                 ast_queue_hangup_with_cause(session->channel, cause);
1924         } else {
1925                 ast_queue_hangup(session->channel);
1926         }
1927 }
1928
1929 /*! \brief Function called when a request is received on the session */
1930 static int chan_pjsip_incoming_request(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
1931 {
1932         pjsip_tx_data *packet = NULL;
1933
1934         if (session->channel) {
1935                 return 0;
1936         }
1937
1938         if (!(session->channel = chan_pjsip_new(session, AST_STATE_RING, session->exten, NULL, NULL, NULL))) {
1939                 if (pjsip_inv_end_session(session->inv_session, 503, NULL, &packet) == PJ_SUCCESS) {
1940                         ast_sip_session_send_response(session, packet);
1941                 }
1942
1943                 ast_log(LOG_ERROR, "Failed to allocate new PJSIP channel on incoming SIP INVITE\n");
1944                 return -1;
1945         }
1946         /* channel gets created on incoming request, but we wait to call start
1947            so other supplements have a chance to run */
1948         return 0;
1949 }
1950
1951 static int pbx_start_incoming_request(struct ast_sip_session *session, pjsip_rx_data *rdata)
1952 {
1953         int res;
1954
1955         res = ast_pbx_start(session->channel);
1956
1957         switch (res) {
1958         case AST_PBX_FAILED:
1959                 ast_log(LOG_WARNING, "Failed to start PBX ;(\n");
1960                 ast_channel_hangupcause_set(session->channel, AST_CAUSE_SWITCH_CONGESTION);
1961                 ast_hangup(session->channel);
1962                 break;
1963         case AST_PBX_CALL_LIMIT:
1964                 ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
1965                 ast_channel_hangupcause_set(session->channel, AST_CAUSE_SWITCH_CONGESTION);
1966                 ast_hangup(session->channel);
1967                 break;
1968         case AST_PBX_SUCCESS:
1969         default:
1970                 break;
1971         }
1972
1973         ast_debug(3, "Started PBX on new PJSIP channel %s\n", ast_channel_name(session->channel));
1974
1975         return (res == AST_PBX_SUCCESS) ? 0 : -1;
1976 }
1977
1978 static struct ast_sip_session_supplement pbx_start_supplement = {
1979         .method = "INVITE",
1980         .priority = AST_SIP_SESSION_SUPPLEMENT_PRIORITY_LAST,
1981         .incoming_request = pbx_start_incoming_request,
1982 };
1983
1984 /*! \brief Function called when a response is received on the session */
1985 static void chan_pjsip_incoming_response(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
1986 {
1987         struct pjsip_status_line status = rdata->msg_info.msg->line.status;
1988
1989         if (!session->channel) {
1990                 return;
1991         }
1992
1993         switch (status.code) {
1994         case 180:
1995                 ast_queue_control(session->channel, AST_CONTROL_RINGING);
1996                 if (ast_channel_state(session->channel) != AST_STATE_UP) {
1997                         ast_setstate(session->channel, AST_STATE_RINGING);
1998                 }
1999                 break;
2000         case 183:
2001                 ast_queue_control(session->channel, AST_CONTROL_PROGRESS);
2002                 break;
2003         case 200:
2004                 ast_queue_control(session->channel, AST_CONTROL_ANSWER);
2005                 break;
2006         default:
2007                 break;
2008         }
2009 }
2010
2011 static int chan_pjsip_incoming_ack(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
2012 {
2013         if (rdata->msg_info.msg->line.req.method.id == PJSIP_ACK_METHOD) {
2014                 if (session->endpoint->media.direct_media.enabled) {
2015                         ast_queue_control(session->channel, AST_CONTROL_SRCCHANGE);
2016                 }
2017         }
2018         return 0;
2019 }
2020
2021 /*!
2022  * \brief Load the module
2023  *
2024  * Module loading including tests for configuration or dependencies.
2025  * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
2026  * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
2027  * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
2028  * configuration file or other non-critical problem return
2029  * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
2030  */
2031 static int load_module(void)
2032 {
2033         if (!(chan_pjsip_tech.capabilities = ast_format_cap_alloc())) {
2034                 return AST_MODULE_LOAD_DECLINE;
2035         }
2036
2037         ast_format_cap_add_all_by_type(chan_pjsip_tech.capabilities, AST_FORMAT_TYPE_AUDIO);
2038
2039         ast_rtp_glue_register(&chan_pjsip_rtp_glue);
2040
2041         if (ast_channel_register(&chan_pjsip_tech)) {
2042                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", channel_type);
2043                 goto end;
2044         }
2045
2046         if (ast_custom_function_register(&chan_pjsip_dial_contacts_function)) {
2047                 ast_log(LOG_ERROR, "Unable to register PJSIP_DIAL_CONTACTS dialplan function\n");
2048                 goto end;
2049         }
2050
2051         if (ast_custom_function_register(&media_offer_function)) {
2052                 ast_log(LOG_WARNING, "Unable to register PJSIP_MEDIA_OFFER dialplan function\n");
2053         }
2054
2055         if (ast_sip_session_register_supplement(&chan_pjsip_supplement)) {
2056                 ast_log(LOG_ERROR, "Unable to register PJSIP supplement\n");
2057                 goto end;
2058         }
2059
2060         if (ast_sip_session_register_supplement(&pbx_start_supplement)) {
2061                 ast_log(LOG_ERROR, "Unable to register PJSIP pbx start supplement\n");
2062                 ast_sip_session_unregister_supplement(&chan_pjsip_supplement);
2063                 goto end;
2064         }
2065
2066         if (ast_sip_session_register_supplement(&chan_pjsip_ack_supplement)) {
2067                 ast_log(LOG_ERROR, "Unable to register PJSIP ACK supplement\n");
2068                 ast_sip_session_unregister_supplement(&pbx_start_supplement);
2069                 ast_sip_session_unregister_supplement(&chan_pjsip_supplement);
2070                 goto end;
2071         }
2072
2073         return 0;
2074
2075 end:
2076         ast_custom_function_unregister(&media_offer_function);
2077         ast_custom_function_unregister(&chan_pjsip_dial_contacts_function);
2078         ast_channel_unregister(&chan_pjsip_tech);
2079         ast_rtp_glue_unregister(&chan_pjsip_rtp_glue);
2080
2081         return AST_MODULE_LOAD_FAILURE;
2082 }
2083
2084 /*! \brief Reload module */
2085 static int reload(void)
2086 {
2087         return -1;
2088 }
2089
2090 /*! \brief Unload the PJSIP channel from Asterisk */
2091 static int unload_module(void)
2092 {
2093         ast_custom_function_unregister(&media_offer_function);
2094
2095         ast_sip_session_unregister_supplement(&chan_pjsip_supplement);
2096         ast_sip_session_unregister_supplement(&pbx_start_supplement);
2097
2098         ast_custom_function_unregister(&chan_pjsip_dial_contacts_function);
2099         ast_channel_unregister(&chan_pjsip_tech);
2100         ast_rtp_glue_unregister(&chan_pjsip_rtp_glue);
2101
2102         return 0;
2103 }
2104
2105 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP Channel Driver",
2106                 .load = load_module,
2107                 .unload = unload_module,
2108                 .reload = reload,
2109                 .load_pri = AST_MODPRI_CHANNEL_DRIVER,
2110                );