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