4f01ccec5aa9ba6af6f87bd1d605190797f38067
[asterisk/asterisk.git] / channels / chan_motif.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2012, 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 Motif Jingle Channel Driver
24  *
25  * Iksemel http://iksemel.jabberstudio.org/
26  *
27  * \ingroup channel_drivers
28  */
29
30 /*! \li \ref chan_motif.c uses the configuration file \ref motif.conf
31  * \addtogroup configuration_file
32  */
33
34 /*! \page motif.conf motif.conf
35  * \verbinclude motif.conf.sample
36  */
37
38 /*** MODULEINFO
39         <depend>iksemel</depend>
40         <depend>res_xmpp</depend>
41         <use type="external">openssl</use>
42         <support_level>core</support_level>
43  ***/
44
45 #include "asterisk.h"
46
47 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
48
49 #include <sys/socket.h>
50 #include <fcntl.h>
51 #include <netdb.h>
52 #include <netinet/in.h>
53 #include <arpa/inet.h>
54 #include <sys/signal.h>
55 #include <iksemel.h>
56 #include <pthread.h>
57
58 #include "asterisk/lock.h"
59 #include "asterisk/channel.h"
60 #include "asterisk/config_options.h"
61 #include "asterisk/module.h"
62 #include "asterisk/pbx.h"
63 #include "asterisk/sched.h"
64 #include "asterisk/io.h"
65 #include "asterisk/rtp_engine.h"
66 #include "asterisk/acl.h"
67 #include "asterisk/callerid.h"
68 #include "asterisk/file.h"
69 #include "asterisk/cli.h"
70 #include "asterisk/app.h"
71 #include "asterisk/musiconhold.h"
72 #include "asterisk/manager.h"
73 #include "asterisk/stringfields.h"
74 #include "asterisk/utils.h"
75 #include "asterisk/causes.h"
76 #include "asterisk/astobj.h"
77 #include "asterisk/abstract_jb.h"
78 #include "asterisk/xmpp.h"
79
80 /*! \brief Default maximum number of ICE candidates we will offer */
81 #define DEFAULT_MAX_ICE_CANDIDATES "10"
82
83 /*! \brief Default maximum number of payloads we will offer */
84 #define DEFAULT_MAX_PAYLOADS "30"
85
86 /*! \brief Number of buckets for endpoints */
87 #define ENDPOINT_BUCKETS 37
88
89 /*! \brief Number of buckets for sessions, on a per-endpoint basis */
90 #define SESSION_BUCKETS 37
91
92 /*! \brief Namespace for Jingle itself */
93 #define JINGLE_NS "urn:xmpp:jingle:1"
94
95 /*! \brief Namespace for Jingle RTP sessions */
96 #define JINGLE_RTP_NS "urn:xmpp:jingle:apps:rtp:1"
97
98 /*! \brief Namespace for Jingle RTP info */
99 #define JINGLE_RTP_INFO_NS "urn:xmpp:jingle:apps:rtp:info:1"
100
101 /*! \brief Namespace for Jingle ICE-UDP */
102 #define JINGLE_ICE_UDP_NS "urn:xmpp:jingle:transports:ice-udp:1"
103
104 /*! \brief Namespace for Google Talk ICE-UDP */
105 #define GOOGLE_TRANSPORT_NS "http://www.google.com/transport/p2p"
106
107 /*! \brief Namespace for Google Talk Raw UDP */
108 #define GOOGLE_TRANSPORT_RAW_NS "http://www.google.com/transport/raw-udp"
109
110 /*! \brief Namespace for Google Session */
111 #define GOOGLE_SESSION_NS "http://www.google.com/session"
112
113 /*! \brief Namespace for Google Phone description */
114 #define GOOGLE_PHONE_NS "http://www.google.com/session/phone"
115
116 /*! \brief Namespace for Google Video description */
117 #define GOOGLE_VIDEO_NS "http://www.google.com/session/video"
118
119 /*! \brief Namespace for XMPP stanzas */
120 #define XMPP_STANZAS_NS "urn:ietf:params:xml:ns:xmpp-stanzas"
121
122 /*! \brief The various transport methods supported, from highest priority to lowest priority when doing fallback */
123 enum jingle_transport {
124         JINGLE_TRANSPORT_ICE_UDP = 3,   /*!< XEP-0176 */
125         JINGLE_TRANSPORT_GOOGLE_V2 = 2, /*!< https://developers.google.com/talk/call_signaling */
126         JINGLE_TRANSPORT_GOOGLE_V1 = 1, /*!< Undocumented initial Google specification */
127         JINGLE_TRANSPORT_NONE = 0,      /*!< No transport specified */
128 };
129
130 /*! \brief Endpoint state information */
131 struct jingle_endpoint_state {
132         struct ao2_container *sessions; /*!< Active sessions to or from the endpoint */
133 };
134
135 /*! \brief Endpoint which contains configuration information and active sessions */
136 struct jingle_endpoint {
137         AST_DECLARE_STRING_FIELDS(
138                 AST_STRING_FIELD(name);              /*!< Name of the endpoint */
139                 AST_STRING_FIELD(context);           /*!< Context to place incoming calls into */
140                 AST_STRING_FIELD(accountcode);       /*!< Account code */
141                 AST_STRING_FIELD(language);          /*!< Default language for prompts */
142                 AST_STRING_FIELD(musicclass);        /*!< Configured music on hold class */
143                 AST_STRING_FIELD(parkinglot);        /*!< Configured parking lot */
144                 );
145         struct ast_xmpp_client *connection;     /*!< Connection to use for traffic */
146         iksrule *rule;                          /*!< Active matching rule */
147         unsigned int maxicecandidates;          /*!< Maximum number of ICE candidates we will offer */
148         unsigned int maxpayloads;               /*!< Maximum number of payloads we will offer */
149         struct ast_codec_pref prefs;            /*!< Codec preferences */
150         struct ast_format_cap *cap;             /*!< Formats to use */
151         ast_group_t callgroup;                  /*!< Call group */
152         ast_group_t pickupgroup;                /*!< Pickup group */
153         enum jingle_transport transport;        /*!< Default transport to use on outgoing sessions */
154         struct jingle_endpoint_state *state;    /*!< Endpoint state information */
155 };
156
157 /*! \brief Session which contains information about an active session */
158 struct jingle_session {
159         AST_DECLARE_STRING_FIELDS(
160                 AST_STRING_FIELD(sid);        /*!< Session identifier */
161                 AST_STRING_FIELD(audio_name); /*!< Name of the audio content */
162                 AST_STRING_FIELD(video_name); /*!< Name of the video content */
163                 );
164         struct jingle_endpoint_state *state;  /*!< Endpoint we are associated with */
165         struct ast_xmpp_client *connection;   /*!< Connection to use for traffic */
166         enum jingle_transport transport;      /*!< Transport type to use for this session */
167         unsigned int maxicecandidates;        /*!< Maximum number of ICE candidates we will offer */
168         unsigned int maxpayloads;             /*!< Maximum number of payloads we will offer */
169         char remote_original[XMPP_MAX_JIDLEN];/*!< Identifier of the original remote party (remote may have changed due to redirect) */
170         char remote[XMPP_MAX_JIDLEN];         /*!< Identifier of the remote party */
171         iksrule *rule;                        /*!< Session matching rule */
172         struct ast_codec_pref prefs;          /*!< Codec preferences */
173         struct ast_channel *owner;            /*!< Master Channel */
174         struct ast_rtp_instance *rtp;         /*!< RTP audio session */
175         struct ast_rtp_instance *vrtp;        /*!< RTP video session */
176         struct ast_format_cap *cap;           /*!< Local codec capabilities */
177         struct ast_format_cap *jointcap;      /*!< Joint codec capabilities */
178         struct ast_format_cap *peercap;       /*!< Peer codec capabilities */
179         unsigned int outgoing:1;              /*!< Whether this is an outgoing leg or not */
180         unsigned int gone:1;                  /*!< In the eyes of Jingle this session is already gone */
181         struct ast_callid *callid;            /*!< Bound session call-id */
182 };
183
184 static const char desc[] = "Motif Jingle Channel";
185 static const char channel_type[] = "Motif";
186
187 struct jingle_config {
188         struct ao2_container *endpoints; /*!< Configured endpoints */
189 };
190
191 static AO2_GLOBAL_OBJ_STATIC(globals);
192
193 static struct ast_sched_context *sched; /*!< Scheduling context for RTCP */
194
195 /* \brief Asterisk core interaction functions */
196 static struct ast_channel *jingle_request(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, const char *data, int *cause);
197 static int jingle_sendtext(struct ast_channel *ast, const char *text);
198 static int jingle_digit_begin(struct ast_channel *ast, char digit);
199 static int jingle_digit_end(struct ast_channel *ast, char digit, unsigned int duration);
200 static int jingle_call(struct ast_channel *ast, const char *dest, int timeout);
201 static int jingle_hangup(struct ast_channel *ast);
202 static int jingle_answer(struct ast_channel *ast);
203 static struct ast_frame *jingle_read(struct ast_channel *ast);
204 static int jingle_write(struct ast_channel *ast, struct ast_frame *f);
205 static int jingle_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
206 static int jingle_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
207 static struct jingle_session *jingle_alloc(struct jingle_endpoint *endpoint, const char *from, const char *sid);
208
209 /*! \brief Action handlers */
210 static void jingle_action_session_initiate(struct jingle_endpoint *endpoint, struct jingle_session *session, ikspak *pak);
211 static void jingle_action_transport_info(struct jingle_endpoint *endpoint, struct jingle_session *session, ikspak *pak);
212 static void jingle_action_session_accept(struct jingle_endpoint *endpoint, struct jingle_session *session, ikspak *pak);
213 static void jingle_action_session_info(struct jingle_endpoint *endpoint, struct jingle_session *session, ikspak *pak);
214 static void jingle_action_session_terminate(struct jingle_endpoint *endpoint, struct jingle_session *session, ikspak *pak);
215
216 /*! \brief PBX interface structure for channel registration */
217 static struct ast_channel_tech jingle_tech = {
218         .type = "Motif",
219         .description = "Motif Jingle Channel Driver",
220         .requester = jingle_request,
221         .send_text = jingle_sendtext,
222         .send_digit_begin = jingle_digit_begin,
223         .send_digit_end = jingle_digit_end,
224         .bridge = ast_rtp_instance_bridge,
225         .call = jingle_call,
226         .hangup = jingle_hangup,
227         .answer = jingle_answer,
228         .read = jingle_read,
229         .write = jingle_write,
230         .write_video = jingle_write,
231         .exception = jingle_read,
232         .indicate = jingle_indicate,
233         .fixup = jingle_fixup,
234         .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER
235 };
236
237 /*! \brief Defined handlers for different Jingle actions */
238 static const struct jingle_action_handler {
239         const char *action;
240         void (*handler)(struct jingle_endpoint *endpoint, struct jingle_session *session, ikspak *pak);
241 } jingle_action_handlers[] = {
242         /* Jingle actions */
243         { "session-initiate", jingle_action_session_initiate, },
244         { "transport-info", jingle_action_transport_info, },
245         { "session-accept", jingle_action_session_accept, },
246         { "session-info", jingle_action_session_info, },
247         { "session-terminate", jingle_action_session_terminate, },
248         /* Google-V1 actions */
249         { "initiate", jingle_action_session_initiate, },
250         { "candidates", jingle_action_transport_info, },
251         { "accept", jingle_action_session_accept, },
252         { "terminate", jingle_action_session_terminate, },
253         { "reject", jingle_action_session_terminate, },
254 };
255
256 /*! \brief Reason text <-> cause code mapping */
257 static const struct jingle_reason_mapping {
258         const char *reason;
259         int cause;
260 } jingle_reason_mappings[] = {
261         { "busy", AST_CAUSE_BUSY, },
262         { "cancel", AST_CAUSE_CALL_REJECTED, },
263         { "connectivity-error", AST_CAUSE_INTERWORKING, },
264         { "decline", AST_CAUSE_CALL_REJECTED, },
265         { "expired", AST_CAUSE_NO_USER_RESPONSE, },
266         { "failed-transport", AST_CAUSE_PROTOCOL_ERROR, },
267         { "failed-application", AST_CAUSE_SWITCH_CONGESTION, },
268         { "general-error", AST_CAUSE_CONGESTION, },
269         { "gone", AST_CAUSE_NORMAL_CLEARING, },
270         { "incompatible-parameters", AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, },
271         { "media-error", AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, },
272         { "security-error", AST_CAUSE_PROTOCOL_ERROR, },
273         { "success", AST_CAUSE_NORMAL_CLEARING, },
274         { "timeout", AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, },
275         { "unsupported-applications", AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, },
276         { "unsupported-transports", AST_CAUSE_FACILITY_NOT_IMPLEMENTED, },
277 };
278
279 /*! \brief Hashing function for Jingle sessions */
280 static int jingle_session_hash(const void *obj, const int flags)
281 {
282         const struct jingle_session *session = obj;
283         const char *sid = obj;
284
285         return ast_str_hash(flags & OBJ_KEY ? sid : session->sid);
286 }
287
288 /*! \brief Comparator function for Jingle sessions */
289 static int jingle_session_cmp(void *obj, void *arg, int flags)
290 {
291         struct jingle_session *session1 = obj, *session2 = arg;
292         const char *sid = arg;
293
294         return !strcmp(session1->sid, flags & OBJ_KEY ? sid : session2->sid) ? CMP_MATCH | CMP_STOP : 0;
295 }
296
297 /*! \brief Destructor for Jingle endpoint state */
298 static void jingle_endpoint_state_destructor(void *obj)
299 {
300         struct jingle_endpoint_state *state = obj;
301
302         ao2_ref(state->sessions, -1);
303 }
304
305 /*! \brief Destructor for Jingle endpoints */
306 static void jingle_endpoint_destructor(void *obj)
307 {
308         struct jingle_endpoint *endpoint = obj;
309
310         if (endpoint->rule) {
311                 iks_filter_remove_rule(endpoint->connection->filter, endpoint->rule);
312         }
313
314         if (endpoint->connection) {
315                 ast_xmpp_client_unref(endpoint->connection);
316         }
317
318         ast_format_cap_destroy(endpoint->cap);
319
320         ao2_ref(endpoint->state, -1);
321
322         ast_string_field_free_memory(endpoint);
323 }
324
325 /*! \brief Find function for Jingle endpoints */
326 static void *jingle_endpoint_find(struct ao2_container *tmp_container, const char *category)
327 {
328         return ao2_find(tmp_container, category, OBJ_KEY);
329 }
330
331 /*! \brief Allocator function for Jingle endpoint state */
332 static struct jingle_endpoint_state *jingle_endpoint_state_create(void)
333 {
334         struct jingle_endpoint_state *state;
335
336         if (!(state = ao2_alloc(sizeof(*state), jingle_endpoint_state_destructor))) {
337                 return NULL;
338         }
339
340         if (!(state->sessions = ao2_container_alloc(SESSION_BUCKETS, jingle_session_hash, jingle_session_cmp))) {
341                 ao2_ref(state, -1);
342                 return NULL;
343         }
344
345         return state;
346 }
347
348 /*! \brief State find/create function */
349 static struct jingle_endpoint_state *jingle_endpoint_state_find_or_create(const char *category)
350 {
351         RAII_VAR(struct jingle_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
352         RAII_VAR(struct jingle_endpoint *, endpoint, NULL, ao2_cleanup);
353
354         if (!cfg || !cfg->endpoints || !(endpoint = jingle_endpoint_find(cfg->endpoints, category))) {
355                 return jingle_endpoint_state_create();
356         }
357
358         ao2_ref(endpoint->state, +1);
359         return endpoint->state;
360 }
361
362 /*! \brief Allocator function for Jingle endpoints */
363 static void *jingle_endpoint_alloc(const char *cat)
364 {
365         struct jingle_endpoint *endpoint;
366
367         if (!(endpoint = ao2_alloc(sizeof(*endpoint), jingle_endpoint_destructor))) {
368                 return NULL;
369         }
370
371         if (ast_string_field_init(endpoint, 512)) {
372                 ao2_ref(endpoint, -1);
373                 return NULL;
374         }
375
376         if (!(endpoint->state = jingle_endpoint_state_find_or_create(cat))) {
377                 ao2_ref(endpoint, -1);
378                 return NULL;
379         }
380
381         ast_string_field_set(endpoint, name, cat);
382
383         endpoint->cap = ast_format_cap_alloc_nolock();
384         endpoint->transport = JINGLE_TRANSPORT_ICE_UDP;
385
386         return endpoint;
387 }
388
389 /*! \brief Hashing function for Jingle endpoints */
390 static int jingle_endpoint_hash(const void *obj, const int flags)
391 {
392         const struct jingle_endpoint *endpoint = obj;
393         const char *name = obj;
394
395         return ast_str_hash(flags & OBJ_KEY ? name : endpoint->name);
396 }
397
398 /*! \brief Comparator function for Jingle endpoints */
399 static int jingle_endpoint_cmp(void *obj, void *arg, int flags)
400 {
401         struct jingle_endpoint *endpoint1 = obj, *endpoint2 = arg;
402         const char *name = arg;
403
404         return !strcmp(endpoint1->name, flags & OBJ_KEY ? name : endpoint2->name) ? CMP_MATCH | CMP_STOP : 0;
405 }
406
407 static struct aco_type endpoint_option = {
408         .type = ACO_ITEM,
409         .category_match = ACO_BLACKLIST,
410         .category = "^general$",
411         .item_alloc = jingle_endpoint_alloc,
412         .item_find = jingle_endpoint_find,
413         .item_offset = offsetof(struct jingle_config, endpoints),
414 };
415
416 struct aco_type *endpoint_options[] = ACO_TYPES(&endpoint_option);
417
418 struct aco_file jingle_conf = {
419         .filename = "motif.conf",
420         .types = ACO_TYPES(&endpoint_option),
421 };
422
423 /*! \brief Destructor for Jingle sessions */
424 static void jingle_session_destructor(void *obj)
425 {
426         struct jingle_session *session = obj;
427
428         if (session->rule) {
429                 iks_filter_remove_rule(session->connection->filter, session->rule);
430         }
431
432         if (session->connection) {
433                 ast_xmpp_client_unref(session->connection);
434         }
435
436         if (session->rtp) {
437                 ast_rtp_instance_destroy(session->rtp);
438         }
439
440         if (session->vrtp) {
441                 ast_rtp_instance_destroy(session->vrtp);
442         }
443
444         ast_format_cap_destroy(session->cap);
445         ast_format_cap_destroy(session->jointcap);
446         ast_format_cap_destroy(session->peercap);
447
448         if (session->callid) {
449                 ast_callid_unref(session->callid);
450         }
451
452         ast_string_field_free_memory(session);
453 }
454
455 /*! \brief Destructor called when module configuration goes away */
456 static void jingle_config_destructor(void *obj)
457 {
458         struct jingle_config *cfg = obj;
459         ao2_cleanup(cfg->endpoints);
460 }
461
462 /*! \brief Allocator called when module configuration should appear */
463 static void *jingle_config_alloc(void)
464 {
465         struct jingle_config *cfg;
466
467         if (!(cfg = ao2_alloc(sizeof(*cfg), jingle_config_destructor))) {
468                 return NULL;
469         }
470
471         if (!(cfg->endpoints = ao2_container_alloc(ENDPOINT_BUCKETS, jingle_endpoint_hash, jingle_endpoint_cmp))) {
472                 ao2_ref(cfg, -1);
473                 return NULL;
474         }
475
476         return cfg;
477 }
478
479 CONFIG_INFO_STANDARD(cfg_info, globals, jingle_config_alloc,
480                      .files = ACO_FILES(&jingle_conf),
481         );
482
483 /*! \brief Function called by RTP engine to get local RTP peer */
484 static enum ast_rtp_glue_result jingle_get_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
485 {
486         struct jingle_session *session = ast_channel_tech_pvt(chan);
487         enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_LOCAL;
488
489         if (!session->rtp) {
490                 return AST_RTP_GLUE_RESULT_FORBID;
491         }
492
493         ao2_ref(session->rtp, +1);
494         *instance = session->rtp;
495
496         return res;
497 }
498
499 /*! \brief Function called by RTP engine to get peer capabilities */
500 static void jingle_get_codec(struct ast_channel *chan, struct ast_format_cap *result)
501 {
502 }
503
504 /*! \brief Function called by RTP engine to change where the remote party should send media */
505 static int jingle_set_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance *rtp, struct ast_rtp_instance *vrtp, struct ast_rtp_instance *tpeer, const struct ast_format_cap *cap, int nat_active)
506 {
507         return -1;
508 }
509
510 /*! \brief Local glue for interacting with the RTP engine core */
511 static struct ast_rtp_glue jingle_rtp_glue = {
512         .type = "Motif",
513         .get_rtp_info = jingle_get_rtp_peer,
514         .get_codec = jingle_get_codec,
515         .update_peer = jingle_set_rtp_peer,
516 };
517
518 /*! \brief Internal helper function which enables video support on a sesson if possible */
519 static void jingle_enable_video(struct jingle_session *session)
520 {
521         struct ast_sockaddr tmp;
522         struct ast_rtp_engine_ice *ice;
523
524         /* If video is already present don't do anything */
525         if (session->vrtp) {
526                 return;
527         }
528
529         /* If there are no configured video codecs do not turn video support on, it just won't work */
530         if (!ast_format_cap_has_type(session->cap, AST_FORMAT_TYPE_VIDEO)) {
531                 return;
532         }
533
534         ast_sockaddr_parse(&tmp, "0.0.0.0", 0);
535
536         if (!(session->vrtp = ast_rtp_instance_new("asterisk", sched, &tmp, NULL))) {
537                 return;
538         }
539
540         ast_rtp_instance_set_prop(session->vrtp, AST_RTP_PROPERTY_RTCP, 1);
541
542         ast_channel_set_fd(session->owner, 2, ast_rtp_instance_fd(session->vrtp, 0));
543         ast_channel_set_fd(session->owner, 3, ast_rtp_instance_fd(session->vrtp, 1));
544         ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(session->vrtp), session->vrtp, &session->prefs);
545
546         if (session->transport == JINGLE_TRANSPORT_GOOGLE_V2 && (ice = ast_rtp_instance_get_ice(session->vrtp))) {
547                 ice->stop(session->vrtp);
548         }
549 }
550
551 /*! \brief Internal helper function used to allocate Jingle session on an endpoint */
552 static struct jingle_session *jingle_alloc(struct jingle_endpoint *endpoint, const char *from, const char *sid)
553 {
554         struct jingle_session *session;
555         struct ast_callid *callid;
556         struct ast_sockaddr tmp;
557
558         if (!(session = ao2_alloc(sizeof(*session), jingle_session_destructor))) {
559                 return NULL;
560         }
561
562         callid = ast_read_threadstorage_callid();
563         session->callid = (callid ? callid : ast_create_callid());
564
565         if (ast_string_field_init(session, 512)) {
566                 ao2_ref(session, -1);
567                 return NULL;
568         }
569
570         if (!ast_strlen_zero(from)) {
571                 ast_copy_string(session->remote_original, from, sizeof(session->remote_original));
572                 ast_copy_string(session->remote, from, sizeof(session->remote));
573         }
574
575         if (ast_strlen_zero(sid)) {
576                 ast_string_field_build(session, sid, "%08lx%08lx", ast_random(), ast_random());
577                 session->outgoing = 1;
578                 ast_string_field_set(session, audio_name, "audio");
579                 ast_string_field_set(session, video_name, "video");
580         } else {
581                 ast_string_field_set(session, sid, sid);
582         }
583
584         ao2_ref(endpoint->state, +1);
585         session->state = endpoint->state;
586         ao2_ref(endpoint->connection, +1);
587         session->connection = endpoint->connection;
588         session->transport = endpoint->transport;
589
590         if (!(session->cap = ast_format_cap_alloc_nolock()) ||
591             !(session->jointcap = ast_format_cap_alloc_nolock()) ||
592             !(session->peercap = ast_format_cap_alloc_nolock()) ||
593             !session->callid) {
594                 ao2_ref(session, -1);
595                 return NULL;
596         }
597
598         ast_format_cap_copy(session->cap, endpoint->cap);
599
600         /* While we rely on res_xmpp for communication we still need a temporary ast_sockaddr to tell the RTP engine
601          * that we want IPv4 */
602         ast_sockaddr_parse(&tmp, "0.0.0.0", 0);
603
604         /* Sessions always carry audio, but video is optional so don't enable it here */
605         if (!(session->rtp = ast_rtp_instance_new("asterisk", sched, &tmp, NULL))) {
606                 ao2_ref(session, -1);
607                 return NULL;
608         }
609         ast_rtp_instance_set_prop(session->rtp, AST_RTP_PROPERTY_RTCP, 1);
610         ast_rtp_instance_set_prop(session->rtp, AST_RTP_PROPERTY_DTMF, 1);
611
612         memcpy(&session->prefs, &endpoint->prefs, sizeof(session->prefs));
613
614         session->maxicecandidates = endpoint->maxicecandidates;
615         session->maxpayloads = endpoint->maxpayloads;
616
617         return session;
618 }
619
620 /*! \brief Function called to create a new Jingle Asterisk channel */
621 static struct ast_channel *jingle_new(struct jingle_endpoint *endpoint, struct jingle_session *session, int state, const char *title, const char *linkedid, const char *cid_name)
622 {
623         struct ast_channel *chan;
624         const char *str = S_OR(title, session->remote);
625         struct ast_format tmpfmt;
626
627         if (ast_format_cap_is_empty(session->cap)) {
628                 return NULL;
629         }
630
631         if (!(chan = ast_channel_alloc(1, state, S_OR(title, ""), S_OR(cid_name, ""), "", "", "", linkedid, 0, "Motif/%s-%04lx", str, ast_random() & 0xffff))) {
632                 return NULL;
633         }
634
635         ast_channel_tech_set(chan, &jingle_tech);
636         ast_channel_tech_pvt_set(chan, session);
637         session->owner = chan;
638
639         ast_channel_callid_set(chan, session->callid);
640
641         ast_format_cap_copy(ast_channel_nativeformats(chan), session->cap);
642         ast_codec_choose(&session->prefs, session->cap, 1, &tmpfmt);
643
644         if (session->rtp) {
645                 struct ast_rtp_engine_ice *ice;
646
647                 ast_channel_set_fd(chan, 0, ast_rtp_instance_fd(session->rtp, 0));
648                 ast_channel_set_fd(chan, 1, ast_rtp_instance_fd(session->rtp, 1));
649                 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(session->rtp), session->rtp, &session->prefs);
650
651                 if (((session->transport == JINGLE_TRANSPORT_GOOGLE_V2) ||
652                      (session->transport == JINGLE_TRANSPORT_GOOGLE_V1)) &&
653                     (ice = ast_rtp_instance_get_ice(session->rtp))) {
654                         /* We stop built in ICE support because we need to fall back to old old old STUN support */
655                         ice->stop(session->rtp);
656                 }
657         }
658
659         if (state == AST_STATE_RING) {
660                 ast_channel_rings_set(chan, 1);
661         }
662
663         ast_channel_adsicpe_set(chan, AST_ADSI_UNAVAILABLE);
664
665         ast_best_codec(ast_channel_nativeformats(chan), &tmpfmt);
666         ast_format_copy(ast_channel_writeformat(chan), &tmpfmt);
667         ast_format_copy(ast_channel_rawwriteformat(chan), &tmpfmt);
668         ast_format_copy(ast_channel_readformat(chan), &tmpfmt);
669         ast_format_copy(ast_channel_rawreadformat(chan), &tmpfmt);
670
671         ao2_lock(endpoint);
672
673         ast_channel_callgroup_set(chan, endpoint->callgroup);
674         ast_channel_pickupgroup_set(chan, endpoint->pickupgroup);
675
676         if (!ast_strlen_zero(endpoint->accountcode)) {
677                 ast_channel_accountcode_set(chan, endpoint->accountcode);
678         }
679
680         if (!ast_strlen_zero(endpoint->language)) {
681                 ast_channel_language_set(chan, endpoint->language);
682         }
683
684         if (!ast_strlen_zero(endpoint->musicclass)) {
685                 ast_channel_musicclass_set(chan, endpoint->musicclass);
686         }
687
688         ast_channel_context_set(chan, endpoint->context);
689         ast_channel_exten_set(chan, "s");
690         ast_channel_priority_set(chan, 1);
691
692         ao2_unlock(endpoint);
693
694         return chan;
695 }
696
697 /*! \brief Internal helper function which sends a response */
698 static void jingle_send_response(struct ast_xmpp_client *connection, ikspak *pak)
699 {
700         iks *response;
701
702         if (!(response = iks_new("iq"))) {
703                 ast_log(LOG_ERROR, "Unable to allocate an IKS response stanza\n");
704                 return;
705         }
706
707         iks_insert_attrib(response, "type", "result");
708         iks_insert_attrib(response, "from", connection->jid->full);
709         iks_insert_attrib(response, "to", iks_find_attrib(pak->x, "from"));
710         iks_insert_attrib(response, "id", iks_find_attrib(pak->x, "id"));
711
712         ast_xmpp_client_send(connection, response);
713
714         iks_delete(response);
715 }
716
717 /*! \brief Internal helper function which sends an error response */
718 static void jingle_send_error_response(struct ast_xmpp_client *connection, ikspak *pak, const char *type, const char *reasonstr, const char *reasonstr2)
719 {
720         iks *response, *error = NULL, *reason = NULL, *reason2 = NULL;
721
722         if (!(response = iks_new("iq")) ||
723             !(error = iks_new("error")) ||
724             !(reason = iks_new(reasonstr))) {
725                 ast_log(LOG_ERROR, "Unable to allocate IKS error response stanzas\n");
726                 goto end;
727         }
728
729         iks_insert_attrib(response, "type", "error");
730         iks_insert_attrib(response, "from", connection->jid->full);
731         iks_insert_attrib(response, "to", iks_find_attrib(pak->x, "from"));
732         iks_insert_attrib(response, "id", iks_find_attrib(pak->x, "id"));
733
734         iks_insert_attrib(error, "type", type);
735         iks_insert_node(error, reason);
736
737         if (!ast_strlen_zero(reasonstr2) && (reason2 = iks_new(reasonstr2))) {
738                 iks_insert_node(error, reason2);
739         }
740
741         iks_insert_node(response, error);
742
743         ast_xmpp_client_send(connection, response);
744 end:
745         iks_delete(reason2);
746         iks_delete(reason);
747         iks_delete(error);
748         iks_delete(response);
749 }
750
751 /*! \brief Internal helper function which adds ICE-UDP candidates to a transport node */
752 static int jingle_add_ice_udp_candidates_to_transport(struct ast_rtp_instance *rtp, iks *transport, iks **candidates, unsigned int maximum)
753 {
754         struct ast_rtp_engine_ice *ice;
755         struct ao2_container *local_candidates;
756         struct ao2_iterator it;
757         struct ast_rtp_engine_ice_candidate *candidate;
758         int i = 0, res = 0;
759
760         if (!(ice = ast_rtp_instance_get_ice(rtp)) || !(local_candidates = ice->get_local_candidates(rtp))) {
761                 ast_log(LOG_ERROR, "Unable to add ICE-UDP candidates as ICE support not available or no candidates available\n");
762                 return -1;
763         }
764
765         iks_insert_attrib(transport, "xmlns", JINGLE_ICE_UDP_NS);
766         iks_insert_attrib(transport, "pwd", ice->get_password(rtp));
767         iks_insert_attrib(transport, "ufrag", ice->get_ufrag(rtp));
768
769         it = ao2_iterator_init(local_candidates, 0);
770
771         while ((candidate = ao2_iterator_next(&it)) && (i < maximum)) {
772                 iks *local_candidate;
773                 char tmp[30];
774
775                 if (!(local_candidate = iks_new("candidate"))) {
776                         res = -1;
777                         ast_log(LOG_ERROR, "Unable to allocate IKS candidate stanza for ICE-UDP transport\n");
778                         break;
779                 }
780
781                 snprintf(tmp, sizeof(tmp), "%d", candidate->id);
782                 iks_insert_attrib(local_candidate, "component", tmp);
783                 snprintf(tmp, sizeof(tmp), "%d", ast_str_hash(candidate->foundation));
784                 iks_insert_attrib(local_candidate, "foundation", tmp);
785                 iks_insert_attrib(local_candidate, "generation", "0");
786                 snprintf(tmp, sizeof(tmp), "%04lx", ast_random() & 0xffff);
787                 iks_insert_attrib(local_candidate, "id", tmp);
788                 iks_insert_attrib(local_candidate, "ip", ast_sockaddr_stringify_host(&candidate->address));
789                 iks_insert_attrib(local_candidate, "port", ast_sockaddr_stringify_port(&candidate->address));
790                 snprintf(tmp, sizeof(tmp), "%d", candidate->priority);
791                 iks_insert_attrib(local_candidate, "priority", tmp);
792                 iks_insert_attrib(local_candidate, "protocol", "udp");
793
794                 if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_HOST) {
795                         iks_insert_attrib(local_candidate, "type", "host");
796                 } else if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_SRFLX) {
797                         iks_insert_attrib(local_candidate, "type", "srflx");
798                 } else if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_RELAYED) {
799                         iks_insert_attrib(local_candidate, "type", "relay");
800                 }
801
802                 iks_insert_node(transport, local_candidate);
803                 candidates[i++] = local_candidate;
804         }
805
806         ao2_iterator_destroy(&it);
807         ao2_ref(local_candidates, -1);
808
809         return res;
810 }
811
812 /*! \brief Internal helper function which adds Google candidates to a transport node */
813 static int jingle_add_google_candidates_to_transport(struct ast_rtp_instance *rtp, iks *transport, iks **candidates, unsigned int video, enum jingle_transport transport_type, unsigned int maximum)
814 {
815         struct ast_rtp_engine_ice *ice;
816         struct ao2_container *local_candidates;
817         struct ao2_iterator it;
818         struct ast_rtp_engine_ice_candidate *candidate;
819         int i = 0, res = 0;
820
821         if (!(ice = ast_rtp_instance_get_ice(rtp)) || !(local_candidates = ice->get_local_candidates(rtp))) {
822                 ast_log(LOG_ERROR, "Unable to add Google ICE candidates as ICE support not available or no candidates available\n");
823                 return -1;
824         }
825
826         if (transport_type != JINGLE_TRANSPORT_GOOGLE_V1) {
827                 iks_insert_attrib(transport, "xmlns", GOOGLE_TRANSPORT_NS);
828         }
829
830         it = ao2_iterator_init(local_candidates, 0);
831
832         while ((candidate = ao2_iterator_next(&it)) && (i < maximum)) {
833                 iks *local_candidate;
834                 /* In Google land a username is 16 bytes, explicitly */
835                 char ufrag[17] = "";
836
837                 if (!(local_candidate = iks_new("candidate"))) {
838                         res = -1;
839                         ast_log(LOG_ERROR, "Unable to allocate IKS candidate stanza for Google ICE transport\n");
840                         break;
841                 }
842
843                 if (candidate->id == 1) {
844                         iks_insert_attrib(local_candidate, "name", !video ? "rtp" : "video_rtp");
845                 } else if (candidate->id == 2) {
846                         iks_insert_attrib(local_candidate, "name", !video ? "rtcp" : "video_rtcp");
847                 } else {
848                         iks_delete(local_candidate);
849                         continue;
850                 }
851
852                 iks_insert_attrib(local_candidate, "address", ast_sockaddr_stringify_host(&candidate->address));
853                 iks_insert_attrib(local_candidate, "port", ast_sockaddr_stringify_port(&candidate->address));
854
855                 if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_HOST) {
856                         iks_insert_attrib(local_candidate, "preference", "0.95");
857                         iks_insert_attrib(local_candidate, "type", "local");
858                 } else if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_SRFLX) {
859                         iks_insert_attrib(local_candidate, "preference", "0.9");
860                         iks_insert_attrib(local_candidate, "type", "stun");
861                 }
862
863                 iks_insert_attrib(local_candidate, "protocol", "udp");
864                 iks_insert_attrib(local_candidate, "network", "0");
865                 snprintf(ufrag, sizeof(ufrag), "%s", ice->get_ufrag(rtp));
866                 iks_insert_attrib(local_candidate, "username", ufrag);
867                 iks_insert_attrib(local_candidate, "generation", "0");
868
869                 if (transport_type == JINGLE_TRANSPORT_GOOGLE_V1) {
870                         iks_insert_attrib(local_candidate, "password", "");
871                         iks_insert_attrib(local_candidate, "foundation", "0");
872                         iks_insert_attrib(local_candidate, "component", "1");
873                 } else {
874                         iks_insert_attrib(local_candidate, "password", ice->get_password(rtp));
875                 }
876
877                 /* You may notice a lack of relay support up above - this is because we don't support it for use with
878                  * the Google talk transport due to their arcane support. */
879
880                 iks_insert_node(transport, local_candidate);
881                 candidates[i++] = local_candidate;
882         }
883
884         ao2_iterator_destroy(&it);
885         ao2_ref(local_candidates, -1);
886
887         return res;
888 }
889
890 /*! \brief Internal function which sends a session-terminate message */
891 static void jingle_send_session_terminate(struct jingle_session *session, const char *reasontext)
892 {
893         iks *iq = NULL, *jingle = NULL, *reason = NULL, *text = NULL;
894
895         if (!(iq = iks_new("iq")) || !(jingle = iks_new(session->transport == JINGLE_TRANSPORT_GOOGLE_V1 ? "session" : "jingle")) ||
896             !(reason = iks_new("reason")) || !(text = iks_new(reasontext))) {
897                 ast_log(LOG_ERROR, "Failed to allocate stanzas for session-terminate message on session '%s'\n", session->sid);
898                 goto end;
899         }
900
901         iks_insert_attrib(iq, "to", session->remote);
902         iks_insert_attrib(iq, "type", "set");
903         iks_insert_attrib(iq, "id", session->connection->mid);
904         ast_xmpp_increment_mid(session->connection->mid);
905
906         if (session->transport == JINGLE_TRANSPORT_GOOGLE_V1) {
907                 iks_insert_attrib(jingle, "type", "terminate");
908                 iks_insert_attrib(jingle, "id", session->sid);
909                 iks_insert_attrib(jingle, "xmlns", GOOGLE_SESSION_NS);
910                 iks_insert_attrib(jingle, "initiator", session->outgoing ? session->connection->jid->full : session->remote);
911         } else {
912                 iks_insert_attrib(jingle, "action", "session-terminate");
913                 iks_insert_attrib(jingle, "sid", session->sid);
914                 iks_insert_attrib(jingle, "xmlns", JINGLE_NS);
915         }
916
917         iks_insert_node(iq, jingle);
918         iks_insert_node(jingle, reason);
919         iks_insert_node(reason, text);
920
921         ast_xmpp_client_send(session->connection, iq);
922
923 end:
924         iks_delete(text);
925         iks_delete(reason);
926         iks_delete(jingle);
927         iks_delete(iq);
928 }
929
930 /*! \brief Internal function which sends a session-info message */
931 static void jingle_send_session_info(struct jingle_session *session, const char *info)
932 {
933         iks *iq = NULL, *jingle = NULL, *text = NULL;
934
935         /* Google-V1 has no way to send informational messages so don't even bother trying */
936         if (session->transport == JINGLE_TRANSPORT_GOOGLE_V1) {
937                 return;
938         }
939
940         if (!(iq = iks_new("iq")) || !(jingle = iks_new("jingle")) || !(text = iks_new(info))) {
941                 ast_log(LOG_ERROR, "Failed to allocate stanzas for session-info message on session '%s'\n", session->sid);
942                 goto end;
943         }
944
945         iks_insert_attrib(iq, "to", session->remote);
946         iks_insert_attrib(iq, "type", "set");
947         iks_insert_attrib(iq, "id", session->connection->mid);
948         ast_xmpp_increment_mid(session->connection->mid);
949
950         iks_insert_attrib(jingle, "action", "session-info");
951         iks_insert_attrib(jingle, "sid", session->sid);
952         iks_insert_attrib(jingle, "xmlns", JINGLE_NS);
953         iks_insert_node(iq, jingle);
954         iks_insert_node(jingle, text);
955
956         ast_xmpp_client_send(session->connection, iq);
957
958 end:
959         iks_delete(text);
960         iks_delete(jingle);
961         iks_delete(iq);
962 }
963
964 /*! \internal
965  *
966  * \brief Locks both pvt and pvt owner if owner is present.
967  *
968  * \note This function gives a ref to pvt->owner if it is present and locked.
969  *       This reference must be decremented after pvt->owner is unlocked.
970  *
971  * \note This function will never give you up,
972  * \note This function will never let you down.
973  * \note This function will run around and desert you.
974  *
975  * \pre pvt is not locked
976  * \post pvt is locked
977  * \post pvt->owner is locked and its reference count is increased (if pvt->owner is not NULL)
978  *
979  * \returns a pointer to the locked and reffed pvt->owner channel if it exists.
980  */
981 static struct ast_channel *jingle_session_lock_full(struct jingle_session *pvt)
982 {
983         struct ast_channel *chan;
984
985         /* Locking is simple when it is done right.  If you see a deadlock resulting
986          * in this function, it is not this function's fault, Your problem exists elsewhere.
987          * This function is perfect... seriously. */
988         for (;;) {
989                 /* First, get the channel and grab a reference to it */
990                 ao2_lock(pvt);
991                 chan = pvt->owner;
992                 if (chan) {
993                         /* The channel can not go away while we hold the pvt lock.
994                          * Give the channel a ref so it will not go away after we let
995                          * the pvt lock go. */
996                         ast_channel_ref(chan);
997                 } else {
998                         /* no channel, return pvt locked */
999                         return NULL;
1000                 }
1001
1002                 /* We had to hold the pvt lock while getting a ref to the owner channel
1003                  * but now we have to let this lock go in order to preserve proper
1004                  * locking order when grabbing the channel lock */
1005                 ao2_unlock(pvt);
1006
1007                 /* Look, no deadlock avoidance, hooray! */
1008                 ast_channel_lock(chan);
1009                 ao2_lock(pvt);
1010                 if (pvt->owner == chan) {
1011                         /* done */
1012                         break;
1013                 }
1014
1015                 /* If the owner changed while everything was unlocked, no problem,
1016                  * just start over and everthing will work.  This is rare, do not be
1017                  * confused by this loop and think this it is an expensive operation.
1018                  * The majority of the calls to this function will never involve multiple
1019                  * executions of this loop. */
1020                 ast_channel_unlock(chan);
1021                 ast_channel_unref(chan);
1022                 ao2_unlock(pvt);
1023         }
1024
1025         /* If owner exists, it is locked and reffed */
1026         return pvt->owner;
1027 }
1028
1029 /*! \brief Helper function which queues a hangup frame with cause code */
1030 static void jingle_queue_hangup_with_cause(struct jingle_session *session, int cause)
1031 {
1032         struct ast_channel *chan;
1033
1034         if ((chan = jingle_session_lock_full(session))) {
1035                 ast_debug(3, "Hanging up channel '%s' with cause '%d'\n", ast_channel_name(chan), cause);
1036                 ast_queue_hangup_with_cause(chan, cause);
1037                 ast_channel_unlock(chan);
1038                 ast_channel_unref(chan);
1039         }
1040         ao2_unlock(session);
1041 }
1042
1043 /*! \brief Internal function which sends a transport-info message */
1044 static void jingle_send_transport_info(struct jingle_session *session, const char *from)
1045 {
1046         iks *iq, *jingle = NULL, *audio = NULL, *audio_transport = NULL, *video = NULL, *video_transport = NULL;
1047         iks *audio_candidates[session->maxicecandidates], *video_candidates[session->maxicecandidates];
1048         int i, res = 0;
1049
1050         if (!(iq = iks_new("iq")) ||
1051             !(jingle = iks_new(session->transport == JINGLE_TRANSPORT_GOOGLE_V1 ? "session" : "jingle"))) {
1052                 iks_delete(iq);
1053                 jingle_queue_hangup_with_cause(session, AST_CAUSE_SWITCH_CONGESTION);
1054                 ast_log(LOG_ERROR, "Failed to allocate stanzas for transport-info message, hanging up session '%s'\n", session->sid);
1055                 return;
1056         }
1057
1058         memset(audio_candidates, 0, sizeof(audio_candidates));
1059         memset(video_candidates, 0, sizeof(video_candidates));
1060
1061         iks_insert_attrib(iq, "from", session->connection->jid->full);
1062         iks_insert_attrib(iq, "to", from);
1063         iks_insert_attrib(iq, "type", "set");
1064         iks_insert_attrib(iq, "id", session->connection->mid);
1065         ast_xmpp_increment_mid(session->connection->mid);
1066
1067         if (session->transport == JINGLE_TRANSPORT_GOOGLE_V1) {
1068                 iks_insert_attrib(jingle, "type", "candidates");
1069                 iks_insert_attrib(jingle, "id", session->sid);
1070                 iks_insert_attrib(jingle, "xmlns", GOOGLE_SESSION_NS);
1071                 iks_insert_attrib(jingle, "initiator", session->outgoing ? session->connection->jid->full : from);
1072         } else {
1073                 iks_insert_attrib(jingle, "action", "transport-info");
1074                 iks_insert_attrib(jingle, "sid", session->sid);
1075                 iks_insert_attrib(jingle, "xmlns", JINGLE_NS);
1076         }
1077         iks_insert_node(iq, jingle);
1078
1079         if (session->rtp) {
1080                 if (session->transport == JINGLE_TRANSPORT_GOOGLE_V1) {
1081                         /* V1 protocol has the candidates directly in the session */
1082                         res = jingle_add_google_candidates_to_transport(session->rtp, jingle, audio_candidates, 0, session->transport, session->maxicecandidates);
1083                 } else if ((audio = iks_new("content")) && (audio_transport = iks_new("transport"))) {
1084                         iks_insert_attrib(audio, "creator", session->outgoing ? "initiator" : "responder");
1085                         iks_insert_attrib(audio, "name", session->audio_name);
1086                         iks_insert_node(jingle, audio);
1087                         iks_insert_node(audio, audio_transport);
1088
1089                         if (session->transport == JINGLE_TRANSPORT_ICE_UDP) {
1090                                 res = jingle_add_ice_udp_candidates_to_transport(session->rtp, audio_transport, audio_candidates, session->maxicecandidates);
1091                         } else if (session->transport == JINGLE_TRANSPORT_GOOGLE_V2) {
1092                                 res = jingle_add_google_candidates_to_transport(session->rtp, audio_transport, audio_candidates, 0, session->transport,
1093                                                                                 session->maxicecandidates);
1094                         }
1095                 } else {
1096                         res = -1;
1097                 }
1098         }
1099
1100         if ((session->transport != JINGLE_TRANSPORT_GOOGLE_V1) && !res && session->vrtp) {
1101                 if ((video = iks_new("content")) && (video_transport = iks_new("transport"))) {
1102                         iks_insert_attrib(video, "creator", session->outgoing ? "initiator" : "responder");
1103                         iks_insert_attrib(video, "name", session->video_name);
1104                         iks_insert_node(jingle, video);
1105                         iks_insert_node(video, video_transport);
1106
1107                         if (session->transport == JINGLE_TRANSPORT_ICE_UDP) {
1108                                 res = jingle_add_ice_udp_candidates_to_transport(session->vrtp, video_transport, video_candidates, session->maxicecandidates);
1109                         } else if (session->transport == JINGLE_TRANSPORT_GOOGLE_V2) {
1110                                 res = jingle_add_google_candidates_to_transport(session->vrtp, video_transport, video_candidates, 1, session->transport,
1111                                                                                 session->maxicecandidates);
1112                         }
1113                 } else {
1114                         res = -1;
1115                 }
1116         }
1117
1118         if (!res) {
1119                 ast_xmpp_client_send(session->connection, iq);
1120         } else {
1121                 jingle_queue_hangup_with_cause(session, AST_CAUSE_SWITCH_CONGESTION);
1122         }
1123
1124         /* Clean up after ourselves */
1125         for (i = 0; i < session->maxicecandidates; i++) {
1126                 iks_delete(video_candidates[i]);
1127                 iks_delete(audio_candidates[i]);
1128         }
1129
1130         iks_delete(video_transport);
1131         iks_delete(video);
1132         iks_delete(audio_transport);
1133         iks_delete(audio);
1134         iks_delete(jingle);
1135         iks_delete(iq);
1136 }
1137
1138 /*! \brief Internal helper function which adds payloads to a description */
1139 static int jingle_add_payloads_to_description(struct jingle_session *session, struct ast_rtp_instance *rtp, iks *description, iks **payloads, enum ast_format_type type)
1140 {
1141         struct ast_format format;
1142         int x = 0, i = 0, res = 0;
1143
1144         for (x = 0; (x < AST_CODEC_PREF_SIZE) && (i < (session->maxpayloads - 2)); x++) {
1145                 int rtp_code;
1146                 iks *payload;
1147                 char tmp[32];
1148
1149                 if (!ast_codec_pref_index(&session->prefs, x, &format)) {
1150                         break;
1151                 }
1152
1153                 if (AST_FORMAT_GET_TYPE(format.id) != type) {
1154                         continue;
1155                 }
1156
1157                 if (!ast_format_cap_iscompatible(session->jointcap, &format)) {
1158                         continue;
1159                 }
1160
1161                 if (((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(rtp), 1, &format, 0)) == -1) ||
1162                     (!(payload = iks_new("payload-type")))) {
1163                         return -1;
1164                 }
1165
1166                 if (session->transport == JINGLE_TRANSPORT_GOOGLE_V1) {
1167                         iks_insert_attrib(payload, "xmlns", GOOGLE_PHONE_NS);
1168                 }
1169
1170                 snprintf(tmp, sizeof(tmp), "%d", rtp_code);
1171                 iks_insert_attrib(payload, "id", tmp);
1172                 iks_insert_attrib(payload, "name", ast_rtp_lookup_mime_subtype2(1, &format, 0, 0));
1173                 iks_insert_attrib(payload, "channels", "1");
1174
1175                 if ((format.id == AST_FORMAT_G722) && ((session->transport == JINGLE_TRANSPORT_GOOGLE_V1) || (session->transport == JINGLE_TRANSPORT_GOOGLE_V2))) {
1176                         iks_insert_attrib(payload, "clockrate", "16000");
1177                 } else {
1178                         snprintf(tmp, sizeof(tmp), "%d", ast_rtp_lookup_sample_rate2(1, &format, 0));
1179                         iks_insert_attrib(payload, "clockrate", tmp);
1180                 }
1181
1182                 if ((type == AST_FORMAT_TYPE_VIDEO) && (session->transport == JINGLE_TRANSPORT_GOOGLE_V2)) {
1183                         iks *parameter;
1184
1185                         /* Google requires these parameters to be set, but alas we can not give accurate values so use some safe defaults */
1186                         if ((parameter = iks_new("parameter"))) {
1187                                 iks_insert_attrib(parameter, "name", "width");
1188                                 iks_insert_attrib(parameter, "value", "640");
1189                                 iks_insert_node(payload, parameter);
1190                         }
1191                         if ((parameter = iks_new("parameter"))) {
1192                                 iks_insert_attrib(parameter, "name", "height");
1193                                 iks_insert_attrib(parameter, "value", "480");
1194                                 iks_insert_node(payload, parameter);
1195                         }
1196                         if ((parameter = iks_new("parameter"))) {
1197                                 iks_insert_attrib(parameter, "name", "framerate");
1198                                 iks_insert_attrib(parameter, "value", "30");
1199                                 iks_insert_node(payload, parameter);
1200                         }
1201                 }
1202
1203                 iks_insert_node(description, payload);
1204                 payloads[i++] = payload;
1205         }
1206         /* If this is for audio and there is room for RFC2833 add it in */
1207         if ((type == AST_FORMAT_TYPE_AUDIO) && (i < session->maxpayloads)) {
1208                 iks *payload;
1209
1210                 if ((payload = iks_new("payload-type"))) {
1211                         if (session->transport == JINGLE_TRANSPORT_GOOGLE_V1) {
1212                                 iks_insert_attrib(payload, "xmlns", GOOGLE_PHONE_NS);
1213                         }
1214
1215                         iks_insert_attrib(payload, "id", "101");
1216                         iks_insert_attrib(payload, "name", "telephone-event");
1217                         iks_insert_attrib(payload, "channels", "1");
1218                         iks_insert_attrib(payload, "clockrate", "8000");
1219                         iks_insert_node(description, payload);
1220                         payloads[i++] = payload;
1221                 }
1222         }
1223
1224         return res;
1225 }
1226
1227 /*! \brief Helper function which adds content to a description */
1228 static int jingle_add_content(struct jingle_session *session, iks *jingle, iks *content, iks *description, iks *transport,
1229                               const char *name, enum ast_format_type type, struct ast_rtp_instance *rtp, iks **payloads)
1230 {
1231         int res = 0;
1232
1233         if (session->transport != JINGLE_TRANSPORT_GOOGLE_V1) {
1234                 iks_insert_attrib(content, "creator", session->outgoing ? "initiator" : "responder");
1235                 iks_insert_attrib(content, "name", name);
1236                 iks_insert_node(jingle, content);
1237
1238                 iks_insert_attrib(description, "xmlns", JINGLE_RTP_NS);
1239                 if (type == AST_FORMAT_TYPE_AUDIO) {
1240                         iks_insert_attrib(description, "media", "audio");
1241                 } else if (type == AST_FORMAT_TYPE_VIDEO) {
1242                         iks_insert_attrib(description, "media", "video");
1243                 } else {
1244                         return -1;
1245                 }
1246                 iks_insert_node(content, description);
1247         } else {
1248                 iks_insert_attrib(description, "xmlns", GOOGLE_PHONE_NS);
1249                 iks_insert_node(jingle, description);
1250         }
1251
1252         if (!(res = jingle_add_payloads_to_description(session, rtp, description, payloads, type))) {
1253                 if (session->transport == JINGLE_TRANSPORT_ICE_UDP) {
1254                         iks_insert_attrib(transport, "xmlns", JINGLE_ICE_UDP_NS);
1255                         iks_insert_node(content, transport);
1256                 } else if (session->transport == JINGLE_TRANSPORT_GOOGLE_V2) {
1257                         iks_insert_attrib(transport, "xmlns", GOOGLE_TRANSPORT_NS);
1258                         iks_insert_node(content, transport);
1259                 }
1260         }
1261
1262         return res;
1263 }
1264
1265 /*! \brief Internal function which sends a complete session message */
1266 static void jingle_send_session_action(struct jingle_session *session, const char *action)
1267 {
1268         iks *iq, *jingle, *audio = NULL, *audio_description = NULL, *video = NULL, *video_description = NULL;
1269         iks *audio_payloads[session->maxpayloads], *video_payloads[session->maxpayloads];
1270         iks *audio_transport = NULL, *video_transport = NULL;
1271         int i, res = 0;
1272
1273         if (!(iq = iks_new("iq")) ||
1274             !(jingle = iks_new(session->transport == JINGLE_TRANSPORT_GOOGLE_V1 ? "session" : "jingle"))) {
1275                 jingle_queue_hangup_with_cause(session, AST_CAUSE_SWITCH_CONGESTION);
1276                 iks_delete(iq);
1277                 return;
1278         }
1279
1280         memset(audio_payloads, 0, sizeof(audio_payloads));
1281         memset(video_payloads, 0, sizeof(video_payloads));
1282
1283         iks_insert_attrib(iq, "from", session->connection->jid->full);
1284         iks_insert_attrib(iq, "to", session->remote);
1285         iks_insert_attrib(iq, "type", "set");
1286         iks_insert_attrib(iq, "id", session->connection->mid);
1287         ast_xmpp_increment_mid(session->connection->mid);
1288
1289         if (session->transport == JINGLE_TRANSPORT_GOOGLE_V1) {
1290                 iks_insert_attrib(jingle, "type", action);
1291                 iks_insert_attrib(jingle, "id", session->sid);
1292                 iks_insert_attrib(jingle, "xmlns", GOOGLE_SESSION_NS);
1293         } else {
1294                 iks_insert_attrib(jingle, "action", action);
1295                 iks_insert_attrib(jingle, "sid", session->sid);
1296                 iks_insert_attrib(jingle, "xmlns", JINGLE_NS);
1297         }
1298
1299         if (!strcasecmp(action, "session-initiate") || !strcasecmp(action, "initiate") || !strcasecmp(action, "accept")) {
1300                 iks_insert_attrib(jingle, "initiator", session->outgoing ? session->connection->jid->full : session->remote);
1301         }
1302
1303         iks_insert_node(iq, jingle);
1304
1305         if (session->rtp && (audio = iks_new("content")) && (audio_description = iks_new("description")) &&
1306             (audio_transport = iks_new("transport"))) {
1307                 res = jingle_add_content(session, jingle, audio, audio_description, audio_transport, session->audio_name,
1308                                          AST_FORMAT_TYPE_AUDIO, session->rtp, audio_payloads);
1309         } else {
1310                 ast_log(LOG_ERROR, "Failed to allocate audio content stanzas for session '%s', hanging up\n", session->sid);
1311                 res = -1;
1312         }
1313
1314         if ((session->transport != JINGLE_TRANSPORT_GOOGLE_V1) && !res && session->vrtp) {
1315                 if ((video = iks_new("content")) && (video_description = iks_new("description")) &&
1316                     (video_transport = iks_new("transport"))) {
1317                         res = jingle_add_content(session, jingle, video, video_description, video_transport, session->video_name,
1318                                                  AST_FORMAT_TYPE_VIDEO, session->vrtp, video_payloads);
1319                 } else {
1320                         ast_log(LOG_ERROR, "Failed to allocate video content stanzas for session '%s', hanging up\n", session->sid);
1321                         res = -1;
1322                 }
1323         }
1324
1325         if (!res) {
1326                 ast_xmpp_client_send(session->connection, iq);
1327         } else {
1328                 jingle_queue_hangup_with_cause(session, AST_CAUSE_SWITCH_CONGESTION);
1329         }
1330
1331         iks_delete(video_transport);
1332         iks_delete(audio_transport);
1333
1334         for (i = 0; i < session->maxpayloads; i++) {
1335                 iks_delete(video_payloads[i]);
1336                 iks_delete(audio_payloads[i]);
1337         }
1338
1339         iks_delete(video_description);
1340         iks_delete(video);
1341         iks_delete(audio_description);
1342         iks_delete(audio);
1343         iks_delete(jingle);
1344         iks_delete(iq);
1345 }
1346
1347 /*! \brief Internal function which sends a session-inititate message */
1348 static void jingle_send_session_initiate(struct jingle_session *session)
1349 {
1350         jingle_send_session_action(session, session->transport == JINGLE_TRANSPORT_GOOGLE_V1 ? "initiate" : "session-initiate");
1351 }
1352
1353 /*! \brief Internal function which sends a session-accept message */
1354 static void jingle_send_session_accept(struct jingle_session *session)
1355 {
1356         jingle_send_session_action(session, session->transport == JINGLE_TRANSPORT_GOOGLE_V1 ? "accept" : "session-accept");
1357 }
1358
1359 /*! \brief Callback for when a response is received for an outgoing session-initiate message */
1360 static int jingle_outgoing_hook(void *data, ikspak *pak)
1361 {
1362         struct jingle_session *session = data;
1363         iks *error = iks_find(pak->x, "error"), *redirect;
1364
1365         /* In all cases this hook is done with */
1366         iks_filter_remove_rule(session->connection->filter, session->rule);
1367         session->rule = NULL;
1368
1369         ast_callid_threadassoc_add(session->callid);
1370
1371         /* If no error occurred they accepted our session-initiate message happily */
1372         if (!error) {
1373                 struct ast_channel *chan;
1374
1375                 if ((chan = jingle_session_lock_full(session))) {
1376                         ast_queue_control(chan, AST_CONTROL_PROCEEDING);
1377                         ast_channel_unlock(chan);
1378                         ast_channel_unref(chan);
1379                 }
1380                 ao2_unlock(session);
1381
1382                 jingle_send_transport_info(session, iks_find_attrib(pak->x, "from"));
1383
1384                 goto end;
1385         }
1386
1387         /* Assume that because this is an error the session is gone, there is only one case where this is incorrect - a redirect */
1388         session->gone = 1;
1389
1390         /* Map the error we received to an appropriate cause code and hang up the channel */
1391         if ((redirect = iks_find_with_attrib(error, "redirect", "xmlns", XMPP_STANZAS_NS))) {
1392                 iks *to = iks_child(redirect);
1393                 char *target;
1394
1395                 if (to && (target = iks_name(to)) && !ast_strlen_zero(target)) {
1396                         /* Make the xmpp: go away if it is present */
1397                         if (!strncmp(target, "xmpp:", 5)) {
1398                                 target += 5;
1399                         }
1400
1401                         /* This is actually a fairly simple operation - we update the remote and send another session-initiate */
1402                         ast_copy_string(session->remote, target, sizeof(session->remote));
1403
1404                         /* Add a new hook so we can get the status of redirected session */
1405                         session->rule = iks_filter_add_rule(session->connection->filter, jingle_outgoing_hook, session,
1406                                                             IKS_RULE_ID, session->connection->mid, IKS_RULE_DONE);
1407
1408                         jingle_send_session_initiate(session);
1409
1410                         session->gone = 0;
1411                 } else {
1412                         jingle_queue_hangup_with_cause(session, AST_CAUSE_PROTOCOL_ERROR);
1413                 }
1414         } else if (iks_find_with_attrib(error, "service-unavailable", "xmlns", XMPP_STANZAS_NS)) {
1415                 jingle_queue_hangup_with_cause(session, AST_CAUSE_CONGESTION);
1416         } else if (iks_find_with_attrib(error, "resource-constraint", "xmlns", XMPP_STANZAS_NS)) {
1417                 jingle_queue_hangup_with_cause(session, AST_CAUSE_REQUESTED_CHAN_UNAVAIL);
1418         } else if (iks_find_with_attrib(error, "bad-request", "xmlns", XMPP_STANZAS_NS)) {
1419                 jingle_queue_hangup_with_cause(session, AST_CAUSE_PROTOCOL_ERROR);
1420         } else if (iks_find_with_attrib(error, "remote-server-not-found", "xmlns", XMPP_STANZAS_NS)) {
1421                 jingle_queue_hangup_with_cause(session, AST_CAUSE_NO_ROUTE_DESTINATION);
1422         } else if (iks_find_with_attrib(error, "feature-not-implemented", "xmlns", XMPP_STANZAS_NS)) {
1423                 /* Assume that this occurred because the remote side does not support our transport, so drop it down one and try again */
1424                 session->transport--;
1425
1426                 /* If we still have a viable transport mechanism re-send the session-initiate */
1427                 if (session->transport != JINGLE_TRANSPORT_NONE) {
1428                         struct ast_rtp_engine_ice *ice;
1429
1430                         if (((session->transport == JINGLE_TRANSPORT_GOOGLE_V2) ||
1431                              (session->transport == JINGLE_TRANSPORT_GOOGLE_V1)) &&
1432                             (ice = ast_rtp_instance_get_ice(session->rtp))) {
1433                                 /* We stop built in ICE support because we need to fall back to old old old STUN support */
1434                                 ice->stop(session->rtp);
1435                         }
1436
1437                         /* Re-send the message to the *original* target and not a redirected one */
1438                         ast_copy_string(session->remote, session->remote_original, sizeof(session->remote));
1439
1440                         session->rule = iks_filter_add_rule(session->connection->filter, jingle_outgoing_hook, session,
1441                                                             IKS_RULE_ID, session->connection->mid, IKS_RULE_DONE);
1442
1443                         jingle_send_session_initiate(session);
1444
1445                         session->gone = 0;
1446                 } else {
1447                         /* Otherwise we have exhausted all transports */
1448                         jingle_queue_hangup_with_cause(session, AST_CAUSE_FACILITY_NOT_IMPLEMENTED);
1449                 }
1450         } else {
1451                 jingle_queue_hangup_with_cause(session, AST_CAUSE_PROTOCOL_ERROR);
1452         }
1453
1454 end:
1455         ast_callid_threadassoc_remove();
1456
1457         return IKS_FILTER_EAT;
1458 }
1459
1460 /*! \brief Function called by core when we should answer a Jingle session */
1461 static int jingle_answer(struct ast_channel *ast)
1462 {
1463         struct jingle_session *session = ast_channel_tech_pvt(ast);
1464
1465         /* The channel has already been answered so we don't need to do anything */
1466         if (ast_channel_state(ast) == AST_STATE_UP) {
1467                 return 0;
1468         }
1469
1470         jingle_send_session_accept(session);
1471
1472         return 0;
1473 }
1474
1475 /*! \brief Function called by core to read any waiting frames */
1476 static struct ast_frame *jingle_read(struct ast_channel *ast)
1477 {
1478         struct jingle_session *session = ast_channel_tech_pvt(ast);
1479         struct ast_frame *frame = &ast_null_frame;
1480
1481         switch (ast_channel_fdno(ast)) {
1482         case 0:
1483                 if (session->rtp) {
1484                         frame = ast_rtp_instance_read(session->rtp, 0);
1485                 }
1486                 break;
1487         case 1:
1488                 if (session->rtp) {
1489                         frame = ast_rtp_instance_read(session->rtp, 1);
1490                 }
1491                 break;
1492         case 2:
1493                 if (session->vrtp) {
1494                         frame = ast_rtp_instance_read(session->vrtp, 0);
1495                 }
1496                 break;
1497         case 3:
1498                 if (session->vrtp) {
1499                         frame = ast_rtp_instance_read(session->vrtp, 1);
1500                 }
1501                 break;
1502         default:
1503                 break;
1504         }
1505
1506         if (frame && frame->frametype == AST_FRAME_VOICE &&
1507             !ast_format_cap_iscompatible(ast_channel_nativeformats(ast), &frame->subclass.format)) {
1508                 if (!ast_format_cap_iscompatible(session->jointcap, &frame->subclass.format)) {
1509                         ast_debug(1, "Bogus frame of format '%s' received from '%s'!\n",
1510                                   ast_getformatname(&frame->subclass.format), ast_channel_name(ast));
1511                         ast_frfree(frame);
1512                         frame = &ast_null_frame;
1513                 } else {
1514                         ast_debug(1, "Oooh, format changed to %s\n",
1515                                   ast_getformatname(&frame->subclass.format));
1516                         ast_format_cap_remove_bytype(ast_channel_nativeformats(ast), AST_FORMAT_TYPE_AUDIO);
1517                         ast_format_cap_add(ast_channel_nativeformats(ast), &frame->subclass.format);
1518                         ast_set_read_format(ast, ast_channel_readformat(ast));
1519                         ast_set_write_format(ast, ast_channel_writeformat(ast));
1520                 }
1521         }
1522
1523         return frame;
1524 }
1525
1526 /*! \brief Function called by core to write frames */
1527 static int jingle_write(struct ast_channel *ast, struct ast_frame *frame)
1528 {
1529         struct jingle_session *session = ast_channel_tech_pvt(ast);
1530         int res = 0;
1531         char buf[256];
1532
1533         switch (frame->frametype) {
1534         case AST_FRAME_VOICE:
1535                 if (!(ast_format_cap_iscompatible(ast_channel_nativeformats(ast), &frame->subclass.format))) {
1536                         ast_log(LOG_WARNING,
1537                                 "Asked to transmit frame type %s, while native formats is %s (read/write = %s/%s)\n",
1538                                 ast_getformatname(&frame->subclass.format),
1539                                 ast_getformatname_multiple(buf, sizeof(buf), ast_channel_nativeformats(ast)),
1540                                 ast_getformatname(ast_channel_readformat(ast)),
1541                                 ast_getformatname(ast_channel_writeformat(ast)));
1542                         return 0;
1543                 }
1544                 if (session && session->rtp) {
1545                         res = ast_rtp_instance_write(session->rtp, frame);
1546                 }
1547                 break;
1548         case AST_FRAME_VIDEO:
1549                 if (session && session->vrtp) {
1550                         res = ast_rtp_instance_write(session->vrtp, frame);
1551                 }
1552                 break;
1553         default:
1554                 ast_log(LOG_WARNING, "Can't send %d type frames with Jingle write\n",
1555                         frame->frametype);
1556                 return 0;
1557         }
1558
1559         return res;
1560 }
1561
1562 /*! \brief Function called by core to change the underlying owner channel */
1563 static int jingle_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1564 {
1565         struct jingle_session *session = ast_channel_tech_pvt(newchan);
1566
1567         ao2_lock(session);
1568
1569         session->owner = newchan;
1570
1571         ao2_unlock(session);
1572
1573         return 0;
1574 }
1575
1576 /*! \brief Function called by core to ask the channel to indicate some sort of condition */
1577 static int jingle_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
1578 {
1579         struct jingle_session *session = ast_channel_tech_pvt(ast);
1580         int res = 0;
1581
1582         switch (condition) {
1583         case AST_CONTROL_RINGING:
1584                 if (ast_channel_state(ast) == AST_STATE_RING) {
1585                         jingle_send_session_info(session, "ringing xmlns='urn:xmpp:jingle:apps:rtp:info:1'");
1586                 } else {
1587                         res = -1;
1588                 }
1589                 break;
1590         case AST_CONTROL_BUSY:
1591                 if (ast_channel_state(ast) != AST_STATE_UP) {
1592                         ast_channel_hangupcause_set(ast, AST_CAUSE_BUSY);
1593                         ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
1594                 } else {
1595                         res = -1;
1596                 }
1597                 break;
1598         case AST_CONTROL_CONGESTION:
1599                 if (ast_channel_state(ast) != AST_STATE_UP) {
1600                         ast_channel_hangupcause_set(ast, AST_CAUSE_CONGESTION);
1601                         ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
1602                 } else {
1603                         res = -1;
1604                 }
1605                 break;
1606         case AST_CONTROL_INCOMPLETE:
1607                 if (ast_channel_state(ast) != AST_STATE_UP) {
1608                         ast_channel_hangupcause_set(ast, AST_CAUSE_CONGESTION);
1609                         ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
1610                 }
1611                 break;
1612         case AST_CONTROL_HOLD:
1613                 ast_moh_start(ast, data, NULL);
1614                 break;
1615         case AST_CONTROL_UNHOLD:
1616                 ast_moh_stop(ast);
1617                 break;
1618         case AST_CONTROL_SRCUPDATE:
1619                 if (session->rtp) {
1620                         ast_rtp_instance_update_source(session->rtp);
1621                 }
1622                 break;
1623         case AST_CONTROL_SRCCHANGE:
1624                 if (session->rtp) {
1625                         ast_rtp_instance_change_source(session->rtp);
1626                 }
1627                 break;
1628         case AST_CONTROL_VIDUPDATE:
1629         case AST_CONTROL_UPDATE_RTP_PEER:
1630         case AST_CONTROL_CONNECTED_LINE:
1631                 break;
1632         case AST_CONTROL_PVT_CAUSE_CODE:
1633         case -1:
1634                 res = -1;
1635                 break;
1636         default:
1637                 ast_log(LOG_NOTICE, "Don't know how to indicate condition '%d'\n", condition);
1638                 res = -1;
1639         }
1640
1641         return res;
1642 }
1643
1644 /*! \brief Function called by core to send text to the remote party of the Jingle session */
1645 static int jingle_sendtext(struct ast_channel *chan, const char *text)
1646 {
1647         struct jingle_session *session = ast_channel_tech_pvt(chan);
1648
1649         return ast_xmpp_client_send_message(session->connection, session->remote, text);
1650 }
1651
1652 /*! \brief Function called by core to start a DTMF digit */
1653 static int jingle_digit_begin(struct ast_channel *chan, char digit)
1654 {
1655         struct jingle_session *session = ast_channel_tech_pvt(chan);
1656
1657         if (session->rtp) {
1658                 ast_rtp_instance_dtmf_begin(session->rtp, digit);
1659         }
1660
1661         return 0;
1662 }
1663
1664 /*! \brief Function called by core to stop a DTMF digit */
1665 static int jingle_digit_end(struct ast_channel *ast, char digit, unsigned int duration)
1666 {
1667         struct jingle_session *session = ast_channel_tech_pvt(ast);
1668
1669         if (session->rtp) {
1670                 ast_rtp_instance_dtmf_end_with_duration(session->rtp, digit, duration);
1671         }
1672
1673         return 0;
1674 }
1675
1676 /*! \brief Function called by core to actually start calling a remote party */
1677 static int jingle_call(struct ast_channel *ast, const char *dest, int timeout)
1678 {
1679         struct jingle_session *session = ast_channel_tech_pvt(ast);
1680
1681         ast_setstate(ast, AST_STATE_RING);
1682
1683         /* Since we have no idea of the remote capabilities use ours for now */
1684         ast_format_cap_copy(session->jointcap, session->cap);
1685
1686         /* We set up a hook so we can know when our session-initiate message was accepted or rejected */
1687         session->rule = iks_filter_add_rule(session->connection->filter, jingle_outgoing_hook, session,
1688                                             IKS_RULE_ID, session->connection->mid, IKS_RULE_DONE);
1689
1690         jingle_send_session_initiate(session);
1691
1692         return 0;
1693 }
1694
1695 /*! \brief Function called by core to hang up a Jingle session */
1696 static int jingle_hangup(struct ast_channel *ast)
1697 {
1698         struct jingle_session *session = ast_channel_tech_pvt(ast);
1699
1700         ao2_lock(session);
1701
1702         if ((ast_channel_state(ast) != AST_STATE_DOWN) && !session->gone) {
1703                 int cause = (session->owner ? ast_channel_hangupcause(session->owner) : AST_CAUSE_CONGESTION);
1704                 const char *reason = "success";
1705                 int i;
1706
1707                 /* Get the appropriate reason and send a session-terminate */
1708                 for (i = 0; i < ARRAY_LEN(jingle_reason_mappings); i++) {
1709                         if (jingle_reason_mappings[i].cause == cause) {
1710                                 reason = jingle_reason_mappings[i].reason;
1711                                 break;
1712                         }
1713                 }
1714
1715                 jingle_send_session_terminate(session, reason);
1716         }
1717
1718         ast_channel_tech_pvt_set(ast, NULL);
1719         session->owner = NULL;
1720
1721         ao2_unlink(session->state->sessions, session);
1722         ao2_ref(session->state, -1);
1723
1724         ao2_unlock(session);
1725         ao2_ref(session, -1);
1726
1727         return 0;
1728 }
1729
1730 /*! \brief Function called by core to create a new outgoing Jingle session */
1731 static struct ast_channel *jingle_request(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, const char *data, int *cause)
1732 {
1733         RAII_VAR(struct jingle_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
1734         RAII_VAR(struct jingle_endpoint *, endpoint, NULL, ao2_cleanup);
1735         char *dialed, target[200] = "";
1736         struct ast_xmpp_buddy *buddy;
1737         struct jingle_session *session;
1738         struct ast_channel *chan;
1739         enum jingle_transport transport = JINGLE_TRANSPORT_NONE;
1740         struct ast_rtp_engine_ice *ice;
1741         AST_DECLARE_APP_ARGS(args,
1742                              AST_APP_ARG(name);
1743                              AST_APP_ARG(target);
1744                 );
1745
1746         /* We require at a minimum one audio format to be requested */
1747         if (!ast_format_cap_has_type(cap, AST_FORMAT_TYPE_AUDIO)) {
1748                 ast_log(LOG_ERROR, "Motif channel driver requires an audio format when dialing a destination\n");
1749                 *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
1750                 return NULL;
1751         }
1752
1753         if (ast_strlen_zero(data) || !(dialed = ast_strdupa(data))) {
1754                 ast_log(LOG_ERROR, "Unable to create channel with empty destination.\n");
1755                 *cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
1756                 return NULL;
1757         }
1758
1759         /* Parse the given dial string and validate the results */
1760         AST_NONSTANDARD_APP_ARGS(args, dialed, '/');
1761
1762         if (ast_strlen_zero(args.name) || ast_strlen_zero(args.target)) {
1763                 ast_log(LOG_ERROR, "Unable to determine endpoint name and target.\n");
1764                 *cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
1765                 return NULL;
1766         }
1767
1768         if (!(endpoint = jingle_endpoint_find(cfg->endpoints, args.name))) {
1769                 ast_log(LOG_ERROR, "Endpoint '%s' does not exist.\n", args.name);
1770                 *cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
1771                 return NULL;
1772         }
1773
1774         ao2_lock(endpoint->state);
1775
1776         /* If we don't have a connection for the endpoint we can't exactly start a session on it */
1777         if (!endpoint->connection) {
1778                 ast_log(LOG_ERROR, "Unable to create Jingle session on endpoint '%s' as no valid connection exists\n", args.name);
1779                 *cause = AST_CAUSE_SWITCH_CONGESTION;
1780                 ao2_unlock(endpoint->state);
1781                 return NULL;
1782         }
1783
1784         /* Find the target in the roster so we can choose a resource */
1785         if ((buddy = ao2_find(endpoint->connection->buddies, args.target, OBJ_KEY))) {
1786                 struct ao2_iterator res;
1787                 struct ast_xmpp_resource *resource;
1788
1789                 /* Iterate through finding the first viable Jingle capable resource */
1790                 res = ao2_iterator_init(buddy->resources, 0);
1791                 while ((resource = ao2_iterator_next(&res))) {
1792                         if (resource->caps.jingle) {
1793                                 snprintf(target, sizeof(target), "%s/%s", args.target, resource->resource);
1794                                 transport = JINGLE_TRANSPORT_ICE_UDP;
1795                                 break;
1796                         } else if (resource->caps.google) {
1797                                 snprintf(target, sizeof(target), "%s/%s", args.target, resource->resource);
1798                                 transport = JINGLE_TRANSPORT_GOOGLE_V2;
1799                                 break;
1800                         }
1801                         ao2_ref(resource, -1);
1802                 }
1803                 ao2_iterator_destroy(&res);
1804
1805                 ao2_ref(buddy, -1);
1806         } else {
1807                 /* If the target is NOT in the roster use the provided target as-is */
1808                 ast_copy_string(target, args.target, sizeof(target));
1809         }
1810
1811         ao2_unlock(endpoint->state);
1812
1813         /* If no target was found we can't set up a session */
1814         if (ast_strlen_zero(target)) {
1815                 ast_log(LOG_ERROR, "Unable to create Jingle session on endpoint '%s' as no capable resource for target '%s' was found\n", args.name, args.target);
1816                 *cause = AST_CAUSE_SWITCH_CONGESTION;
1817                 return NULL;
1818         }
1819
1820         if (!(session = jingle_alloc(endpoint, target, NULL))) {
1821                 ast_log(LOG_ERROR, "Unable to create Jingle session on endpoint '%s'\n", args.name);
1822                 *cause = AST_CAUSE_SWITCH_CONGESTION;
1823                 return NULL;
1824         }
1825
1826         /* Update the transport if we learned what we should actually use */
1827         if (transport != JINGLE_TRANSPORT_NONE) {
1828                 session->transport = transport;
1829                 /* Note that for Google-V1 and Google-V2 we don't stop built-in ICE support, this will happen in jingle_new */
1830         }
1831
1832         if (!(chan = jingle_new(endpoint, session, AST_STATE_DOWN, target, requestor ? ast_channel_linkedid(requestor) : NULL, NULL))) {
1833                 ast_log(LOG_ERROR, "Unable to create Jingle channel on endpoint '%s'\n", args.name);
1834                 *cause = AST_CAUSE_SWITCH_CONGESTION;
1835                 ao2_ref(session, -1);
1836                 return NULL;
1837         }
1838
1839         /* If video was requested try to enable it on the session */
1840         if (ast_format_cap_has_type(cap, AST_FORMAT_TYPE_VIDEO)) {
1841                 jingle_enable_video(session);
1842         }
1843
1844         /* As this is outgoing set ourselves as controlling */
1845         if (session->rtp && (ice = ast_rtp_instance_get_ice(session->rtp))) {
1846                 ice->ice_lite(session->rtp);
1847         }
1848
1849         if (session->vrtp && (ice = ast_rtp_instance_get_ice(session->vrtp))) {
1850                 ice->ice_lite(session->vrtp);
1851         }
1852
1853         /* We purposely don't decrement the session here as there is a reference on the channel */
1854         ao2_link(endpoint->state->sessions, session);
1855
1856         return chan;
1857 }
1858
1859 /*! \brief Helper function which handles content descriptions */
1860 static int jingle_interpret_description(struct jingle_session *session, iks *description, const char *name, struct ast_rtp_instance **rtp)
1861 {
1862         char *media = iks_find_attrib(description, "media");
1863         struct ast_rtp_codecs codecs;
1864         iks *codec;
1865         int othercapability = 0;
1866
1867         /* Google-V1 is always carrying audio, but just doesn't tell us so */
1868         if (session->transport == JINGLE_TRANSPORT_GOOGLE_V1) {
1869                 media = "audio";
1870         } else if (ast_strlen_zero(media)) {
1871                 jingle_queue_hangup_with_cause(session, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
1872                 ast_log(LOG_ERROR, "Received a content description on session '%s' without a name\n", session->sid);
1873                 return -1;
1874         }
1875
1876         /* Determine the type of media that is being carried and update the RTP instance, as well as the name */
1877         if (!strcasecmp(media, "audio")) {
1878                 if (!ast_strlen_zero(name)) {
1879                         ast_string_field_set(session, audio_name, name);
1880                 }
1881                 *rtp = session->rtp;
1882                 ast_format_cap_remove_bytype(session->peercap, AST_FORMAT_TYPE_AUDIO);
1883                 ast_format_cap_remove_bytype(session->jointcap, AST_FORMAT_TYPE_AUDIO);
1884         } else if (!strcasecmp(media, "video")) {
1885                 if (!ast_strlen_zero(name)) {
1886                         ast_string_field_set(session, video_name, name);
1887                 }
1888
1889                 jingle_enable_video(session);
1890                 *rtp = session->vrtp;
1891
1892                 /* If video is not present cancel this session */
1893                 if (!session->vrtp) {
1894                         jingle_queue_hangup_with_cause(session, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
1895                         ast_log(LOG_ERROR, "Received a video content description on session '%s' but could not enable video\n", session->sid);
1896                         return -1;
1897                 }
1898
1899                 ast_format_cap_remove_bytype(session->peercap, AST_FORMAT_TYPE_VIDEO);
1900                 ast_format_cap_remove_bytype(session->jointcap, AST_FORMAT_TYPE_VIDEO);
1901         } else {
1902                 /* Unknown media type */
1903                 jingle_queue_hangup_with_cause(session, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
1904                 ast_log(LOG_ERROR, "Unsupported media type '%s' received in content description on session '%s'\n", media, session->sid);
1905                 return -1;
1906         }
1907
1908         if (ast_rtp_codecs_payloads_initialize(&codecs)) {
1909                 jingle_queue_hangup_with_cause(session, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
1910                 ast_log(LOG_ERROR, "Could not initialize codecs for negotiation on session '%s'\n", session->sid);
1911                 return -1;
1912         }
1913
1914         /* Iterate the codecs updating the relevant RTP instance as we go */
1915         for (codec = iks_child(description); codec; codec = iks_next(codec)) {
1916                 char *id = iks_find_attrib(codec, "id"), *name = iks_find_attrib(codec, "name");
1917                 char *clockrate = iks_find_attrib(codec, "clockrate");
1918                 int rtp_id, rtp_clockrate;
1919
1920                 if (!ast_strlen_zero(id) && !ast_strlen_zero(name) && (sscanf(id, "%30d", &rtp_id) == 1)) {
1921                         ast_rtp_codecs_payloads_set_m_type(&codecs, NULL, rtp_id);
1922
1923                         if (!ast_strlen_zero(clockrate) && (sscanf(clockrate, "%30d", &rtp_clockrate) == 1)) {
1924                                 ast_rtp_codecs_payloads_set_rtpmap_type_rate(&codecs, NULL, rtp_id, media, name, 0, rtp_clockrate);
1925                         } else {
1926                                 ast_rtp_codecs_payloads_set_rtpmap_type(&codecs, NULL, rtp_id, media, name, 0);
1927                         }
1928                 }
1929         }
1930
1931         ast_rtp_codecs_payload_formats(&codecs, session->peercap, &othercapability);
1932         ast_format_cap_joint_append(session->cap, session->peercap, session->jointcap);
1933
1934         if (ast_format_cap_is_empty(session->jointcap)) {
1935                 /* We have no compatible codecs, so terminate the session appropriately */
1936                 jingle_queue_hangup_with_cause(session, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
1937                 ast_rtp_codecs_payloads_destroy(&codecs);
1938                 return -1;
1939         }
1940
1941         ast_rtp_codecs_payloads_copy(&codecs, ast_rtp_instance_get_codecs(*rtp), *rtp);
1942         ast_rtp_codecs_payloads_destroy(&codecs);
1943
1944         return 0;
1945 }
1946
1947 /*! \brief Helper function which handles ICE-UDP transport information */
1948 static int jingle_interpret_ice_udp_transport(struct jingle_session *session, iks *transport, struct ast_rtp_instance *rtp)
1949 {
1950         struct ast_rtp_engine_ice *ice = ast_rtp_instance_get_ice(rtp);
1951         char *ufrag = iks_find_attrib(transport, "ufrag"), *pwd = iks_find_attrib(transport, "pwd");
1952         iks *candidate;
1953
1954         if (!ice) {
1955                 jingle_queue_hangup_with_cause(session, AST_CAUSE_SWITCH_CONGESTION);
1956                 ast_log(LOG_ERROR, "Received ICE-UDP transport information on session '%s' but ICE support not available\n", session->sid);
1957                 return -1;
1958         }
1959
1960         if (!ast_strlen_zero(ufrag) && !ast_strlen_zero(pwd)) {
1961                 ice->set_authentication(rtp, ufrag, pwd);
1962         }
1963
1964         for (candidate = iks_child(transport); candidate; candidate = iks_next(candidate)) {
1965                 char *component = iks_find_attrib(candidate, "component"), *foundation = iks_find_attrib(candidate, "foundation");
1966                 char *generation = iks_find_attrib(candidate, "generation"), *id = iks_find_attrib(candidate, "id");
1967                 char *ip = iks_find_attrib(candidate, "ip"), *network = iks_find_attrib(candidate, "network");
1968                 char *port = iks_find_attrib(candidate, "port"), *priority = iks_find_attrib(candidate, "priority");
1969                 char *protocol = iks_find_attrib(candidate, "protocol"), *type = iks_find_attrib(candidate, "type");
1970                 struct ast_rtp_engine_ice_candidate local_candidate = { 0, };
1971                 int real_port;
1972                 struct ast_sockaddr remote_address = { { 0, } };
1973
1974                 /* If this candidate is incomplete skip it */
1975                 if (ast_strlen_zero(component) || ast_strlen_zero(foundation) || ast_strlen_zero(generation) || ast_strlen_zero(id) ||
1976                     ast_strlen_zero(ip) || ast_strlen_zero(network) || ast_strlen_zero(port) || ast_strlen_zero(priority) ||
1977                     ast_strlen_zero(protocol) || ast_strlen_zero(type)) {
1978                         jingle_queue_hangup_with_cause(session, AST_CAUSE_PROTOCOL_ERROR);
1979                         ast_log(LOG_ERROR, "Incomplete ICE-UDP candidate received on session '%s'\n", session->sid);
1980                         return -1;
1981                 }
1982
1983                 if ((sscanf(component, "%30u", &local_candidate.id) != 1) ||
1984                     (sscanf(priority, "%30u", &local_candidate.priority) != 1) ||
1985                     (sscanf(port, "%30d", &real_port) != 1)) {
1986                         jingle_queue_hangup_with_cause(session, AST_CAUSE_PROTOCOL_ERROR);
1987                         ast_log(LOG_ERROR, "Invalid ICE-UDP candidate information received on session '%s'\n", session->sid);
1988                         return -1;
1989                 }
1990
1991                 local_candidate.foundation = foundation;
1992                 local_candidate.transport = protocol;
1993
1994                 ast_sockaddr_parse(&local_candidate.address, ip, PARSE_PORT_FORBID);
1995
1996                 /* We only support IPv4 right now */
1997                 if (!ast_sockaddr_is_ipv4(&local_candidate.address)) {
1998                         continue;
1999                 }
2000
2001                 ast_sockaddr_set_port(&local_candidate.address, real_port);
2002
2003                 if (!strcasecmp(type, "host")) {
2004                         local_candidate.type = AST_RTP_ICE_CANDIDATE_TYPE_HOST;
2005                 } else if (!strcasecmp(type, "srflx")) {
2006                         local_candidate.type = AST_RTP_ICE_CANDIDATE_TYPE_SRFLX;
2007                 } else if (!strcasecmp(type, "relay")) {
2008                         local_candidate.type = AST_RTP_ICE_CANDIDATE_TYPE_RELAYED;
2009                 } else {
2010                         continue;
2011                 }
2012
2013                 /* Worst case use the first viable address */
2014                 ast_rtp_instance_get_remote_address(rtp, &remote_address);
2015
2016                 if (ast_sockaddr_is_ipv4(&local_candidate.address) && ast_sockaddr_isnull(&remote_address)) {
2017                         ast_rtp_instance_set_remote_address(rtp, &local_candidate.address);
2018                 }
2019
2020                 ice->add_remote_candidate(rtp, &local_candidate);
2021         }
2022
2023         ice->start(rtp);
2024
2025         return 0;
2026 }
2027
2028 /*! \brief Helper function which handles Google transport information */
2029 static int jingle_interpret_google_transport(struct jingle_session *session, iks *transport, struct ast_rtp_instance *rtp)
2030 {
2031         struct ast_rtp_engine_ice *ice = ast_rtp_instance_get_ice(rtp);
2032         iks *candidate;
2033
2034         if (!ice) {
2035                 jingle_queue_hangup_with_cause(session, AST_CAUSE_SWITCH_CONGESTION);
2036                 ast_log(LOG_ERROR, "Received Google transport information on session '%s' but ICE support not available\n", session->sid);
2037                 return -1;
2038         }
2039
2040         /* If this session has not transitioned to the Google transport do so now */
2041         if ((session->transport != JINGLE_TRANSPORT_GOOGLE_V2) &&
2042             (session->transport != JINGLE_TRANSPORT_GOOGLE_V1)) {
2043                 /* Stop built-in ICE support... we need to fall back to the old old old STUN */
2044                 ice->stop(rtp);
2045
2046                 session->transport = JINGLE_TRANSPORT_GOOGLE_V2;
2047         }
2048
2049         for (candidate = iks_child(transport); candidate; candidate = iks_next(candidate)) {
2050                 char *address = iks_find_attrib(candidate, "address"), *port = iks_find_attrib(candidate, "port");
2051                 char *username = iks_find_attrib(candidate, "username"), *name = iks_find_attrib(candidate, "name");
2052                 char *protocol = iks_find_attrib(candidate, "protocol");
2053                 int real_port;
2054                 struct ast_sockaddr target = { { 0, } };
2055                 /* In Google land the combined value is 32 bytes */
2056                 char combined[33] = "";
2057
2058                 /* If this is NOT actually a candidate just skip it */
2059                 if (strcasecmp(iks_name(candidate), "candidate") &&
2060                     strcasecmp(iks_name(candidate), "p:candidate") &&
2061                     strcasecmp(iks_name(candidate), "ses:candidate")) {
2062                         continue;
2063                 }
2064
2065                 /* If this candidate is incomplete skip it */
2066                 if (ast_strlen_zero(address) || ast_strlen_zero(port) || ast_strlen_zero(username) ||
2067                     ast_strlen_zero(name)) {
2068                         jingle_queue_hangup_with_cause(session, AST_CAUSE_PROTOCOL_ERROR);
2069                         ast_log(LOG_ERROR, "Incomplete Google candidate received on session '%s'\n", session->sid);
2070                         return -1;
2071                 }
2072
2073                 /* We only support UDP so skip any other protocols */
2074                 if (!ast_strlen_zero(protocol) && strcasecmp(protocol, "udp")) {
2075                         continue;
2076                 }
2077
2078                 /* We only permit audio and video, not RTCP */
2079                 if (strcasecmp(name, "rtp") && strcasecmp(name, "video_rtp")) {
2080                         continue;
2081                 }
2082
2083                 /* Parse the target information so we can send a STUN request to the candidate */
2084                 if (sscanf(port, "%30d", &real_port) != 1) {
2085                         jingle_queue_hangup_with_cause(session, AST_CAUSE_PROTOCOL_ERROR);
2086                         ast_log(LOG_ERROR, "Invalid Google candidate port '%s' received on session '%s'\n", port, session->sid);
2087                         return -1;
2088                 }
2089                 ast_sockaddr_parse(&target, address, PARSE_PORT_FORBID);
2090                 ast_sockaddr_set_port(&target, real_port);
2091
2092                 /* Per the STUN support Google talk uses combine the two usernames */
2093                 snprintf(combined, sizeof(combined), "%s%s", username, ice->get_ufrag(rtp));
2094
2095                 /* This should appease the masses... we will actually change the remote address when we get their STUN packet */
2096                 ast_rtp_instance_stun_request(rtp, &target, combined);
2097         }
2098
2099         return 0;
2100 }
2101
2102 /*!
2103  * \brief Helper function which locates content stanzas and interprets them
2104  *
2105  * \note The session *must not* be locked before calling this
2106  */
2107 static int jingle_interpret_content(struct jingle_session *session, ikspak *pak)
2108 {
2109         iks *content;
2110         unsigned int changed = 0;
2111         struct ast_channel *chan;
2112
2113         /* Look at the content in the session initiation */
2114         for (content = iks_child(iks_child(pak->x)); content; content = iks_next(content)) {
2115                 char *name;
2116                 struct ast_rtp_instance *rtp = NULL;
2117                 iks *description, *transport;
2118
2119                 /* Ignore specific parts if they are known not to be useful */
2120                 if (!strcmp(iks_name(content), "conference-info")) {
2121                         continue;
2122                 }
2123
2124                 name = iks_find_attrib(content, "name");
2125
2126                 if (session->transport != JINGLE_TRANSPORT_GOOGLE_V1) {
2127                         /* If this content stanza has no name consider it invalid and move on */
2128                         if (ast_strlen_zero(name) && !(name = iks_find_attrib(content, "jin:name"))) {
2129                                 jingle_queue_hangup_with_cause(session, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
2130                                 ast_log(LOG_ERROR, "Received content without a name on session '%s'\n", session->sid);
2131                                 return -1;
2132                         }
2133
2134                         /* Try to pre-populate which RTP instance this content is relevant to */
2135                         if (!strcmp(session->audio_name, name)) {
2136                                 rtp = session->rtp;
2137                         } else if (!strcmp(session->video_name, name)) {
2138                                 rtp = session->vrtp;
2139                         }
2140                 } else {
2141                         /* Google-V1 has no concept of assocating things like the above does, so since we only support audio over it assume they want audio */
2142                         rtp = session->rtp;
2143                 }
2144
2145                 /* If description information is available use it */
2146                 if ((description = iks_find_with_attrib(content, "description", "xmlns", JINGLE_RTP_NS)) ||
2147                     (description = iks_find_with_attrib(content, "rtp:description", "xmlns:rtp", JINGLE_RTP_NS)) ||
2148                     (description = iks_find_with_attrib(content, "pho:description", "xmlns:pho", GOOGLE_PHONE_NS)) ||
2149                     (description = iks_find_with_attrib(pak->query, "description", "xmlns", GOOGLE_PHONE_NS)) ||
2150                     (description = iks_find_with_attrib(pak->query, "pho:description", "xmlns:pho", GOOGLE_PHONE_NS)) ||
2151                     (description = iks_find_with_attrib(pak->query, "vid:description", "xmlns", GOOGLE_VIDEO_NS))) {
2152                         /* If we failed to do something with the content description abort immediately */
2153                         if (jingle_interpret_description(session, description, name, &rtp)) {
2154                                 return -1;
2155                         }
2156
2157                         /* If we successfully interpret the description then the codecs need updating */
2158                         changed = 1;
2159                 }
2160
2161                 /* If we get past the description handling and we still don't know what RTP instance this is for... it is unknown content */
2162                 if (!rtp) {
2163                         ast_log(LOG_ERROR, "Received a content stanza but have no RTP instance for it on session '%s'\n", session->sid);
2164                         jingle_queue_hangup_with_cause(session, AST_CAUSE_SWITCH_CONGESTION);
2165                         return -1;
2166                 }
2167
2168                 /* If ICE UDP transport information is available use it */
2169                 if ((transport = iks_find_with_attrib(content, "transport", "xmlns", JINGLE_ICE_UDP_NS))) {
2170                         if (jingle_interpret_ice_udp_transport(session, transport, rtp)) {
2171                                 return -1;
2172                         }
2173                 } else if ((transport = iks_find_with_attrib(content, "transport", "xmlns", GOOGLE_TRANSPORT_NS)) ||
2174                            (transport = iks_find_with_attrib(content, "p:transport", "xmlns:p", GOOGLE_TRANSPORT_NS)) ||
2175                            (transport = iks_find_with_attrib(pak->x, "session", "xmlns", GOOGLE_SESSION_NS)) ||
2176                            (transport = iks_find_with_attrib(pak->x, "ses:session", "xmlns:ses", GOOGLE_SESSION_NS))) {
2177                         /* If Google transport support is available use it */
2178                         if (jingle_interpret_google_transport(session, transport, rtp)) {
2179                                 return -1;
2180                         }
2181                 } else if (iks_find(content, "transport")) {
2182                         /* If this is a transport we do not support terminate the session as it probably won't work out in the end */
2183                         jingle_queue_hangup_with_cause(session, AST_CAUSE_FACILITY_NOT_IMPLEMENTED);
2184                         ast_log(LOG_ERROR, "Unsupported transport type received on session '%s'\n", session->sid);
2185                         return -1;
2186                 }
2187         }
2188
2189         if (!changed) {
2190                 return 0;
2191         }
2192
2193         if ((chan = jingle_session_lock_full(session))) {
2194                 struct ast_format fmt;
2195
2196                 ast_format_cap_copy(ast_channel_nativeformats(chan), session->jointcap);
2197                 ast_codec_choose(&session->prefs, session->jointcap, 1, &fmt);
2198                 ast_set_read_format(chan, &fmt);
2199                 ast_set_write_format(chan, &fmt);
2200
2201                 ast_channel_unlock(chan);
2202                 ast_channel_unref(chan);
2203         }
2204         ao2_unlock(session);
2205
2206         return 0;
2207 }
2208
2209 /*! \brief Handler function for the 'session-initiate' action */
2210 static void jingle_action_session_initiate(struct jingle_endpoint *endpoint, struct jingle_session *session, ikspak *pak)
2211 {
2212         char *sid;
2213         enum jingle_transport transport = JINGLE_TRANSPORT_NONE;
2214         struct ast_channel *chan;
2215         int res;
2216
2217         if (session) {
2218                 /* This is a duplicate session setup, so respond accordingly */
2219                 jingle_send_error_response(endpoint->connection, pak, "result", "out-of-order", NULL);
2220                 return;
2221         }
2222
2223         /* Retrieve the session identifier from the message, note that this may alter the transport */
2224         if ((sid = iks_find_attrib(pak->query, "id"))) {
2225                 /* The presence of the session identifier in the 'id' attribute tells us that this is Google-V1 as everything else uses 'sid' */
2226                 transport = JINGLE_TRANSPORT_GOOGLE_V1;
2227         } else if (!(sid = iks_find_attrib(pak->query, "sid"))) {
2228                 jingle_send_error_response(endpoint->connection, pak, "bad-request", NULL, NULL);
2229                 return;
2230         }
2231
2232         /* Create a new local session */
2233         if (!(session = jingle_alloc(endpoint, pak->from->full, sid))) {
2234                 jingle_send_error_response(endpoint->connection, pak, "cancel", "service-unavailable xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'", NULL);
2235                 return;
2236         }
2237
2238         /* If we determined that the transport should change as a result of how we got the SID change it */
2239         if (transport != JINGLE_TRANSPORT_NONE) {
2240                 session->transport = transport;
2241         }
2242
2243         /* Create a new Asterisk channel using the above local session */
2244         if (!(chan = jingle_new(endpoint, session, AST_STATE_DOWN, pak->from->user, NULL, pak->from->full))) {
2245                 ao2_ref(session, -1);
2246                 jingle_send_error_response(endpoint->connection, pak, "cancel", "service-unavailable xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'", NULL);
2247                 return;
2248         }
2249
2250         ao2_link(endpoint->state->sessions, session);
2251
2252         ast_setstate(chan, AST_STATE_RING);
2253         res = ast_pbx_start(chan);
2254
2255         switch (res) {
2256         case AST_PBX_FAILED:
2257                 ast_log(LOG_WARNING, "Failed to start PBX :(\n");
2258                 jingle_send_error_response(endpoint->connection, pak, "cancel", "service-unavailable xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'", NULL);
2259                 session->gone = 1;
2260                 ast_hangup(chan);
2261                 break;
2262         case AST_PBX_CALL_LIMIT:
2263                 ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
2264                 jingle_send_error_response(endpoint->connection, pak, "wait", "resource-constraint xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'", NULL);
2265                 ast_hangup(chan);
2266                 break;
2267         case AST_PBX_SUCCESS:
2268                 jingle_send_response(endpoint->connection, pak);
2269
2270                 /* Only send a transport-info message if we successfully interpreted the available content */
2271                 if (!jingle_interpret_content(session, pak)) {
2272                         jingle_send_transport_info(session, iks_find_attrib(pak->x, "from"));
2273                 }
2274                 break;
2275         }
2276 }
2277
2278 /*! \brief Handler function for the 'transport-info' action */
2279 static void jingle_action_transport_info(struct jingle_endpoint *endpoint, struct jingle_session *session, ikspak *pak)
2280 {
2281         if (!session) {
2282                 jingle_send_error_response(endpoint->connection, pak, "cancel", "item-not-found xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'",
2283                                            "unknown-session xmlns='urn:xmpp:jingle:errors:1'");
2284                 return;
2285         }
2286
2287         jingle_interpret_content(session, pak);
2288         jingle_send_response(endpoint->connection, pak);
2289 }
2290
2291 /*! \brief Handler function for the 'session-accept' action */
2292 static void jingle_action_session_accept(struct jingle_endpoint *endpoint, struct jingle_session *session, ikspak *pak)
2293 {
2294         struct ast_channel *chan;
2295
2296         if (!session) {
2297                 jingle_send_error_response(endpoint->connection, pak, "cancel", "item-not-found xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'",
2298                                            "unknown-session xmlns='urn:xmpp:jingle:errors:1'");
2299                 return;
2300         }
2301
2302
2303         jingle_interpret_content(session, pak);
2304
2305         if ((chan = jingle_session_lock_full(session))) {
2306                 ast_queue_control(chan, AST_CONTROL_ANSWER);
2307                 ast_channel_unlock(chan);
2308                 ast_channel_unref(chan);
2309         }
2310         ao2_unlock(session);
2311
2312         jingle_send_response(endpoint->connection, pak);
2313 }
2314
2315 /*! \brief Handler function for the 'session-info' action */
2316 static void jingle_action_session_info(struct jingle_endpoint *endpoint, struct jingle_session *session, ikspak *pak)
2317 {
2318         struct ast_channel *chan;
2319
2320         if (!session) {
2321                 jingle_send_error_response(endpoint->connection, pak, "cancel", "item-not-found xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'",
2322                                            "unknown-session xmlns='urn:xmpp:jingle:errors:1'");
2323                 return;
2324         }
2325
2326         if (!(chan = jingle_session_lock_full(session))) {
2327                 ao2_unlock(session);
2328                 jingle_send_response(endpoint->connection, pak);
2329                 return;
2330         }
2331
2332         if (iks_find_with_attrib(pak->query, "ringing", "xmlns", JINGLE_RTP_INFO_NS)) {
2333                 ast_queue_control(chan, AST_CONTROL_RINGING);
2334                 if (ast_channel_state(chan) != AST_STATE_UP) {
2335                         ast_setstate(chan, AST_STATE_RINGING);
2336                 }
2337         } else if (iks_find_with_attrib(pak->query, "hold", "xmlns", JINGLE_RTP_INFO_NS)) {
2338                 ast_queue_control(chan, AST_CONTROL_HOLD);
2339         } else if (iks_find_with_attrib(pak->query, "unhold", "xmlns", JINGLE_RTP_INFO_NS)) {
2340                 ast_queue_control(chan, AST_CONTROL_UNHOLD);
2341         }
2342
2343         ast_channel_unlock(chan);
2344         ast_channel_unref(chan);
2345         ao2_unlock(session);
2346
2347         jingle_send_response(endpoint->connection, pak);
2348 }
2349
2350 /*! \brief Handler function for the 'session-terminate' action */
2351 static void jingle_action_session_terminate(struct jingle_endpoint *endpoint, struct jingle_session *session, ikspak *pak)
2352 {
2353         struct ast_channel *chan;
2354         iks *reason, *text;
2355         int cause = AST_CAUSE_NORMAL;
2356
2357         if (!session) {
2358                 jingle_send_error_response(endpoint->connection, pak, "cancel", "item-not-found xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'",
2359                                            "unknown-session xmlns='urn:xmpp:jingle:errors:1'");
2360                 return;
2361         }
2362
2363         if (!(chan = jingle_session_lock_full(session))) {
2364                 ao2_unlock(session);
2365                 jingle_send_response(endpoint->connection, pak);
2366                 return;
2367         }
2368
2369         /* Pull the reason text from the session-terminate message and translate it into a cause code */
2370         if ((reason = iks_find(pak->query, "reason")) && (text = iks_child(reason))) {
2371                 int i;
2372
2373                 /* Get the appropriate cause code mapping for this reason */
2374                 for (i = 0; i < ARRAY_LEN(jingle_reason_mappings); i++) {
2375                         if (!strcasecmp(jingle_reason_mappings[i].reason, iks_name(text))) {
2376                                 cause = jingle_reason_mappings[i].cause;
2377                                 break;
2378                         }
2379                 }
2380         }
2381
2382         ast_debug(3, "Hanging up channel '%s' due to session terminate message with cause '%d'\n", ast_channel_name(chan), cause);
2383         ast_queue_hangup_with_cause(chan, cause);
2384         session->gone = 1;
2385
2386         ast_channel_unlock(chan);
2387         ast_channel_unref(chan);
2388         ao2_unlock(session);
2389
2390         jingle_send_response(endpoint->connection, pak);
2391 }
2392
2393 /*! \brief Callback for when a Jingle action is received from an endpoint */
2394 static int jingle_action_hook(void *data, ikspak *pak)
2395 {
2396         char *action;
2397         const char *sid = NULL;
2398         struct jingle_session *session = NULL;
2399         struct jingle_endpoint *endpoint = data;
2400         int i, handled = 0;
2401
2402         /* We accept both Jingle and Google-V1 */
2403         if (!(action = iks_find_attrib(pak->query, "action")) &&
2404             !(action = iks_find_attrib(pak->query, "type"))) {
2405                 /* This occurs if either receive a packet masquerading as Jingle or Google-V1 that is actually not OR we receive a response
2406                  * to a message that has no response hook. */
2407                 return IKS_FILTER_EAT;
2408         }
2409
2410         /* Bump the endpoint reference count up in case a reload occurs. Unfortunately the available synchronization between iksemel and us
2411          * does not permit us to make this completely safe. */
2412         ao2_ref(endpoint, +1);
2413
2414         /* If a Jingle session identifier is present use it */
2415         if (!(sid = iks_find_attrib(pak->query, "sid"))) {
2416                 /* If a Google-V1 session identifier is present use it */
2417                 sid = iks_find_attrib(pak->query, "id");
2418         }
2419
2420         /* If a session identifier was present in the message attempt to find the session, it is up to the action handler whether
2421          * this is required or not */
2422         if (!ast_strlen_zero(sid)) {
2423                 session = ao2_find(endpoint->state->sessions, sid, OBJ_KEY);
2424         }
2425
2426         /* If a session is present associate the callid with this thread */
2427         if (session) {
2428                 ast_callid_threadassoc_add(session->callid);
2429         }
2430
2431         /* Iterate through supported action handlers looking for one that is able to handle this */
2432         for (i = 0; i < ARRAY_LEN(jingle_action_handlers); i++) {
2433                 if (!strcasecmp(jingle_action_handlers[i].action, action)) {
2434                         jingle_action_handlers[i].handler(endpoint, session, pak);
2435                         handled = 1;
2436                         break;
2437                 }
2438         }
2439
2440         /* If no action handler is present for the action they sent us make it evident */
2441         if (!handled) {
2442                 ast_log(LOG_NOTICE, "Received action '%s' for session '%s' that has no handler\n", action, sid);
2443         }
2444
2445         /* If a session was successfully found for this message deref it now since the handler is done */
2446         if (session) {
2447                 ast_callid_threadassoc_remove();
2448                 ao2_ref(session, -1);
2449         }
2450
2451         ao2_ref(endpoint, -1);
2452
2453         return IKS_FILTER_EAT;
2454 }
2455
2456 /*! \brief Custom handler for groups */
2457 static int custom_group_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
2458 {
2459         struct jingle_endpoint *endpoint = obj;
2460
2461         if (!strcasecmp(var->name, "callgroup")) {
2462                 endpoint->callgroup = ast_get_group(var->value);
2463         } else if (!strcasecmp(var->name, "pickupgroup")) {
2464                 endpoint->pickupgroup = ast_get_group(var->value);
2465         } else {
2466                 return -1;
2467         }
2468
2469         return 0;
2470 }
2471
2472 /*! \brief Custom handler for connection */
2473 static int custom_connection_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
2474 {
2475         struct jingle_endpoint *endpoint = obj;
2476
2477         /* You might think... but Josh, shouldn't you do this in a prelink callback? Well I *could* but until the original is destroyed
2478          * this will not actually get called, so even if the config turns out to be bogus this is harmless.
2479          */
2480         if (!(endpoint->connection = ast_xmpp_client_find(var->value))) {
2481                 ast_log(LOG_ERROR, "Connection '%s' configured on endpoint '%s' could not be found\n", var->value, endpoint->name);
2482                 return -1;
2483         }
2484
2485         if (!(endpoint->rule = iks_filter_add_rule(endpoint->connection->filter, jingle_action_hook, endpoint,
2486                                                    IKS_RULE_TYPE, IKS_PAK_IQ,
2487                                                    IKS_RULE_NS, JINGLE_NS,
2488                                                    IKS_RULE_NS, GOOGLE_SESSION_NS,
2489                                                    IKS_RULE_DONE))) {
2490                 ast_log(LOG_ERROR, "Action hook could not be added to connection '%s' on endpoint '%s'\n", var->value, endpoint->name);
2491                 return -1;
2492         }
2493
2494         return 0;
2495 }
2496
2497 /*! \brief Custom handler for transport */
2498 static int custom_transport_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
2499 {
2500         struct jingle_endpoint *endpoint = obj;
2501
2502         if (!strcasecmp(var->value, "ice-udp")) {
2503                 endpoint->transport = JINGLE_TRANSPORT_ICE_UDP;
2504         } else if (!strcasecmp(var->value, "google")) {
2505                 endpoint->transport = JINGLE_TRANSPORT_GOOGLE_V2;
2506         } else if (!strcasecmp(var->value, "google-v1")) {
2507                 endpoint->transport = JINGLE_TRANSPORT_GOOGLE_V1;
2508         } else {
2509                 ast_log(LOG_WARNING, "Unknown transport type '%s' on endpoint '%s', defaulting to 'ice-udp'\n", var->value, endpoint->name);
2510                 endpoint->transport = JINGLE_TRANSPORT_ICE_UDP;
2511         }
2512
2513         return 0;
2514 }
2515
2516 /*!
2517  * \brief Load the module
2518  *
2519  * Module loading including tests for configuration or dependencies.
2520  * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
2521  * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
2522  * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the 
2523  * configuration file or other non-critical problem return 
2524  * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
2525  */
2526 static int load_module(void)
2527 {
2528         if (!(jingle_tech.capabilities = ast_format_cap_alloc())) {
2529                 return AST_MODULE_LOAD_DECLINE;
2530         }
2531
2532         if (aco_info_init(&cfg_info)) {
2533                 ast_log(LOG_ERROR, "Unable to intialize configuration for chan_motif.\n");
2534                 goto end;
2535         }
2536
2537         aco_option_register(&cfg_info, "context", ACO_EXACT, endpoint_options, "default", OPT_STRINGFIELD_T, 0, STRFLDSET(struct jingle_endpoint, context));
2538         aco_option_register_custom(&cfg_info, "callgroup", ACO_EXACT, endpoint_options, NULL, custom_group_handler, 0);
2539         aco_option_register_custom(&cfg_info, "pickupgroup", ACO_EXACT, endpoint_options, NULL, custom_group_handler, 0);
2540         aco_option_register(&cfg_info, "language", ACO_EXACT, endpoint_options, NULL, OPT_STRINGFIELD_T, 0, STRFLDSET(struct jingle_endpoint, language));
2541         aco_option_register(&cfg_info, "musicclass", ACO_EXACT, endpoint_options, NULL, OPT_STRINGFIELD_T, 0, STRFLDSET(struct jingle_endpoint, musicclass));
2542         aco_option_register(&cfg_info, "parkinglot", ACO_EXACT, endpoint_options, NULL, OPT_STRINGFIELD_T, 0, STRFLDSET(struct jingle_endpoint, parkinglot));
2543         aco_option_register(&cfg_info, "accountcode", ACO_EXACT, endpoint_options, NULL, OPT_STRINGFIELD_T, 0, STRFLDSET(struct jingle_endpoint, accountcode));
2544         aco_option_register(&cfg_info, "allow", ACO_EXACT, endpoint_options, "ulaw,alaw", OPT_CODEC_T, 1, FLDSET(struct jingle_endpoint, prefs, cap));
2545         aco_option_register(&cfg_info, "disallow", ACO_EXACT, endpoint_options, "all", OPT_CODEC_T, 0, FLDSET(struct jingle_endpoint, prefs, cap));
2546         aco_option_register_custom(&cfg_info, "connection", ACO_EXACT, endpoint_options, NULL, custom_connection_handler, 0);
2547         aco_option_register_custom(&cfg_info, "transport", ACO_EXACT, endpoint_options, NULL, custom_transport_handler, 0);
2548         aco_option_register(&cfg_info, "maxicecandidates", ACO_EXACT, endpoint_options, DEFAULT_MAX_ICE_CANDIDATES, OPT_UINT_T, PARSE_DEFAULT,
2549                             FLDSET(struct jingle_endpoint, maxicecandidates));
2550         aco_option_register(&cfg_info, "maxpayloads", ACO_EXACT, endpoint_options, DEFAULT_MAX_PAYLOADS, OPT_UINT_T, PARSE_DEFAULT,
2551                             FLDSET(struct jingle_endpoint, maxpayloads));
2552
2553         ast_format_cap_add_all_by_type(jingle_tech.capabilities, AST_FORMAT_TYPE_AUDIO);
2554
2555         if (aco_process_config(&cfg_info, 0)) {
2556                 ast_log(LOG_ERROR, "Unable to read config file motif.conf. Not loading module.\n");
2557                 aco_info_destroy(&cfg_info);
2558                 return AST_MODULE_LOAD_DECLINE;
2559         }
2560
2561         if (!(sched = ast_sched_context_create())) {
2562                 ast_log(LOG_ERROR, "Unable to create scheduler context.\n");
2563                 goto end;
2564         }
2565
2566         if (ast_sched_start_thread(sched)) {
2567                 ast_log(LOG_ERROR, "Unable to create scheduler context thread.\n");
2568                 goto end;
2569         }
2570
2571         ast_rtp_glue_register(&jingle_rtp_glue);
2572
2573         if (ast_channel_register(&jingle_tech)) {
2574                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", channel_type);
2575                 goto end;
2576         }
2577
2578         return 0;
2579
2580 end:
2581         ast_rtp_glue_unregister(&jingle_rtp_glue);
2582
2583         if (sched) {
2584                 ast_sched_context_destroy(sched);
2585         }
2586
2587         aco_info_destroy(&cfg_info);
2588
2589         return AST_MODULE_LOAD_FAILURE;
2590 }
2591
2592 /*! \brief Reload module */
2593 static int reload(void)
2594 {
2595         return aco_process_config(&cfg_info, 1);
2596 }
2597
2598 /*! \brief Unload the jingle channel from Asterisk */
2599 static int unload_module(void)
2600 {
2601         ast_channel_unregister(&jingle_tech);
2602         ast_rtp_glue_unregister(&jingle_rtp_glue);
2603         ast_sched_context_destroy(sched);
2604         aco_info_destroy(&cfg_info);
2605         ao2_global_obj_release(globals);
2606
2607         return 0;
2608 }
2609
2610 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Motif Jingle Channel Driver",
2611                 .load = load_module,
2612                 .unload = unload_module,
2613                 .reload = reload,
2614                 .load_pri = AST_MODPRI_CHANNEL_DRIVER,
2615                );