56c15b193f6f14cf4d359f4fa9163f6786933098
[asterisk/asterisk.git] / channels / chan_jingle.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2005, Digium, Inc.
5  *
6  * Matt O'Gorman <mogorman@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 Matt O'Gorman <mogorman@digium.com>
22  *
23  * \brief Jingle Channel Driver
24  *
25  * Iksemel http://iksemel.jabberstudio.org/
26  * 
27  * \ingroup channel_drivers
28  */
29
30 /*! \li \ref chan_jingle.c uses the configuration file \ref jingle.conf
31  * \addtogroup configuration_file
32  */
33
34 /*! \page jingle.conf jingle.conf
35  * \verbinclude jingle.conf.sample
36  */
37
38 /*** MODULEINFO
39         <depend>iksemel</depend>
40         <depend>res_jabber</depend>
41         <use type="external">openssl</use>
42         <defaultenabled>no</defaultenabled>
43         <support_level>deprecated</support_level>
44         <replacement>chan_motif</replacement>
45  ***/
46
47 #include "asterisk.h"
48
49 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
50
51 #include <sys/socket.h>
52 #include <fcntl.h>
53 #include <netdb.h>
54 #include <netinet/in.h>
55 #include <arpa/inet.h>
56 #include <sys/signal.h>
57 #include <iksemel.h>
58 #include <pthread.h>
59
60 #include "asterisk/lock.h"
61 #include "asterisk/channel.h"
62 #include "asterisk/config.h"
63 #include "asterisk/module.h"
64 #include "asterisk/pbx.h"
65 #include "asterisk/sched.h"
66 #include "asterisk/io.h"
67 #include "asterisk/rtp_engine.h"
68 #include "asterisk/acl.h"
69 #include "asterisk/callerid.h"
70 #include "asterisk/file.h"
71 #include "asterisk/cli.h"
72 #include "asterisk/app.h"
73 #include "asterisk/musiconhold.h"
74 #include "asterisk/manager.h"
75 #include "asterisk/stringfields.h"
76 #include "asterisk/utils.h"
77 #include "asterisk/causes.h"
78 #include "asterisk/astobj.h"
79 #include "asterisk/abstract_jb.h"
80 #include "asterisk/jabber.h"
81 #include "asterisk/jingle.h"
82 #include "asterisk/stasis_channels.h"
83
84 #define JINGLE_CONFIG "jingle.conf"
85
86 /*! Global jitterbuffer configuration - by default, jb is disabled */
87 static struct ast_jb_conf default_jbconf =
88 {
89         .flags = 0,
90         .max_size = -1,
91         .resync_threshold = -1,
92         .impl = "",
93         .target_extra = -1,
94 };
95 static struct ast_jb_conf global_jbconf;
96
97 enum jingle_protocol {
98         AJI_PROTOCOL_UDP,
99         AJI_PROTOCOL_SSLTCP,
100 };
101
102 enum jingle_connect_type {
103         AJI_CONNECT_HOST,
104         AJI_CONNECT_PRFLX,
105         AJI_CONNECT_RELAY,
106         AJI_CONNECT_SRFLX,
107 };
108
109 struct jingle_pvt {
110         ast_mutex_t lock;                /*!< Channel private lock */
111         time_t laststun;
112         struct jingle *parent;           /*!< Parent client */
113         char sid[100];
114         char them[AJI_MAX_JIDLEN];
115         char ring[10];                   /*!< Message ID of ring */
116         iksrule *ringrule;               /*!< Rule for matching RING request */
117         int initiator;                   /*!< If we're the initiator */
118         int alreadygone;
119         struct ast_codec_pref prefs;
120         struct jingle_candidate *theircandidates;
121         struct jingle_candidate *ourcandidates;
122         char cid_num[80];                /*!< Caller ID num */
123         char cid_name[80];               /*!< Caller ID name */
124         char exten[80];                  /*!< Called extension */
125         struct ast_channel *owner;       /*!< Master Channel */
126         char audio_content_name[100];    /*!< name attribute of content tag */
127         struct ast_rtp_instance *rtp;             /*!< RTP audio session */
128         char video_content_name[100];    /*!< name attribute of content tag */
129         struct ast_rtp_instance *vrtp;            /*!< RTP video session */
130         struct ast_format_cap *cap;
131         struct ast_format_cap *jointcap;             /*!< Supported capability at both ends (codecs ) */
132         struct ast_format_cap *peercap;
133         struct jingle_pvt *next;        /* Next entity */
134 };
135
136 struct jingle_candidate {
137         unsigned int component;          /*!< ex. : 1 for RTP, 2 for RTCP */
138         unsigned int foundation;         /*!< Function of IP, protocol, type */
139         unsigned int generation;
140         char ip[16];
141         unsigned int network;
142         unsigned int port;
143         unsigned int priority;
144         enum jingle_protocol protocol;
145         char password[100];
146         enum jingle_connect_type type;
147         char ufrag[100];
148         unsigned int preference;
149         struct jingle_candidate *next;
150 };
151
152 struct jingle {
153         ASTOBJ_COMPONENTS(struct jingle);
154         struct aji_client *connection;
155         struct aji_buddy *buddy;
156         struct jingle_pvt *p;
157         struct ast_codec_pref prefs;
158         int amaflags;                   /*!< AMA Flags */
159         char user[100];
160         char context[100];
161         char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */
162         struct ast_format_cap *cap;
163         ast_group_t callgroup;  /*!< Call group */
164         ast_group_t pickupgroup;        /*!< Pickup group */
165         int callingpres;                /*!< Calling presentation */
166         int allowguest;
167         char language[MAX_LANGUAGE];    /*!<  Default language for prompts */
168         char musicclass[MAX_MUSICCLASS];        /*!<  Music on Hold class */
169         char parkinglot[AST_MAX_CONTEXT];   /*!< Parkinglot */
170 };
171
172 struct jingle_container {
173         ASTOBJ_CONTAINER_COMPONENTS(struct jingle);
174 };
175
176 static const char desc[] = "Jingle Channel";
177 static const char channel_type[] = "Jingle";
178
179 static struct ast_format_cap *global_capability;
180
181 AST_MUTEX_DEFINE_STATIC(jinglelock); /*!< Protect the interface list (of jingle_pvt's) */
182
183 /* Forward declarations */
184 static struct ast_channel *jingle_request(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, const char *data, int *cause);
185 static int jingle_sendtext(struct ast_channel *ast, const char *text);
186 static int jingle_digit_begin(struct ast_channel *ast, char digit);
187 static int jingle_digit_end(struct ast_channel *ast, char digit, unsigned int duration);
188 static int jingle_call(struct ast_channel *ast, const char *dest, int timeout);
189 static int jingle_hangup(struct ast_channel *ast);
190 static int jingle_answer(struct ast_channel *ast);
191 static int jingle_newcall(struct jingle *client, ikspak *pak);
192 static struct ast_frame *jingle_read(struct ast_channel *ast);
193 static int jingle_write(struct ast_channel *ast, struct ast_frame *f);
194 static int jingle_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
195 static int jingle_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
196 static int jingle_sendhtml(struct ast_channel *ast, int subclass, const char *data, int datalen);
197 static struct jingle_pvt *jingle_alloc(struct jingle *client, const char *from, const char *sid);
198 static char *jingle_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
199 static char *jingle_do_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
200 static void jingle_set_owner(struct jingle_pvt *pvt, struct ast_channel *chan);
201
202 /*! \brief PBX interface structure for channel registration */
203 static struct ast_channel_tech jingle_tech = {
204         .type = "Jingle",
205         .description = "Jingle Channel Driver",
206         .requester = jingle_request,
207         .send_text = jingle_sendtext,
208         .send_digit_begin = jingle_digit_begin,
209         .send_digit_end = jingle_digit_end,
210         .call = jingle_call,
211         .hangup = jingle_hangup,
212         .answer = jingle_answer,
213         .read = jingle_read,
214         .write = jingle_write,
215         .exception = jingle_read,
216         .indicate = jingle_indicate,
217         .fixup = jingle_fixup,
218         .send_html = jingle_sendhtml,
219         .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER
220 };
221
222 static struct sockaddr_in bindaddr = { 0, };    /*!< The address we bind to */
223
224 static struct ast_sched_context *sched; /*!< The scheduling context */
225 static struct io_context *io;   /*!< The IO context */
226 static struct in_addr __ourip;
227
228 static struct ast_cli_entry jingle_cli[] = {
229         AST_CLI_DEFINE(jingle_do_reload, "Reload Jingle configuration"),
230         AST_CLI_DEFINE(jingle_show_channels, "Show Jingle channels"),
231 };
232
233
234 static char externip[16];
235
236 static struct jingle_container jingle_list;
237
238 static void jingle_member_destroy(struct jingle *obj)
239 {
240         obj->cap = ast_format_cap_destroy(obj->cap);
241         if (obj->connection) {
242                 ASTOBJ_UNREF(obj->connection, ast_aji_client_destroy);
243         }
244         if (obj->buddy) {
245                 ASTOBJ_UNREF(obj->buddy, ast_aji_buddy_destroy);
246         }
247         ast_free(obj);
248 }
249
250 /* XXX This could be a source of reference leaks given that the CONTAINER_FIND
251  * macros bump the refcount while the traversal does not. */
252 static struct jingle *find_jingle(char *name, char *connection)
253 {
254         struct jingle *jingle = NULL;
255
256         jingle = ASTOBJ_CONTAINER_FIND(&jingle_list, name);
257         if (!jingle && strchr(name, '@'))
258                 jingle = ASTOBJ_CONTAINER_FIND_FULL(&jingle_list, name, user,,, strcasecmp);
259
260         if (!jingle) {                          
261                 /* guest call */
262                 ASTOBJ_CONTAINER_TRAVERSE(&jingle_list, 1, {
263                         ASTOBJ_RDLOCK(iterator);
264                         if (!strcasecmp(iterator->name, "guest")) {
265                                 jingle = iterator;
266                         }
267                         ASTOBJ_UNLOCK(iterator);
268
269                         if (jingle)
270                                 break;
271                 });
272
273         }
274         return jingle;
275 }
276
277
278 static void add_codec_to_answer(const struct jingle_pvt *p, struct ast_format *codec, iks *dcodecs)
279 {
280         const char *format = ast_getformatname(codec);
281
282         if (!strcasecmp("ulaw", format)) {
283                 iks *payload_eg711u, *payload_pcmu;
284                 payload_pcmu = iks_new("payload-type");
285                 iks_insert_attrib(payload_pcmu, "id", "0");
286                 iks_insert_attrib(payload_pcmu, "name", "PCMU");
287                 payload_eg711u = iks_new("payload-type");
288                 iks_insert_attrib(payload_eg711u, "id", "100");
289                 iks_insert_attrib(payload_eg711u, "name", "EG711U");
290                 iks_insert_node(dcodecs, payload_pcmu);
291                 iks_insert_node(dcodecs, payload_eg711u);
292         }
293         if (!strcasecmp("alaw", format)) {
294                 iks *payload_eg711a;
295                 iks *payload_pcma = iks_new("payload-type");
296                 iks_insert_attrib(payload_pcma, "id", "8");
297                 iks_insert_attrib(payload_pcma, "name", "PCMA");
298                 payload_eg711a = iks_new("payload-type");
299                 iks_insert_attrib(payload_eg711a, "id", "101");
300                 iks_insert_attrib(payload_eg711a, "name", "EG711A");
301                 iks_insert_node(dcodecs, payload_pcma);
302                 iks_insert_node(dcodecs, payload_eg711a);
303         }
304         if (!strcasecmp("ilbc", format)) {
305                 iks *payload_ilbc = iks_new("payload-type");
306                 iks_insert_attrib(payload_ilbc, "id", "97");
307                 iks_insert_attrib(payload_ilbc, "name", "iLBC");
308                 iks_insert_node(dcodecs, payload_ilbc);
309         }
310         if (!strcasecmp("g723", format)) {
311                 iks *payload_g723 = iks_new("payload-type");
312                 iks_insert_attrib(payload_g723, "id", "4");
313                 iks_insert_attrib(payload_g723, "name", "G723");
314                 iks_insert_node(dcodecs, payload_g723);
315         }
316 }
317
318 static int jingle_accept_call(struct jingle *client, struct jingle_pvt *p)
319 {
320         struct jingle_pvt *tmp = client->p;
321         struct aji_client *c = client->connection;
322         iks *iq, *jingle, *dcodecs, *payload_red, *payload_audio, *payload_cn;
323         int x;
324         struct ast_format pref_codec;
325         struct ast_format_cap *alreadysent = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_NOLOCK);
326
327         if (p->initiator || !alreadysent)
328                 return 1;
329
330         iq = iks_new("iq");
331         jingle = iks_new(JINGLE_NODE);
332         dcodecs = iks_new("description");
333         if (iq && jingle && dcodecs) {
334                 iks_insert_attrib(dcodecs, "xmlns", JINGLE_AUDIO_RTP_NS);
335
336                 for (x = 0; x < AST_CODEC_PREF_SIZE; x++) {
337                         if (!(ast_codec_pref_index(&client->prefs, x, &pref_codec)))
338                                 break;
339                         if (!(ast_format_cap_iscompatible(client->cap, &pref_codec)))
340                                 continue;
341                         if ((ast_format_cap_iscompatible(alreadysent, &pref_codec)))
342                                 continue;
343                         add_codec_to_answer(p, &pref_codec, dcodecs);
344                         ast_format_cap_add(alreadysent, &pref_codec);
345                 }
346                 payload_red = iks_new("payload-type");
347                 iks_insert_attrib(payload_red, "id", "117");
348                 iks_insert_attrib(payload_red, "name", "red");
349                 payload_audio = iks_new("payload-type");
350                 iks_insert_attrib(payload_audio, "id", "106");
351                 iks_insert_attrib(payload_audio, "name", "audio/telephone-event");
352                 payload_cn = iks_new("payload-type");
353                 iks_insert_attrib(payload_cn, "id", "13");
354                 iks_insert_attrib(payload_cn, "name", "CN");
355
356
357                 iks_insert_attrib(iq, "type", "set");
358                 iks_insert_attrib(iq, "to", (p->them) ? p->them : client->user);
359                 iks_insert_attrib(iq, "id", client->connection->mid);
360                 ast_aji_increment_mid(client->connection->mid);
361
362                 iks_insert_attrib(jingle, "xmlns", JINGLE_NS);
363                 iks_insert_attrib(jingle, "action", JINGLE_ACCEPT);
364                 iks_insert_attrib(jingle, "initiator", p->initiator ? client->connection->jid->full : p->them);
365                 iks_insert_attrib(jingle, JINGLE_SID, tmp->sid);
366                 iks_insert_node(iq, jingle);
367                 iks_insert_node(jingle, dcodecs);
368                 iks_insert_node(dcodecs, payload_red);
369                 iks_insert_node(dcodecs, payload_audio);
370                 iks_insert_node(dcodecs, payload_cn);
371
372                 ast_aji_send(c, iq);
373
374                 iks_delete(payload_red);
375                 iks_delete(payload_audio);
376                 iks_delete(payload_cn);
377                 iks_delete(dcodecs);
378                 iks_delete(jingle);
379                 iks_delete(iq);
380         }
381         alreadysent = ast_format_cap_destroy(alreadysent);
382         return 1;
383 }
384
385 static int jingle_ringing_ack(void *data, ikspak *pak)
386 {
387         struct jingle_pvt *p = data;
388
389         if (p->ringrule)
390                 iks_filter_remove_rule(p->parent->connection->f, p->ringrule);
391         p->ringrule = NULL;
392         if (p->owner)
393                 ast_queue_control(p->owner, AST_CONTROL_RINGING);
394         return IKS_FILTER_EAT;
395 }
396
397 static int jingle_answer(struct ast_channel *ast)
398 {
399         struct jingle_pvt *p = ast_channel_tech_pvt(ast);
400         struct jingle *client = p->parent;
401         int res = 0;
402
403         ast_debug(1, "Answer!\n");
404         ast_mutex_lock(&p->lock);
405         jingle_accept_call(client, p);
406         ast_mutex_unlock(&p->lock);
407         return res;
408 }
409
410 static enum ast_rtp_glue_result jingle_get_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
411 {
412         struct jingle_pvt *p = ast_channel_tech_pvt(chan);
413         enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_FORBID;
414
415         if (!p)
416                 return res;
417
418         ast_mutex_lock(&p->lock);
419         if (p->rtp) {
420                 ao2_ref(p->rtp, +1);
421                 *instance = p->rtp;
422                 res = AST_RTP_GLUE_RESULT_LOCAL;
423         }
424         ast_mutex_unlock(&p->lock);
425
426         return res;
427 }
428
429 static void jingle_get_codec(struct ast_channel *chan, struct ast_format_cap *result)
430 {
431         struct jingle_pvt *p = ast_channel_tech_pvt(chan);
432         ast_mutex_lock(&p->lock);
433         ast_format_cap_copy(result, p->peercap);
434         ast_mutex_unlock(&p->lock);
435 }
436
437 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)
438 {
439         struct jingle_pvt *p;
440
441         p = ast_channel_tech_pvt(chan);
442         if (!p)
443                 return -1;
444         ast_mutex_lock(&p->lock);
445
446 /*      if (rtp)
447                 ast_rtp_get_peer(rtp, &p->redirip);
448         else
449                 memset(&p->redirip, 0, sizeof(p->redirip));
450         p->redircodecs = codecs; */
451
452         /* Reset lastrtprx timer */
453         ast_mutex_unlock(&p->lock);
454         return 0;
455 }
456
457 static struct ast_rtp_glue jingle_rtp_glue = {
458         .type = "Jingle",
459         .get_rtp_info = jingle_get_rtp_peer,
460         .get_codec = jingle_get_codec,
461         .update_peer = jingle_set_rtp_peer,
462 };
463
464 static int jingle_response(struct jingle *client, ikspak *pak, const char *reasonstr, const char *reasonstr2)
465 {
466         iks *response = NULL, *error = NULL, *reason = NULL;
467         int res = -1;
468
469         response = iks_new("iq");
470         if (response) {
471                 iks_insert_attrib(response, "type", "result");
472                 iks_insert_attrib(response, "from", client->connection->jid->full);
473                 iks_insert_attrib(response, "to", iks_find_attrib(pak->x, "from"));
474                 iks_insert_attrib(response, "id", iks_find_attrib(pak->x, "id"));
475                 if (reasonstr) {
476                         error = iks_new("error");
477                         if (error) {
478                                 iks_insert_attrib(error, "type", "cancel");
479                                 reason = iks_new(reasonstr);
480                                 if (reason)
481                                         iks_insert_node(error, reason);
482                                 iks_insert_node(response, error);
483                         }
484                 }
485                 ast_aji_send(client->connection, response);
486                 res = 0;
487         }
488         
489         iks_delete(reason);
490         iks_delete(error);
491         iks_delete(response);
492
493         return res;
494 }
495
496 static int jingle_is_answered(struct jingle *client, ikspak *pak)
497 {
498         struct jingle_pvt *tmp;
499
500         ast_debug(1, "The client is %s\n", client->name);
501         /* Make sure our new call doesn't exist yet */
502         for (tmp = client->p; tmp; tmp = tmp->next) {
503                 if (iks_find_with_attrib(pak->x, JINGLE_NODE, JINGLE_SID, tmp->sid))
504                         break;
505         }
506
507         if (tmp) {
508                 if (tmp->owner)
509                         ast_queue_control(tmp->owner, AST_CONTROL_ANSWER);
510         } else
511                 ast_log(LOG_NOTICE, "Whoa, didn't find call!\n");
512         jingle_response(client, pak, NULL, NULL);
513         return 1;
514 }
515
516 static int jingle_handle_dtmf(struct jingle *client, ikspak *pak)
517 {
518         struct jingle_pvt *tmp;
519         iks *dtmfnode = NULL, *dtmfchild = NULL;
520         char *dtmf;
521         /* Make sure our new call doesn't exist yet */
522         for (tmp = client->p; tmp; tmp = tmp->next) {
523                 if (iks_find_with_attrib(pak->x, JINGLE_NODE, JINGLE_SID, tmp->sid))
524                         break;
525         }
526
527         if (tmp) {
528                 if(iks_find_with_attrib(pak->x, "dtmf-method", "method", "rtp")) {
529                         jingle_response(client,pak,
530                                         "feature-not-implemented xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'",
531                                         "unsupported-dtmf-method xmlns='http://www.xmpp.org/extensions/xep-0181.html#ns-errors'");
532                         return -1;
533                 }
534                 if ((dtmfnode = iks_find(pak->x, "dtmf"))) {
535                         if((dtmf = iks_find_attrib(dtmfnode, "code"))) {
536                                 if(iks_find_with_attrib(pak->x, "dtmf", "action", "button-up")) {
537                                         struct ast_frame f = {AST_FRAME_DTMF_BEGIN, };
538                                         f.subclass.integer = dtmf[0];
539                                         ast_queue_frame(tmp->owner, &f);
540                                         ast_verbose("JINGLE! DTMF-relay event received: %c\n", f.subclass.integer);
541                                 } else if(iks_find_with_attrib(pak->x, "dtmf", "action", "button-down")) {
542                                         struct ast_frame f = {AST_FRAME_DTMF_END, };
543                                         f.subclass.integer = dtmf[0];
544                                         ast_queue_frame(tmp->owner, &f);
545                                         ast_verbose("JINGLE! DTMF-relay event received: %c\n", f.subclass.integer);
546                                 } else if(iks_find_attrib(pak->x, "dtmf")) { /* 250 millasecond default */
547                                         struct ast_frame f = {AST_FRAME_DTMF, };
548                                         f.subclass.integer = dtmf[0];
549                                         ast_queue_frame(tmp->owner, &f);
550                                         ast_verbose("JINGLE! DTMF-relay event received: %c\n", f.subclass.integer);
551                                 }
552                         }
553                 } else if ((dtmfnode = iks_find_with_attrib(pak->x, JINGLE_NODE, "action", "session-info"))) {
554                         if((dtmfchild = iks_find(dtmfnode, "dtmf"))) {
555                                 if((dtmf = iks_find_attrib(dtmfchild, "code"))) {
556                                         if(iks_find_with_attrib(dtmfnode, "dtmf", "action", "button-up")) {
557                                                 struct ast_frame f = {AST_FRAME_DTMF_END, };
558                                                 f.subclass.integer = dtmf[0];
559                                                 ast_queue_frame(tmp->owner, &f);
560                                                 ast_verbose("JINGLE! DTMF-relay event received: %c\n", f.subclass.integer);
561                                         } else if(iks_find_with_attrib(dtmfnode, "dtmf", "action", "button-down")) {
562                                                 struct ast_frame f = {AST_FRAME_DTMF_BEGIN, };
563                                                 f.subclass.integer = dtmf[0];
564                                                 ast_queue_frame(tmp->owner, &f);
565                                                 ast_verbose("JINGLE! DTMF-relay event received: %c\n", f.subclass.integer);
566                                         }
567                                 }
568                         }
569                 }
570                 jingle_response(client, pak, NULL, NULL);
571                 return 1;
572         } else
573                 ast_log(LOG_NOTICE, "Whoa, didn't find call!\n");
574
575         jingle_response(client, pak, NULL, NULL);
576         return 1;
577 }
578
579
580 static int jingle_hangup_farend(struct jingle *client, ikspak *pak)
581 {
582         struct jingle_pvt *tmp;
583
584         ast_debug(1, "The client is %s\n", client->name);
585         /* Make sure our new call doesn't exist yet */
586         for (tmp = client->p; tmp; tmp = tmp->next) {
587                 if (iks_find_with_attrib(pak->x, JINGLE_NODE, JINGLE_SID, tmp->sid))
588                         break;
589         }
590
591         if (tmp) {
592                 tmp->alreadygone = 1;
593                 if (tmp->owner)
594                         ast_queue_hangup(tmp->owner);
595         } else
596                 ast_log(LOG_NOTICE, "Whoa, didn't find call!\n");
597         jingle_response(client, pak, NULL, NULL);
598         return 1;
599 }
600
601 static int jingle_create_candidates(struct jingle *client, struct jingle_pvt *p, char *sid, char *from)
602 {
603         struct jingle_candidate *tmp;
604         struct aji_client *c = client->connection;
605         struct jingle_candidate *ours1 = NULL, *ours2 = NULL;
606         struct sockaddr_in sin = { 0, };
607         struct ast_sockaddr sin_tmp;
608         struct ast_sockaddr us_tmp;
609         struct ast_sockaddr bindaddr_tmp;
610         struct in_addr us;
611         struct in_addr externaddr;
612         iks *iq, *jingle, *content, *transport, *candidate;
613         char component[16], foundation[16], generation[16], network[16], pass[16], port[7], priority[16], user[16];
614
615
616         iq = iks_new("iq");
617         jingle = iks_new(JINGLE_NODE);
618         content = iks_new("content");
619         transport = iks_new("transport");
620         candidate = iks_new("candidate");
621         if (!iq || !jingle || !content || !transport || !candidate) {
622                 ast_log(LOG_ERROR, "Memory allocation error\n");
623                 goto safeout;
624         }
625         ours1 = ast_calloc(1, sizeof(*ours1));
626         ours2 = ast_calloc(1, sizeof(*ours2));
627         if (!ours1 || !ours2)
628                 goto safeout;
629
630         iks_insert_node(iq, jingle);
631         iks_insert_node(jingle, content);
632         iks_insert_node(content, transport);
633         iks_insert_node(transport, candidate);
634
635         for (; p; p = p->next) {
636                 if (!strcasecmp(p->sid, sid))
637                         break;
638         }
639
640         if (!p) {
641                 ast_log(LOG_NOTICE, "No matching jingle session - SID %s!\n", sid);
642                 goto safeout;
643         }
644
645         ast_rtp_instance_get_local_address(p->rtp, &sin_tmp);
646         ast_sockaddr_to_sin(&sin_tmp, &sin);
647         ast_sockaddr_from_sin(&bindaddr_tmp, &bindaddr);
648         ast_find_ourip(&us_tmp, &bindaddr_tmp, AF_INET);
649         us.s_addr = htonl(ast_sockaddr_ipv4(&us_tmp));
650
651         /* Setup our first jingle candidate */
652         ours1->component = 1;
653         ours1->foundation = (unsigned int)bindaddr.sin_addr.s_addr | AJI_CONNECT_HOST | AJI_PROTOCOL_UDP;
654         ours1->generation = 0;
655         ast_copy_string(ours1->ip, ast_inet_ntoa(us), sizeof(ours1->ip));
656         ours1->network = 0;
657         ours1->port = ntohs(sin.sin_port);
658         ours1->priority = 1678246398;
659         ours1->protocol = AJI_PROTOCOL_UDP;
660         snprintf(pass, sizeof(pass), "%08lx%08lx", ast_random(), ast_random());
661         ast_copy_string(ours1->password, pass, sizeof(ours1->password));
662         ours1->type = AJI_CONNECT_HOST;
663         snprintf(user, sizeof(user), "%08lx%08lx", ast_random(), ast_random());
664         ast_copy_string(ours1->ufrag, user, sizeof(ours1->ufrag));
665         p->ourcandidates = ours1;
666
667         if (!ast_strlen_zero(externip)) {
668                 /* XXX We should really stun for this one not just go with externip XXX */
669                 if (inet_aton(externip, &externaddr))
670                         ast_log(LOG_WARNING, "Invalid extern IP : %s\n", externip);
671
672                 ours2->component = 1;
673                 ours2->foundation = (unsigned int)externaddr.s_addr | AJI_CONNECT_PRFLX | AJI_PROTOCOL_UDP;
674                 ours2->generation = 0;
675                 ast_copy_string(ours2->ip, externip, sizeof(ours2->ip));
676                 ours2->network = 0;
677                 ours2->port = ntohs(sin.sin_port);
678                 ours2->priority = 1678246397;
679                 ours2->protocol = AJI_PROTOCOL_UDP;
680                 snprintf(pass, sizeof(pass), "%08lx%08lx", ast_random(), ast_random());
681                 ast_copy_string(ours2->password, pass, sizeof(ours2->password));
682                 ours2->type = AJI_CONNECT_PRFLX;
683
684                 snprintf(user, sizeof(user), "%08lx%08lx", ast_random(), ast_random());
685                 ast_copy_string(ours2->ufrag, user, sizeof(ours2->ufrag));
686                 ours1->next = ours2;
687                 ours2 = NULL;
688         }
689         ours1 = NULL;
690
691         for (tmp = p->ourcandidates; tmp; tmp = tmp->next) {
692                 snprintf(component, sizeof(component), "%u", tmp->component);
693                 snprintf(foundation, sizeof(foundation), "%u", tmp->foundation);
694                 snprintf(generation, sizeof(generation), "%u", tmp->generation);
695                 snprintf(network, sizeof(network), "%u", tmp->network);
696                 snprintf(port, sizeof(port), "%u", tmp->port);
697                 snprintf(priority, sizeof(priority), "%u", tmp->priority);
698
699                 iks_insert_attrib(iq, "from", c->jid->full);
700                 iks_insert_attrib(iq, "to", from);
701                 iks_insert_attrib(iq, "type", "set");
702                 iks_insert_attrib(iq, "id", c->mid);
703                 ast_aji_increment_mid(c->mid);
704                 iks_insert_attrib(jingle, "action", JINGLE_NEGOTIATE);
705                 iks_insert_attrib(jingle, JINGLE_SID, sid);
706                 iks_insert_attrib(jingle, "initiator", (p->initiator) ? c->jid->full : from);
707                 iks_insert_attrib(jingle, "xmlns", JINGLE_NS);
708                 iks_insert_attrib(content, "creator", p->initiator ? "initiator" : "responder");
709                 iks_insert_attrib(content, "name", "asterisk-audio-content");
710                 iks_insert_attrib(transport, "xmlns", JINGLE_ICE_UDP_NS);
711                 iks_insert_attrib(candidate, "component", component);
712                 iks_insert_attrib(candidate, "foundation", foundation);
713                 iks_insert_attrib(candidate, "generation", generation);
714                 iks_insert_attrib(candidate, "ip", tmp->ip);
715                 iks_insert_attrib(candidate, "network", network);
716                 iks_insert_attrib(candidate, "port", port);
717                 iks_insert_attrib(candidate, "priority", priority);
718                 switch (tmp->protocol) {
719                 case AJI_PROTOCOL_UDP:
720                         iks_insert_attrib(candidate, "protocol", "udp");
721                         break;
722                 case AJI_PROTOCOL_SSLTCP:
723                         iks_insert_attrib(candidate, "protocol", "ssltcp");
724                         break;
725                 }
726                 iks_insert_attrib(candidate, "pwd", tmp->password);
727                 switch (tmp->type) {
728                 case AJI_CONNECT_HOST:
729                         iks_insert_attrib(candidate, "type", "host");
730                         break;
731                 case AJI_CONNECT_PRFLX:
732                         iks_insert_attrib(candidate, "type", "prflx");
733                         break;
734                 case AJI_CONNECT_RELAY:
735                         iks_insert_attrib(candidate, "type", "relay");
736                         break;
737                 case AJI_CONNECT_SRFLX:
738                         iks_insert_attrib(candidate, "type", "srflx");
739                         break;
740                 }
741                 iks_insert_attrib(candidate, "ufrag", tmp->ufrag);
742
743                 ast_aji_send(c, iq);
744         }
745         p->laststun = 0;
746
747 safeout:
748         if (ours1)
749                 ast_free(ours1);
750         if (ours2)
751                 ast_free(ours2);
752         iks_delete(iq);
753         iks_delete(jingle);
754         iks_delete(content);
755         iks_delete(transport);
756         iks_delete(candidate);
757
758         return 1;
759 }
760
761 static struct jingle_pvt *jingle_alloc(struct jingle *client, const char *from, const char *sid)
762 {
763         struct jingle_pvt *tmp = NULL;
764         struct aji_resource *resources = NULL;
765         struct aji_buddy *buddy = NULL;
766         char idroster[200];
767         struct ast_sockaddr bindaddr_tmp;
768
769         ast_debug(1, "The client is %s for alloc\n", client->name);
770         if (!sid && !strchr(from, '/')) {       /* I started call! */
771                 if (!strcasecmp(client->name, "guest")) {
772                         buddy = ASTOBJ_CONTAINER_FIND(&client->connection->buddies, from);
773                         if (buddy) {
774                                 resources = buddy->resources;
775                         }
776                 } else if (client->buddy)
777                         resources = client->buddy->resources;
778                 while (resources) {
779                         if (resources->cap->jingle) {
780                                 break;
781                         }
782                         resources = resources->next;
783                 }
784                 if (resources)
785                         snprintf(idroster, sizeof(idroster), "%s/%s", from, resources->resource);
786                 else {
787                         ast_log(LOG_ERROR, "no jingle capable clients to talk to.\n");
788                         if (buddy) {
789                                 ASTOBJ_UNREF(buddy, ast_aji_buddy_destroy);
790                         }
791                         return NULL;
792                 }
793                 if (buddy) {
794                         ASTOBJ_UNREF(buddy, ast_aji_buddy_destroy);
795                 }
796         }
797         if (!(tmp = ast_calloc(1, sizeof(*tmp)))) {
798                 return NULL;
799         }
800
801         tmp->cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_NOLOCK);
802         tmp->jointcap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_NOLOCK);
803         tmp->peercap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_NOLOCK);
804         if (!tmp->cap || !tmp->jointcap || !tmp->peercap) {
805                 tmp->cap = ast_format_cap_destroy(tmp->cap);
806                 tmp->jointcap = ast_format_cap_destroy(tmp->jointcap);
807                 tmp->peercap = ast_format_cap_destroy(tmp->peercap);
808                 ast_free(tmp);
809                 return NULL;
810         }
811         memcpy(&tmp->prefs, &client->prefs, sizeof(tmp->prefs));
812
813         if (sid) {
814                 ast_copy_string(tmp->sid, sid, sizeof(tmp->sid));
815                 ast_copy_string(tmp->them, from, sizeof(tmp->them));
816         } else {
817                 snprintf(tmp->sid, sizeof(tmp->sid), "%08lx%08lx", ast_random(), ast_random());
818                 ast_copy_string(tmp->them, idroster, sizeof(tmp->them));
819                 tmp->initiator = 1;
820         }
821         ast_sockaddr_from_sin(&bindaddr_tmp, &bindaddr);
822         tmp->rtp = ast_rtp_instance_new("asterisk", sched, &bindaddr_tmp, NULL);
823         tmp->parent = client;
824         if (!tmp->rtp) {
825                 ast_log(LOG_WARNING, "Out of RTP sessions?\n");
826                 ast_free(tmp);
827                 return NULL;
828         }
829         ast_copy_string(tmp->exten, "s", sizeof(tmp->exten));
830         ast_mutex_init(&tmp->lock);
831         ast_mutex_lock(&jinglelock);
832         tmp->next = client->p;
833         client->p = tmp;
834         ast_mutex_unlock(&jinglelock);
835         return tmp;
836 }
837
838 static void jingle_set_owner(struct jingle_pvt *pvt, struct ast_channel *chan)
839 {
840         pvt->owner = chan;
841         if (pvt->rtp) {
842                 ast_rtp_instance_set_channel_id(pvt->rtp, pvt->owner ? ast_channel_uniqueid(pvt->owner) : "");
843         }
844         if (pvt->vrtp) {
845                 ast_rtp_instance_set_channel_id(pvt->vrtp, pvt->owner ? ast_channel_uniqueid(pvt->owner) : "");
846         }
847 }
848
849 /*! \brief Start new jingle channel */
850 static struct ast_channel *jingle_new(struct jingle *client, struct jingle_pvt *i, int state, const char *title, const char *linkedid)
851 {
852         struct ast_channel *tmp;
853         struct ast_format_cap *what;  /* SHALLOW COPY DO NOT DESTROY */
854         struct ast_format tmpfmt;
855         const char *str;
856
857         if (title)
858                 str = title;
859         else
860                 str = i->them;
861         tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, "", "", "", linkedid, 0, "Jingle/%s-%04lx", str, ast_random() & 0xffff);
862         if (!tmp) {
863                 ast_log(LOG_WARNING, "Unable to allocate Jingle channel structure!\n");
864                 return NULL;
865         }
866
867         ast_channel_stage_snapshot(tmp);
868
869         ast_channel_tech_set(tmp, &jingle_tech);
870
871         /* Select our native format based on codec preference until we receive
872            something from another device to the contrary. */
873         if (!ast_format_cap_is_empty(i->jointcap))
874                 what = i->jointcap;
875         else if (!(ast_format_cap_is_empty(i->cap)))
876                 what = i->cap;
877         else
878                 what = global_capability;
879
880         /* Set Frame packetization */
881         if (i->rtp)
882                 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(i->rtp), i->rtp, &i->prefs);
883
884         ast_codec_choose(&i->prefs, what, 1, &tmpfmt);
885         ast_format_cap_add(ast_channel_nativeformats(tmp), &tmpfmt);
886
887         ast_format_cap_iter_start(i->jointcap);
888         while (!(ast_format_cap_iter_next(i->jointcap, &tmpfmt))) {
889                 if (AST_FORMAT_GET_TYPE(tmpfmt.id) == AST_FORMAT_TYPE_VIDEO) {
890                         ast_format_cap_add(ast_channel_nativeformats(tmp), &tmpfmt);
891                 }
892         }
893         ast_format_cap_iter_end(i->jointcap);
894
895         if (i->rtp) {
896                 ast_channel_set_fd(tmp, 0, ast_rtp_instance_fd(i->rtp, 0));
897                 ast_channel_set_fd(tmp, 1, ast_rtp_instance_fd(i->rtp, 1));
898         }
899         if (i->vrtp) {
900                 ast_channel_set_fd(tmp, 2, ast_rtp_instance_fd(i->vrtp, 0));
901                 ast_channel_set_fd(tmp, 3, ast_rtp_instance_fd(i->vrtp, 1));
902         }
903         if (state == AST_STATE_RING)
904                 ast_channel_rings_set(tmp, 1);
905         ast_channel_adsicpe_set(tmp, AST_ADSI_UNAVAILABLE);
906
907
908         ast_best_codec(ast_channel_nativeformats(tmp), &tmpfmt);
909         ast_format_copy(ast_channel_writeformat(tmp), &tmpfmt);
910         ast_format_copy(ast_channel_rawwriteformat(tmp), &tmpfmt);
911         ast_format_copy(ast_channel_readformat(tmp), &tmpfmt);
912         ast_format_copy(ast_channel_rawreadformat(tmp), &tmpfmt);
913         ast_channel_tech_pvt_set(tmp, i);
914
915         ast_channel_callgroup_set(tmp, client->callgroup);
916         ast_channel_pickupgroup_set(tmp, client->pickupgroup);
917         ast_channel_caller(tmp)->id.name.presentation = client->callingpres;
918         ast_channel_caller(tmp)->id.number.presentation = client->callingpres;
919         if (!ast_strlen_zero(client->accountcode))
920                 ast_channel_accountcode_set(tmp, client->accountcode);
921         if (client->amaflags)
922                 ast_channel_amaflags_set(tmp, client->amaflags);
923         if (!ast_strlen_zero(client->language))
924                 ast_channel_language_set(tmp, client->language);
925         if (!ast_strlen_zero(client->musicclass))
926                 ast_channel_musicclass_set(tmp, client->musicclass);
927         jingle_set_owner(i, tmp);
928         ast_channel_context_set(tmp, client->context);
929         ast_channel_exten_set(tmp, i->exten);
930         /* Don't use ast_set_callerid() here because it will
931          * generate an unnecessary NewCallerID event  */
932         if (!ast_strlen_zero(i->cid_num)) {
933                 ast_channel_caller(tmp)->ani.number.valid = 1;
934                 ast_channel_caller(tmp)->ani.number.str = ast_strdup(i->cid_num);
935         }
936         if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s")) {
937                 ast_channel_dialed(tmp)->number.str = ast_strdup(i->exten);
938         }
939         ast_channel_priority_set(tmp, 1);
940         if (i->rtp)
941                 ast_jb_configure(tmp, &global_jbconf);
942
943         ast_channel_stage_snapshot_done(tmp);
944
945         if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
946                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", ast_channel_name(tmp));
947                 ast_channel_hangupcause_set(tmp, AST_CAUSE_SWITCH_CONGESTION);
948                 ast_hangup(tmp);
949                 tmp = NULL;
950         }
951
952         return tmp;
953 }
954
955 static int jingle_action(struct jingle *client, struct jingle_pvt *p, const char *action)
956 {
957         iks *iq, *jingle = NULL;
958         int res = -1;
959
960         iq = iks_new("iq");
961         jingle = iks_new("jingle");
962         
963         if (iq) {
964                 iks_insert_attrib(iq, "type", "set");
965                 iks_insert_attrib(iq, "from", client->connection->jid->full);
966                 iks_insert_attrib(iq, "to", p->them);
967                 iks_insert_attrib(iq, "id", client->connection->mid);
968                 ast_aji_increment_mid(client->connection->mid);
969                 if (jingle) {
970                         iks_insert_attrib(jingle, "action", action);
971                         iks_insert_attrib(jingle, JINGLE_SID, p->sid);
972                         iks_insert_attrib(jingle, "initiator", p->initiator ? client->connection->jid->full : p->them);
973                         iks_insert_attrib(jingle, "xmlns", JINGLE_NS);
974
975                         iks_insert_node(iq, jingle);
976
977                         ast_aji_send(client->connection, iq);
978                         res = 0;
979                 }
980         }
981         
982         iks_delete(jingle);
983         iks_delete(iq);
984         
985         return res;
986 }
987
988 static void jingle_free_candidates(struct jingle_candidate *candidate)
989 {
990         struct jingle_candidate *last;
991         while (candidate) {
992                 last = candidate;
993                 candidate = candidate->next;
994                 ast_free(last);
995         }
996 }
997
998 static void jingle_free_pvt(struct jingle *client, struct jingle_pvt *p)
999 {
1000         struct jingle_pvt *cur, *prev = NULL;
1001         cur = client->p;
1002         while (cur) {
1003                 if (cur == p) {
1004                         if (prev)
1005                                 prev->next = p->next;
1006                         else
1007                                 client->p = p->next;
1008                         break;
1009                 }
1010                 prev = cur;
1011                 cur = cur->next;
1012         }
1013         if (p->ringrule)
1014                 iks_filter_remove_rule(p->parent->connection->f, p->ringrule);
1015         if (p->owner)
1016                 ast_log(LOG_WARNING, "Uh oh, there's an owner, this is going to be messy.\n");
1017         if (p->rtp)
1018                 ast_rtp_instance_destroy(p->rtp);
1019         if (p->vrtp)
1020                 ast_rtp_instance_destroy(p->vrtp);
1021         jingle_free_candidates(p->theircandidates);
1022         p->cap = ast_format_cap_destroy(p->cap);
1023         p->jointcap = ast_format_cap_destroy(p->jointcap);
1024         p->peercap = ast_format_cap_destroy(p->peercap);
1025
1026         ast_free(p);
1027 }
1028
1029
1030 static int jingle_newcall(struct jingle *client, ikspak *pak)
1031 {
1032         struct jingle_pvt *p, *tmp = client->p;
1033         struct ast_channel *chan;
1034         int res;
1035         iks *codec, *content, *description;
1036         char *from = NULL;
1037
1038         /* Make sure our new call doesn't exist yet */
1039         from = iks_find_attrib(pak->x,"to");
1040         if(!from)
1041                 from = client->connection->jid->full;
1042
1043         while (tmp) {
1044                 if (iks_find_with_attrib(pak->x, JINGLE_NODE, JINGLE_SID, tmp->sid)) {
1045                         ast_log(LOG_NOTICE, "Ignoring duplicate call setup on SID %s\n", tmp->sid);
1046                         jingle_response(client, pak, "out-of-order", NULL);
1047                         return -1;
1048                 }
1049                 tmp = tmp->next;
1050         }
1051
1052         if (!strcasecmp(client->name, "guest")){
1053                 /* the guest account is not tied to any configured XMPP client,
1054                    let's set it now */
1055                 if (client->connection) {
1056                         ASTOBJ_UNREF(client->connection, ast_aji_client_destroy);
1057                 }
1058                 client->connection = ast_aji_get_client(from);
1059                 if (!client->connection) {
1060                         ast_log(LOG_ERROR, "No XMPP client to talk to, us (partial JID) : %s\n", from);
1061                         return -1;
1062                 }
1063         }
1064
1065         p = jingle_alloc(client, pak->from->partial, iks_find_attrib(pak->query, JINGLE_SID));
1066         if (!p) {
1067                 ast_log(LOG_WARNING, "Unable to allocate jingle structure!\n");
1068                 return -1;
1069         }
1070         chan = jingle_new(client, p, AST_STATE_DOWN, pak->from->user, NULL);
1071         if (!chan) {
1072                 jingle_free_pvt(client, p);
1073                 return -1;
1074         }
1075         ast_mutex_lock(&p->lock);
1076         ast_copy_string(p->them, pak->from->full, sizeof(p->them));
1077         if (iks_find_attrib(pak->query, JINGLE_SID)) {
1078                 ast_copy_string(p->sid, iks_find_attrib(pak->query, JINGLE_SID),
1079                                 sizeof(p->sid));
1080         }
1081         
1082         /* content points to the first <content/> tag */        
1083         content = iks_child(iks_child(pak->x));
1084         while (content) {
1085                 description = iks_find_with_attrib(content, "description", "xmlns", JINGLE_AUDIO_RTP_NS);
1086                 if (description) {
1087                         /* audio content found */
1088                         codec = iks_child(iks_child(content));
1089                         ast_copy_string(p->audio_content_name, iks_find_attrib(content, "name"), sizeof(p->audio_content_name));
1090
1091                         while (codec) {
1092                                 ast_rtp_codecs_payloads_set_m_type(ast_rtp_instance_get_codecs(p->rtp), p->rtp, atoi(iks_find_attrib(codec, "id")));
1093                                 ast_rtp_codecs_payloads_set_rtpmap_type(ast_rtp_instance_get_codecs(p->rtp), p->rtp, atoi(iks_find_attrib(codec, "id")), "audio", iks_find_attrib(codec, "name"), 0);
1094                                 codec = iks_next(codec);
1095                         }
1096                 }
1097                 
1098                 description = NULL;
1099                 codec = NULL;
1100
1101                 description = iks_find_with_attrib(content, "description", "xmlns", JINGLE_VIDEO_RTP_NS);
1102                 if (description) {
1103                         /* video content found */
1104                         codec = iks_child(iks_child(content));
1105                         ast_copy_string(p->video_content_name, iks_find_attrib(content, "name"), sizeof(p->video_content_name));
1106
1107                         while (codec) {
1108                                 ast_rtp_codecs_payloads_set_m_type(ast_rtp_instance_get_codecs(p->rtp), p->rtp, atoi(iks_find_attrib(codec, "id")));
1109                                 ast_rtp_codecs_payloads_set_rtpmap_type(ast_rtp_instance_get_codecs(p->rtp), p->rtp, atoi(iks_find_attrib(codec, "id")), "audio", iks_find_attrib(codec, "name"), 0);
1110                                 codec = iks_next(codec);
1111                         }
1112                 }
1113                 
1114                 content = iks_next(content);
1115         }
1116
1117         ast_mutex_unlock(&p->lock);
1118         ast_setstate(chan, AST_STATE_RING);
1119         res = ast_pbx_start(chan);
1120         
1121         switch (res) {
1122         case AST_PBX_FAILED:
1123                 ast_log(LOG_WARNING, "Failed to start PBX :(\n");
1124                 jingle_response(client, pak, "service-unavailable", NULL);
1125                 break;
1126         case AST_PBX_CALL_LIMIT:
1127                 ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
1128                 jingle_response(client, pak, "service-unavailable", NULL);
1129                 break;
1130         case AST_PBX_SUCCESS:
1131                 jingle_response(client, pak, NULL, NULL);
1132                 jingle_create_candidates(client, p,
1133                                          iks_find_attrib(pak->query, JINGLE_SID),
1134                                          iks_find_attrib(pak->x, "from"));
1135                 /* nothing to do */
1136                 break;
1137         }
1138
1139         return 1;
1140 }
1141
1142 static int jingle_update_stun(struct jingle *client, struct jingle_pvt *p)
1143 {
1144         struct jingle_candidate *tmp;
1145         struct hostent *hp;
1146         struct ast_hostent ahp;
1147         struct sockaddr_in sin;
1148         struct ast_sockaddr sin_tmp;
1149
1150         if (time(NULL) == p->laststun)
1151                 return 0;
1152
1153         tmp = p->theircandidates;
1154         p->laststun = time(NULL);
1155         while (tmp) {
1156                 char username[256];
1157                 hp = ast_gethostbyname(tmp->ip, &ahp);
1158                 sin.sin_family = AF_INET;
1159                 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
1160                 sin.sin_port = htons(tmp->port);
1161                 snprintf(username, sizeof(username), "%s:%s", tmp->ufrag, p->ourcandidates->ufrag);
1162
1163                 ast_sockaddr_from_sin(&sin_tmp, &sin);
1164                 ast_rtp_instance_stun_request(p->rtp, &sin_tmp, username);
1165                 tmp = tmp->next;
1166         }
1167         return 1;
1168 }
1169
1170 static int jingle_add_candidate(struct jingle *client, ikspak *pak)
1171 {
1172         struct jingle_pvt *p = NULL, *tmp = NULL;
1173         struct aji_client *c = client->connection;
1174         struct jingle_candidate *newcandidate = NULL;
1175         iks *traversenodes = NULL, *receipt = NULL;
1176
1177         for (tmp = client->p; tmp; tmp = tmp->next) {
1178                 if (iks_find_with_attrib(pak->x, JINGLE_NODE, JINGLE_SID, tmp->sid)) {
1179                         p = tmp;
1180                         break;
1181                 }
1182         }
1183
1184         if (!p)
1185                 return -1;
1186
1187         traversenodes = pak->query;
1188         while(traversenodes) {
1189                 if(!strcasecmp(iks_name(traversenodes), "jingle")) {
1190                         traversenodes = iks_child(traversenodes);
1191                         continue;
1192                 }
1193                 if(!strcasecmp(iks_name(traversenodes), "content")) {
1194                         traversenodes = iks_child(traversenodes);
1195                         continue;
1196                 }
1197                 if(!strcasecmp(iks_name(traversenodes), "transport")) {
1198                         traversenodes = iks_child(traversenodes);
1199                         continue;
1200                 }
1201
1202                 if(!strcasecmp(iks_name(traversenodes), "candidate")) {
1203                         newcandidate = ast_calloc(1, sizeof(*newcandidate));
1204                         if (!newcandidate)
1205                                 return 0;
1206                         ast_copy_string(newcandidate->ip, iks_find_attrib(traversenodes, "ip"), sizeof(newcandidate->ip));
1207                         newcandidate->port = atoi(iks_find_attrib(traversenodes, "port"));
1208                         ast_copy_string(newcandidate->password, iks_find_attrib(traversenodes, "pwd"), sizeof(newcandidate->password));
1209                         if (!strcasecmp(iks_find_attrib(traversenodes, "protocol"), "udp"))
1210                                 newcandidate->protocol = AJI_PROTOCOL_UDP;
1211                         else if (!strcasecmp(iks_find_attrib(traversenodes, "protocol"), "ssltcp"))
1212                                 newcandidate->protocol = AJI_PROTOCOL_SSLTCP;
1213                         
1214                         if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "host"))
1215                                 newcandidate->type = AJI_CONNECT_HOST;
1216                         else if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "prflx"))
1217                                 newcandidate->type = AJI_CONNECT_PRFLX;
1218                         else if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "relay"))
1219                                 newcandidate->type = AJI_CONNECT_RELAY;
1220                         else if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "srflx"))
1221                                 newcandidate->type = AJI_CONNECT_SRFLX;
1222
1223                         newcandidate->network = atoi(iks_find_attrib(traversenodes, "network"));
1224                         newcandidate->generation = atoi(iks_find_attrib(traversenodes, "generation"));
1225                         newcandidate->next = NULL;
1226                 
1227                         newcandidate->next = p->theircandidates;
1228                         p->theircandidates = newcandidate;
1229                         p->laststun = 0;
1230                         jingle_update_stun(p->parent, p);
1231                         newcandidate = NULL;
1232                 }
1233                 traversenodes = iks_next(traversenodes);
1234         }
1235         
1236         receipt = iks_new("iq");
1237         iks_insert_attrib(receipt, "type", "result");
1238         iks_insert_attrib(receipt, "from", c->jid->full);
1239         iks_insert_attrib(receipt, "to", iks_find_attrib(pak->x, "from"));
1240         iks_insert_attrib(receipt, "id", iks_find_attrib(pak->x, "id"));
1241         ast_aji_send(c, receipt);
1242
1243         iks_delete(receipt);
1244
1245         return 1;
1246 }
1247
1248 static struct ast_frame *jingle_rtp_read(struct ast_channel *ast, struct jingle_pvt *p)
1249 {
1250         struct ast_frame *f;
1251
1252         if (!p->rtp)
1253                 return &ast_null_frame;
1254         f = ast_rtp_instance_read(p->rtp, 0);
1255         jingle_update_stun(p->parent, p);
1256         if (p->owner) {
1257                 /* We already hold the channel lock */
1258                 if (f->frametype == AST_FRAME_VOICE) {
1259                         if (!(ast_format_cap_iscompatible(ast_channel_nativeformats(p->owner), &f->subclass.format))) {
1260                                 ast_debug(1, "Oooh, format changed to %s\n", ast_getformatname(&f->subclass.format));
1261                                 ast_format_cap_remove_bytype(ast_channel_nativeformats(p->owner), AST_FORMAT_TYPE_AUDIO);
1262                                 ast_format_cap_add(ast_channel_nativeformats(p->owner), &f->subclass.format);
1263                                 ast_set_read_format(p->owner, ast_channel_readformat(p->owner));
1264                                 ast_set_write_format(p->owner, ast_channel_writeformat(p->owner));
1265                         }
1266 /*                      if ((ast_test_flag(p, SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
1267                                 f = ast_dsp_process(p->owner, p->vad, f);
1268                                 if (f && (f->frametype == AST_FRAME_DTMF))
1269                                         ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass.codec);
1270                         } */
1271                 }
1272         }
1273         return f;
1274 }
1275
1276 static struct ast_frame *jingle_read(struct ast_channel *ast)
1277 {
1278         struct ast_frame *fr;
1279         struct jingle_pvt *p = ast_channel_tech_pvt(ast);
1280
1281         ast_mutex_lock(&p->lock);
1282         fr = jingle_rtp_read(ast, p);
1283         ast_mutex_unlock(&p->lock);
1284         return fr;
1285 }
1286
1287 /*! \brief Send frame to media channel (rtp) */
1288 static int jingle_write(struct ast_channel *ast, struct ast_frame *frame)
1289 {
1290         struct jingle_pvt *p = ast_channel_tech_pvt(ast);
1291         int res = 0;
1292         char buf[256];
1293
1294         switch (frame->frametype) {
1295         case AST_FRAME_VOICE:
1296                 if (!(ast_format_cap_iscompatible(ast_channel_nativeformats(ast), &frame->subclass.format))) {
1297                         ast_log(LOG_WARNING,
1298                                         "Asked to transmit frame type %s, while native formats is %s (read/write = %s/%s)\n",
1299                                         ast_getformatname(&frame->subclass.format),
1300                                         ast_getformatname_multiple(buf, sizeof(buf), ast_channel_nativeformats(ast)),
1301                                         ast_getformatname(ast_channel_readformat(ast)),
1302                                         ast_getformatname(ast_channel_writeformat(ast)));
1303                         return 0;
1304                 }
1305                 if (p) {
1306                         ast_mutex_lock(&p->lock);
1307                         if (p->rtp) {
1308                                 res = ast_rtp_instance_write(p->rtp, frame);
1309                         }
1310                         ast_mutex_unlock(&p->lock);
1311                 }
1312                 break;
1313         case AST_FRAME_VIDEO:
1314                 if (p) {
1315                         ast_mutex_lock(&p->lock);
1316                         if (p->vrtp) {
1317                                 res = ast_rtp_instance_write(p->vrtp, frame);
1318                         }
1319                         ast_mutex_unlock(&p->lock);
1320                 }
1321                 break;
1322         case AST_FRAME_IMAGE:
1323                 return 0;
1324                 break;
1325         default:
1326                 ast_log(LOG_WARNING, "Can't send %d type frames with Jingle write\n",
1327                                 frame->frametype);
1328                 return 0;
1329         }
1330
1331         return res;
1332 }
1333
1334 static int jingle_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1335 {
1336         struct jingle_pvt *p = ast_channel_tech_pvt(newchan);
1337         ast_mutex_lock(&p->lock);
1338
1339         if ((p->owner != oldchan)) {
1340                 ast_mutex_unlock(&p->lock);
1341                 return -1;
1342         }
1343         if (p->owner == oldchan) {
1344                 jingle_set_owner(p, newchan);
1345         }
1346         ast_mutex_unlock(&p->lock);
1347         return 0;
1348 }
1349
1350 static int jingle_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
1351 {
1352         int res = 0;
1353
1354         switch (condition) {
1355         case AST_CONTROL_HOLD:
1356                 ast_moh_start(ast, data, NULL);
1357                 break;
1358         case AST_CONTROL_UNHOLD:
1359                 ast_moh_stop(ast);
1360                 break;
1361         default:
1362                 ast_log(LOG_NOTICE, "Don't know how to indicate condition '%d'\n", condition);
1363                 /* fallthrough */
1364         case AST_CONTROL_PVT_CAUSE_CODE:
1365                 res = -1;
1366         }
1367
1368         return res;
1369 }
1370
1371 static int jingle_sendtext(struct ast_channel *chan, const char *text)
1372 {
1373         int res = 0;
1374         struct aji_client *client = NULL;
1375         struct jingle_pvt *p = ast_channel_tech_pvt(chan);
1376
1377
1378         if (!p->parent) {
1379                 ast_log(LOG_ERROR, "Parent channel not found\n");
1380                 return -1;
1381         }
1382         if (!p->parent->connection) {
1383                 ast_log(LOG_ERROR, "XMPP client not found\n");
1384                 return -1;
1385         }
1386         client = p->parent->connection;
1387         res = ast_aji_send_chat(client, p->them, text);
1388         return res;
1389 }
1390
1391 static int jingle_digit(struct ast_channel *ast, char digit, unsigned int duration)
1392 {
1393         struct jingle_pvt *p = ast_channel_tech_pvt(ast);
1394         struct jingle *client = p->parent;
1395         iks *iq, *jingle, *dtmf;
1396         char buffer[2] = {digit, '\0'};
1397         iq = iks_new("iq");
1398         jingle = iks_new("jingle");
1399         dtmf = iks_new("dtmf");
1400         if(!iq || !jingle || !dtmf) {
1401                 iks_delete(iq);
1402                 iks_delete(jingle);
1403                 iks_delete(dtmf);
1404                 ast_log(LOG_ERROR, "Did not send dtmf do to memory issue\n");
1405                 return -1;
1406         }
1407
1408         iks_insert_attrib(iq, "type", "set");
1409         iks_insert_attrib(iq, "to", p->them);
1410         iks_insert_attrib(iq, "from", client->connection->jid->full);
1411         iks_insert_attrib(iq, "id", client->connection->mid);
1412         ast_aji_increment_mid(client->connection->mid);
1413         iks_insert_attrib(jingle, "xmlns", JINGLE_NS);
1414         iks_insert_attrib(jingle, "action", "session-info");
1415         iks_insert_attrib(jingle, "initiator", p->initiator ? client->connection->jid->full : p->them);
1416         iks_insert_attrib(jingle, "sid", p->sid);
1417         iks_insert_attrib(dtmf, "xmlns", JINGLE_DTMF_NS);
1418         iks_insert_attrib(dtmf, "code", buffer);
1419         iks_insert_node(iq, jingle);
1420         iks_insert_node(jingle, dtmf);
1421
1422         ast_mutex_lock(&p->lock);
1423         if (ast_channel_dtmff(ast)->frametype == AST_FRAME_DTMF_BEGIN || duration == 0) {
1424                 iks_insert_attrib(dtmf, "action", "button-down");
1425         } else if (ast_channel_dtmff(ast)->frametype == AST_FRAME_DTMF_END || duration != 0) {
1426                 iks_insert_attrib(dtmf, "action", "button-up");
1427         }
1428         ast_aji_send(client->connection, iq);
1429
1430         iks_delete(iq);
1431         iks_delete(jingle);
1432         iks_delete(dtmf);
1433         ast_mutex_unlock(&p->lock);
1434         return 0;
1435 }
1436
1437 static int jingle_digit_begin(struct ast_channel *chan, char digit)
1438 {
1439         return jingle_digit(chan, digit, 0);
1440 }
1441
1442 static int jingle_digit_end(struct ast_channel *ast, char digit, unsigned int duration)
1443 {
1444         return jingle_digit(ast, digit, duration);
1445 }
1446
1447 static int jingle_sendhtml(struct ast_channel *ast, int subclass, const char *data, int datalen)
1448 {
1449         ast_log(LOG_NOTICE, "XXX Implement jingle sendhtml XXX\n");
1450
1451         return -1;
1452 }
1453 static int jingle_transmit_invite(struct jingle_pvt *p)
1454 {
1455         struct jingle *aux = NULL;
1456         struct aji_client *client = NULL;
1457         iks *iq, *jingle, *content, *description, *transport;
1458         iks *payload_eg711u, *payload_pcmu;
1459
1460         aux = p->parent;
1461         client = aux->connection;
1462         iq = iks_new("iq");
1463         jingle = iks_new(JINGLE_NODE);
1464         content = iks_new("content");
1465         description = iks_new("description");
1466         transport = iks_new("transport");
1467         payload_pcmu = iks_new("payload-type");
1468         payload_eg711u = iks_new("payload-type");
1469
1470         ast_copy_string(p->audio_content_name, "asterisk-audio-content", sizeof(p->audio_content_name));
1471
1472         iks_insert_attrib(iq, "type", "set");
1473         iks_insert_attrib(iq, "to", p->them);
1474         iks_insert_attrib(iq, "from", client->jid->full);
1475         iks_insert_attrib(iq, "id", client->mid);
1476         ast_aji_increment_mid(client->mid);
1477         iks_insert_attrib(jingle, "action", JINGLE_INITIATE);
1478         iks_insert_attrib(jingle, JINGLE_SID, p->sid);
1479         iks_insert_attrib(jingle, "initiator", client->jid->full);
1480         iks_insert_attrib(jingle, "xmlns", JINGLE_NS);
1481
1482         /* For now, we only send one audio based content */
1483         iks_insert_attrib(content, "creator", "initiator");
1484         iks_insert_attrib(content, "name", p->audio_content_name);
1485         iks_insert_attrib(content, "profile", "RTP/AVP");
1486         iks_insert_attrib(description, "xmlns", JINGLE_AUDIO_RTP_NS);
1487         iks_insert_attrib(transport, "xmlns", JINGLE_ICE_UDP_NS);
1488         iks_insert_attrib(payload_pcmu, "id", "0");
1489         iks_insert_attrib(payload_pcmu, "name", "PCMU");
1490         iks_insert_attrib(payload_eg711u, "id", "100");
1491         iks_insert_attrib(payload_eg711u, "name", "EG711U");
1492         iks_insert_node(description, payload_pcmu);
1493         iks_insert_node(description, payload_eg711u);
1494         iks_insert_node(content, description);
1495         iks_insert_node(content, transport);
1496         iks_insert_node(jingle, content);
1497         iks_insert_node(iq, jingle);
1498
1499         ast_aji_send(client, iq);
1500
1501         iks_delete(iq);
1502         iks_delete(jingle);
1503         iks_delete(content);
1504         iks_delete(description);
1505         iks_delete(transport);
1506         iks_delete(payload_eg711u);
1507         iks_delete(payload_pcmu);
1508         return 0;
1509 }
1510
1511 /* Not in use right now.
1512 static int jingle_auto_congest(void *nothing)
1513 {
1514         struct jingle_pvt *p = nothing;
1515
1516         ast_mutex_lock(&p->lock);
1517         if (p->owner) {
1518                 if (!ast_channel_trylock(p->owner)) {
1519                         ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
1520                         ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
1521                         ast_channel_unlock(p->owner);
1522                 }
1523         }
1524         ast_mutex_unlock(&p->lock);
1525         return 0;
1526 }
1527 */
1528
1529 /*! \brief Initiate new call, part of PBX interface 
1530  *      dest is the dial string */
1531 static int jingle_call(struct ast_channel *ast, const char *dest, int timeout)
1532 {
1533         struct jingle_pvt *p = ast_channel_tech_pvt(ast);
1534
1535         if ((ast_channel_state(ast) != AST_STATE_DOWN) && (ast_channel_state(ast) != AST_STATE_RESERVED)) {
1536                 ast_log(LOG_WARNING, "jingle_call called on %s, neither down nor reserved\n", ast_channel_name(ast));
1537                 return -1;
1538         }
1539
1540         ast_setstate(ast, AST_STATE_RING);
1541         ast_format_cap_copy(p->jointcap, p->cap);
1542         if (!p->ringrule) {
1543                 ast_copy_string(p->ring, p->parent->connection->mid, sizeof(p->ring));
1544                 p->ringrule = iks_filter_add_rule(p->parent->connection->f, jingle_ringing_ack, p,
1545                                                         IKS_RULE_ID, p->ring, IKS_RULE_DONE);
1546         } else
1547                 ast_log(LOG_WARNING, "Whoa, already have a ring rule!\n");
1548
1549         jingle_transmit_invite(p);
1550         jingle_create_candidates(p->parent, p, p->sid, p->them);
1551
1552         return 0;
1553 }
1554
1555 /*! \brief Hangup a call through the jingle proxy channel */
1556 static int jingle_hangup(struct ast_channel *ast)
1557 {
1558         struct jingle_pvt *p = ast_channel_tech_pvt(ast);
1559         struct jingle *client;
1560
1561         ast_mutex_lock(&p->lock);
1562         client = p->parent;
1563         jingle_set_owner(p, NULL);
1564         ast_channel_tech_pvt_set(ast, NULL);
1565         if (!p->alreadygone)
1566                 jingle_action(client, p, JINGLE_TERMINATE);
1567         ast_mutex_unlock(&p->lock);
1568
1569         jingle_free_pvt(client, p);
1570
1571         return 0;
1572 }
1573
1574 /*! \brief Part of PBX interface */
1575 static struct ast_channel *jingle_request(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, const char *data, int *cause)
1576 {
1577         struct jingle_pvt *p = NULL;
1578         struct jingle *client = NULL;
1579         char *sender = NULL, *to = NULL, *s = NULL;
1580         struct ast_channel *chan = NULL;
1581
1582         if (data) {
1583                 s = ast_strdupa(data);
1584                 sender = strsep(&s, "/");
1585                 if (sender && (sender[0] != '\0'))
1586                         to = strsep(&s, "/");
1587                 if (!to) {
1588                         ast_log(LOG_ERROR, "Bad arguments in Jingle Dialstring: %s\n", data);
1589                         return NULL;
1590                 }
1591                 if (!to) {
1592                         ast_log(LOG_ERROR, "Bad arguments in Jingle Dialstring: %s\n", (char*) data);
1593                         return NULL;
1594                 }
1595         }
1596
1597         client = find_jingle(to, sender);
1598         if (!client) {
1599                 ast_log(LOG_WARNING, "Could not find recipient.\n");
1600                 return NULL;
1601         }
1602         if (!strcasecmp(client->name, "guest")){
1603                 /* the guest account is not tied to any configured XMPP client,
1604                    let's set it now */
1605                 if (client->connection) {
1606                         ASTOBJ_UNREF(client->connection, ast_aji_client_destroy);
1607                 }
1608                 client->connection = ast_aji_get_client(sender);
1609                 if (!client->connection) {
1610                         ast_log(LOG_ERROR, "No XMPP client to talk to, us (partial JID) : %s\n", sender);
1611                         return NULL;
1612                 }
1613         }
1614        
1615         ASTOBJ_WRLOCK(client);
1616         p = jingle_alloc(client, to, NULL);
1617         if (p)
1618                 chan = jingle_new(client, p, AST_STATE_DOWN, to, requestor ? ast_channel_linkedid(requestor) : NULL);
1619         ASTOBJ_UNLOCK(client);
1620
1621         return chan;
1622 }
1623
1624 /*! \brief CLI command "jingle show channels" */
1625 static char *jingle_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1626 {
1627 #define FORMAT  "%-30.30s  %-30.30s  %-15.15s  %-5.5s %-5.5s \n"
1628         struct jingle_pvt *p;
1629         struct ast_channel *chan;
1630         int numchans = 0;
1631         char them[AJI_MAX_JIDLEN];
1632         char *jid = NULL;
1633         char *resource = NULL;
1634
1635         switch (cmd) {
1636         case CLI_INIT:
1637                 e->command = "jingle show channels";
1638                 e->usage =
1639                         "Usage: jingle show channels\n"
1640                         "       Shows current state of the Jingle channels.\n";
1641                 return NULL;
1642         case CLI_GENERATE:
1643                 return NULL;
1644         }
1645
1646         if (a->argc != 3)
1647                 return CLI_SHOWUSAGE;
1648
1649         ast_mutex_lock(&jinglelock);
1650         ast_cli(a->fd, FORMAT, "Channel", "Jabber ID", "Resource", "Read", "Write");
1651         ASTOBJ_CONTAINER_TRAVERSE(&jingle_list, 1, {
1652                 ASTOBJ_WRLOCK(iterator);
1653                 p = iterator->p;
1654                 while(p) {
1655                         chan = p->owner;
1656                         ast_copy_string(them, p->them, sizeof(them));
1657                         jid = them;
1658                         resource = strchr(them, '/');
1659                         if (!resource)
1660                                 resource = "None";
1661                         else {
1662                                 *resource = '\0';
1663                                 resource ++;
1664                         }
1665                         if (chan)
1666                                 ast_cli(a->fd, FORMAT, 
1667                                         ast_channel_name(chan),
1668                                         jid,
1669                                         resource,
1670                                         ast_getformatname(ast_channel_readformat(chan)),
1671                                         ast_getformatname(ast_channel_writeformat(chan))
1672                                         );
1673                         else 
1674                                 ast_log(LOG_WARNING, "No available channel\n");
1675                         numchans ++;
1676                         p = p->next;
1677                 }
1678                 ASTOBJ_UNLOCK(iterator);
1679         });
1680
1681         ast_mutex_unlock(&jinglelock);
1682
1683         ast_cli(a->fd, "%d active jingle channel%s\n", numchans, (numchans != 1) ? "s" : "");
1684         return CLI_SUCCESS;
1685 #undef FORMAT
1686 }
1687
1688 /*! \brief CLI command "jingle reload" */
1689 static char *jingle_do_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1690 {
1691         switch (cmd) {
1692         case CLI_INIT:
1693                 e->command = "jingle reload";
1694                 e->usage =
1695                         "Usage: jingle reload\n"
1696                         "       Reload jingle channel driver.\n";
1697                 return NULL;
1698         case CLI_GENERATE:
1699                 return NULL;
1700         }       
1701         
1702         return CLI_SUCCESS;
1703 }
1704
1705 static int jingle_parser(void *data, ikspak *pak)
1706 {
1707         struct jingle *client = ASTOBJ_REF((struct jingle *) data);
1708         ast_log(LOG_NOTICE, "Filter matched\n");
1709
1710         if (iks_find_with_attrib(pak->x, JINGLE_NODE, "action", JINGLE_INITIATE)) {
1711                 /* New call */
1712                 jingle_newcall(client, pak);
1713         } else if (iks_find_with_attrib(pak->x, JINGLE_NODE, "action", JINGLE_NEGOTIATE)) {
1714                 ast_debug(3, "About to add candidate!\n");
1715                 jingle_add_candidate(client, pak);
1716                 ast_debug(3, "Candidate Added!\n");
1717         } else if (iks_find_with_attrib(pak->x, JINGLE_NODE, "action", JINGLE_ACCEPT)) {
1718                 jingle_is_answered(client, pak);
1719         } else if (iks_find_with_attrib(pak->x, JINGLE_NODE, "action", JINGLE_INFO)) {
1720                 jingle_handle_dtmf(client, pak);
1721         } else if (iks_find_with_attrib(pak->x, JINGLE_NODE, "action", JINGLE_TERMINATE)) {
1722                 jingle_hangup_farend(client, pak);
1723         } else if (iks_find_with_attrib(pak->x, JINGLE_NODE, "action", "reject")) {
1724                 jingle_hangup_farend(client, pak);
1725         }
1726         ASTOBJ_UNREF(client, jingle_member_destroy);
1727         return IKS_FILTER_EAT;
1728 }
1729 /* Not using this anymore probably take out soon 
1730 static struct jingle_candidate *jingle_create_candidate(char *args)
1731 {
1732         char *name, *type, *preference, *protocol;
1733         struct jingle_candidate *res;
1734         res = ast_calloc(1, sizeof(*res));
1735         if (args)
1736                 name = args;
1737         if ((args = strchr(args, ','))) {
1738                 *args = '\0';
1739                 args++;
1740                 preference = args;
1741         }
1742         if ((args = strchr(args, ','))) {
1743                 *args = '\0';
1744                 args++;
1745                 protocol = args;
1746         }
1747         if ((args = strchr(args, ','))) {
1748                 *args = '\0';
1749                 args++;
1750                 type = args;
1751         }
1752         if (name)
1753                 ast_copy_string(res->name, name, sizeof(res->name));
1754         if (preference) {
1755                 res->preference = atof(preference);
1756         }
1757         if (protocol) {
1758                 if (!strcasecmp("udp", protocol))
1759                         res->protocol = AJI_PROTOCOL_UDP;
1760                 if (!strcasecmp("ssltcp", protocol))
1761                         res->protocol = AJI_PROTOCOL_SSLTCP;
1762         }
1763         if (type) {
1764                 if (!strcasecmp("host", type))
1765                         res->type = AJI_CONNECT_HOST;
1766                 if (!strcasecmp("prflx", type))
1767                         res->type = AJI_CONNECT_PRFLX;
1768                 if (!strcasecmp("relay", type))
1769                         res->type = AJI_CONNECT_RELAY;
1770                 if (!strcasecmp("srflx", type))
1771                         res->type = AJI_CONNECT_SRFLX;
1772         }
1773
1774         return res;
1775 }
1776 */
1777
1778 static int jingle_create_member(char *label, struct ast_variable *var, int allowguest,
1779                                                                 struct ast_codec_pref prefs, char *context,
1780                                                                 struct jingle *member)
1781 {
1782         struct aji_client *client;
1783
1784         if (!member)
1785                 ast_log(LOG_WARNING, "Out of memory.\n");
1786
1787         ast_copy_string(member->name, label, sizeof(member->name));
1788         ast_copy_string(member->user, label, sizeof(member->user));
1789         ast_copy_string(member->context, context, sizeof(member->context));
1790         member->allowguest = allowguest;
1791         member->prefs = prefs;
1792         while (var) {
1793 #if 0
1794                 struct jingle_candidate *candidate = NULL;
1795 #endif
1796                 if (!strcasecmp(var->name, "username"))
1797                         ast_copy_string(member->user, var->value, sizeof(member->user));
1798                 else if (!strcasecmp(var->name, "disallow"))
1799                         ast_parse_allow_disallow(&member->prefs, member->cap, var->value, 0);
1800                 else if (!strcasecmp(var->name, "allow"))
1801                         ast_parse_allow_disallow(&member->prefs, member->cap, var->value, 1);
1802                 else if (!strcasecmp(var->name, "context"))
1803                         ast_copy_string(member->context, var->value, sizeof(member->context));
1804 #if 0
1805                 else if (!strcasecmp(var->name, "candidate")) {
1806                         candidate = jingle_create_candidate(var->value);
1807                         if (candidate) {
1808                                 candidate->next = member->ourcandidates;
1809                                 member->ourcandidates = candidate;
1810                         }
1811                 }
1812 #endif
1813                 else if (!strcasecmp(var->name, "connection")) {
1814                         if ((client = ast_aji_get_client(var->value))) {
1815                                 member->connection = client;
1816                                 iks_filter_add_rule(client->f, jingle_parser, member,
1817                                                     IKS_RULE_TYPE, IKS_PAK_IQ,
1818                                                     IKS_RULE_FROM_PARTIAL, member->user,
1819                                                     IKS_RULE_NS, JINGLE_NS,
1820                                                     IKS_RULE_DONE);
1821                         } else {
1822                                 ast_log(LOG_ERROR, "connection referenced not found!\n");
1823                                 return 0;
1824                         }
1825                 }
1826                 var = var->next;
1827         }
1828         if (member->connection && member->user)
1829                 member->buddy = ASTOBJ_CONTAINER_FIND(&member->connection->buddies, member->user);
1830         else {
1831                 ast_log(LOG_ERROR, "No Connection or Username!\n");
1832         }
1833         return 1;
1834 }
1835
1836 static int jingle_load_config(void)
1837 {
1838         char *cat = NULL;
1839         struct ast_config *cfg = NULL;
1840         char context[100];
1841         int allowguest = 1;
1842         struct ast_variable *var;
1843         struct jingle *member;
1844         struct hostent *hp;
1845         struct ast_hostent ahp;
1846         struct ast_codec_pref prefs;
1847         struct aji_client_container *clients;
1848         struct jingle_candidate *global_candidates = NULL;
1849         struct ast_flags config_flags = { 0 };
1850
1851         cfg = ast_config_load(JINGLE_CONFIG, config_flags);
1852         if (!cfg || cfg == CONFIG_STATUS_FILEINVALID) {
1853                 return 0;
1854         }
1855
1856         /* Copy the default jb config over global_jbconf */
1857         memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
1858
1859         cat = ast_category_browse(cfg, NULL);
1860         for (var = ast_variable_browse(cfg, "general"); var; var = var->next) {
1861                 /* handle jb conf */
1862                 if (!ast_jb_read_conf(&global_jbconf, var->name, var->value))
1863                         continue;
1864
1865                 if (!strcasecmp(var->name, "allowguest"))
1866                         allowguest =
1867                                 (ast_true(ast_variable_retrieve(cfg, "general", "allowguest"))) ? 1 : 0;
1868                 else if (!strcasecmp(var->name, "disallow"))
1869                         ast_parse_allow_disallow(&prefs, global_capability, var->value, 0);
1870                 else if (!strcasecmp(var->name, "allow"))
1871                         ast_parse_allow_disallow(&prefs, global_capability, var->value, 1);
1872                 else if (!strcasecmp(var->name, "context"))
1873                         ast_copy_string(context, var->value, sizeof(context));
1874                 else if (!strcasecmp(var->name, "externip"))
1875                         ast_copy_string(externip, var->value, sizeof(externip));
1876                 else if (!strcasecmp(var->name, "bindaddr")) {
1877                         if (!(hp = ast_gethostbyname(var->value, &ahp))) {
1878                                 ast_log(LOG_WARNING, "Invalid address: %s\n", var->value);
1879                         } else {
1880                                 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
1881                         }
1882                 }
1883 /*  Idea to allow for custom candidates  */
1884 /*
1885                 else if (!strcasecmp(var->name, "candidate")) {
1886                         candidate = jingle_create_candidate(var->value);
1887                         if (candidate) {
1888                                 candidate->next = global_candidates;
1889                                 global_candidates = candidate;
1890                         }
1891                 }
1892 */
1893         }
1894         while (cat) {
1895                 if (strcasecmp(cat, "general")) {
1896                         var = ast_variable_browse(cfg, cat);
1897                         member = ast_calloc(1, sizeof(*member));
1898                         ASTOBJ_INIT(member);
1899                         ASTOBJ_WRLOCK(member);
1900                         member->cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_NOLOCK);
1901                         if (!strcasecmp(cat, "guest")) {
1902                                 ast_copy_string(member->name, "guest", sizeof(member->name));
1903                                 ast_copy_string(member->user, "guest", sizeof(member->user));
1904                                 ast_copy_string(member->context, context, sizeof(member->context));
1905                                 member->allowguest = allowguest;
1906                                 member->prefs = prefs;
1907                                 while (var) {
1908                                         if (!strcasecmp(var->name, "disallow"))
1909                                                 ast_parse_allow_disallow(&member->prefs, member->cap,
1910                                                                                                  var->value, 0);
1911                                         else if (!strcasecmp(var->name, "allow"))
1912                                                 ast_parse_allow_disallow(&member->prefs, member->cap,
1913                                                                                                  var->value, 1);
1914                                         else if (!strcasecmp(var->name, "context"))
1915                                                 ast_copy_string(member->context, var->value,
1916                                                                                 sizeof(member->context));
1917                                         else if (!strcasecmp(var->name, "parkinglot"))
1918                                                 ast_copy_string(member->parkinglot, var->value,
1919                                                                                 sizeof(member->parkinglot));
1920 /*  Idea to allow for custom candidates  */
1921 /*
1922                                         else if (!strcasecmp(var->name, "candidate")) {
1923                                                 candidate = jingle_create_candidate(var->value);
1924                                                 if (candidate) {
1925                                                         candidate->next = member->ourcandidates;
1926                                                         member->ourcandidates = candidate;
1927                                                 }
1928                                         }
1929 */
1930                                         var = var->next;
1931                                 }
1932                                 ASTOBJ_UNLOCK(member);
1933                                 clients = ast_aji_get_clients();
1934                                 if (clients) {
1935                                         ASTOBJ_CONTAINER_TRAVERSE(clients, 1, {
1936                                                 ASTOBJ_WRLOCK(iterator);
1937                                                 ASTOBJ_WRLOCK(member);
1938                                                 if (member->connection) {
1939                                                         ASTOBJ_UNREF(member->connection, ast_aji_client_destroy);
1940                                                 }
1941                                                 member->connection = NULL;
1942                                                 iks_filter_add_rule(iterator->f, jingle_parser, member, IKS_RULE_TYPE, IKS_PAK_IQ, IKS_RULE_NS, JINGLE_NS, IKS_RULE_DONE);
1943                                                 iks_filter_add_rule(iterator->f, jingle_parser, member, IKS_RULE_TYPE, IKS_PAK_IQ, IKS_RULE_NS, JINGLE_DTMF_NS, IKS_RULE_DONE);
1944                                                 ASTOBJ_UNLOCK(member);
1945                                                 ASTOBJ_UNLOCK(iterator);
1946                                         });
1947                                         ASTOBJ_CONTAINER_LINK(&jingle_list, member);
1948                                 } else {
1949                                         ASTOBJ_UNLOCK(member);
1950                                         ASTOBJ_UNREF(member, jingle_member_destroy);
1951                                 }
1952                         } else {
1953                                 ASTOBJ_UNLOCK(member);
1954                                 if (jingle_create_member(cat, var, allowguest, prefs, context, member))
1955                                         ASTOBJ_CONTAINER_LINK(&jingle_list, member);
1956                                 ASTOBJ_UNREF(member, jingle_member_destroy);
1957                         }
1958                 }
1959                 cat = ast_category_browse(cfg, cat);
1960         }
1961         ast_config_destroy(cfg);
1962         jingle_free_candidates(global_candidates);
1963         return 1;
1964 }
1965
1966 /*!
1967  * \brief Load the module
1968  *
1969  * Module loading including tests for configuration or dependencies.
1970  * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
1971  * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
1972  * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the 
1973  * configuration file or other non-critical problem return 
1974  * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
1975  */
1976 static int load_module(void)
1977 {
1978         struct ast_sockaddr ourip_tmp;
1979         struct ast_sockaddr bindaddr_tmp;
1980         struct ast_format tmpfmt;
1981
1982         char *jabber_loaded = ast_module_helper("", "res_jabber.so", 0, 0, 0, 0);
1983
1984         if (!(jingle_tech.capabilities = ast_format_cap_alloc(0))) {
1985                 return AST_MODULE_LOAD_DECLINE;
1986         }
1987
1988         ast_format_cap_add_all_by_type(jingle_tech.capabilities, AST_FORMAT_TYPE_AUDIO);
1989         if (!(global_capability = ast_format_cap_alloc(0))) {
1990                 return AST_MODULE_LOAD_DECLINE;
1991         }
1992         ast_format_cap_add(global_capability, ast_format_set(&tmpfmt, AST_FORMAT_ULAW, 0));
1993         ast_format_cap_add(global_capability, ast_format_set(&tmpfmt, AST_FORMAT_GSM, 0));
1994         ast_format_cap_add(global_capability, ast_format_set(&tmpfmt, AST_FORMAT_ALAW, 0));
1995         ast_format_cap_add(global_capability, ast_format_set(&tmpfmt, AST_FORMAT_H263, 0));
1996
1997         free(jabber_loaded);
1998         if (!jabber_loaded) {
1999                 /* Dependency module has a different name, if embedded */
2000                 jabber_loaded = ast_module_helper("", "res_jabber", 0, 0, 0, 0);
2001                 free(jabber_loaded);
2002                 if (!jabber_loaded) {
2003                         ast_log(LOG_ERROR, "chan_jingle.so depends upon res_jabber.so\n");
2004                         return AST_MODULE_LOAD_DECLINE;
2005                 }
2006         }
2007
2008         ASTOBJ_CONTAINER_INIT(&jingle_list);
2009         if (!jingle_load_config()) {
2010                 ast_log(LOG_ERROR, "Unable to read config file %s. Not loading module.\n", JINGLE_CONFIG);
2011                 return AST_MODULE_LOAD_DECLINE;
2012         }
2013
2014         sched = ast_sched_context_create();
2015         if (!sched) {
2016                 ast_log(LOG_WARNING, "Unable to create schedule context\n");
2017         }
2018
2019         io = io_context_create();
2020         if (!io) {
2021                 ast_log(LOG_WARNING, "Unable to create I/O context\n");
2022         }
2023
2024         bindaddr.sin_family = AF_INET;
2025         ast_sockaddr_from_sin(&bindaddr_tmp, &bindaddr);
2026         if (ast_find_ourip(&ourip_tmp, &bindaddr_tmp, AF_INET)) {
2027                 ast_log(LOG_WARNING, "Unable to get own IP address, Jingle disabled\n");
2028                 return 0;
2029         }
2030         __ourip.s_addr = htonl(ast_sockaddr_ipv4(&ourip_tmp));
2031
2032         ast_rtp_glue_register(&jingle_rtp_glue);
2033         ast_cli_register_multiple(jingle_cli, ARRAY_LEN(jingle_cli));
2034         /* Make sure we can register our channel type */
2035         if (ast_channel_register(&jingle_tech)) {
2036                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", channel_type);
2037                 return -1;
2038         }
2039         return 0;
2040 }
2041
2042 /*! \brief Reload module */
2043 static int reload(void)
2044 {
2045         return 0;
2046 }
2047
2048 /*! \brief Unload the jingle channel from Asterisk */
2049 static int unload_module(void)
2050 {
2051         struct jingle_pvt *privates = NULL;
2052         ast_cli_unregister_multiple(jingle_cli, ARRAY_LEN(jingle_cli));
2053         /* First, take us out of the channel loop */
2054         ast_channel_unregister(&jingle_tech);
2055         ast_rtp_glue_unregister(&jingle_rtp_glue);
2056
2057         if (!ast_mutex_lock(&jinglelock)) {
2058                 /* Hangup all interfaces if they have an owner */
2059                 ASTOBJ_CONTAINER_TRAVERSE(&jingle_list, 1, {
2060                         ASTOBJ_WRLOCK(iterator);
2061                         privates = iterator->p;
2062                         while(privates) {
2063                                 if (privates->owner)
2064                                         ast_softhangup(privates->owner, AST_SOFTHANGUP_APPUNLOAD);
2065                                 privates = privates->next;
2066                         }
2067                         iterator->p = NULL;
2068                         ASTOBJ_UNLOCK(iterator);
2069                 });
2070                 ast_mutex_unlock(&jinglelock);
2071         } else {
2072                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
2073                 return -1;
2074         }
2075         ASTOBJ_CONTAINER_DESTROYALL(&jingle_list, jingle_member_destroy);
2076         ASTOBJ_CONTAINER_DESTROY(&jingle_list);
2077
2078         global_capability = ast_format_cap_destroy(global_capability);
2079         return 0;
2080 }
2081
2082 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Jingle Channel Driver",
2083                 .load = load_module,
2084                 .unload = unload_module,
2085                 .reload = reload,
2086                 .load_pri = AST_MODPRI_CHANNEL_DRIVER,
2087                );