Doxygen Cleanup
[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 /*!
31  * \li The channel chan_jingle uses the configuration file \ref jingle.conf
32  * \addtogroup configuration_file
33  */
34
35 /*! \page jingle.conf jingle.conf
36  * \verbinclude jingle.conf.sample
37  */
38
39 /*** MODULEINFO
40         <depend>iksemel</depend>
41         <depend>res_jabber</depend>
42         <use type="external">openssl</use>
43         <defaultenabled>no</defaultenabled>
44         <support_level>deprecated</support_level>
45         <replacement>chan_motif</replacement>
46  ***/
47
48 #include "asterisk.h"
49
50 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
51
52 #include <sys/socket.h>
53 #include <fcntl.h>
54 #include <netdb.h>
55 #include <netinet/in.h>
56 #include <arpa/inet.h>
57 #include <sys/signal.h>
58 #include <iksemel.h>
59 #include <pthread.h>
60
61 #include "asterisk/lock.h"
62 #include "asterisk/channel.h"
63 #include "asterisk/config.h"
64 #include "asterisk/module.h"
65 #include "asterisk/pbx.h"
66 #include "asterisk/sched.h"
67 #include "asterisk/io.h"
68 #include "asterisk/rtp_engine.h"
69 #include "asterisk/acl.h"
70 #include "asterisk/callerid.h"
71 #include "asterisk/file.h"
72 #include "asterisk/cli.h"
73 #include "asterisk/app.h"
74 #include "asterisk/musiconhold.h"
75 #include "asterisk/manager.h"
76 #include "asterisk/stringfields.h"
77 #include "asterisk/utils.h"
78 #include "asterisk/causes.h"
79 #include "asterisk/astobj.h"
80 #include "asterisk/abstract_jb.h"
81 #include "asterisk/jabber.h"
82 #include "asterisk/jingle.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
201 /*! \brief PBX interface structure for channel registration */
202 static struct ast_channel_tech jingle_tech = {
203         .type = "Jingle",
204         .description = "Jingle Channel Driver",
205         .requester = jingle_request,
206         .send_text = jingle_sendtext,
207         .send_digit_begin = jingle_digit_begin,
208         .send_digit_end = jingle_digit_end,
209         .bridge = ast_rtp_instance_bridge,
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_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_nolock();
802         tmp->jointcap = ast_format_cap_alloc_nolock();
803         tmp->peercap = ast_format_cap_alloc_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 /*! \brief Start new jingle channel */
839 static struct ast_channel *jingle_new(struct jingle *client, struct jingle_pvt *i, int state, const char *title, const char *linkedid)
840 {
841         struct ast_channel *tmp;
842         struct ast_format_cap *what;  /* SHALLOW COPY DO NOT DESTROY */
843         struct ast_format tmpfmt;
844         const char *str;
845
846         if (title)
847                 str = title;
848         else
849                 str = i->them;
850         tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, "", "", "", linkedid, 0, "Jingle/%s-%04lx", str, ast_random() & 0xffff);
851         if (!tmp) {
852                 ast_log(LOG_WARNING, "Unable to allocate Jingle channel structure!\n");
853                 return NULL;
854         }
855         ast_channel_tech_set(tmp, &jingle_tech);
856
857         /* Select our native format based on codec preference until we receive
858            something from another device to the contrary. */
859         if (!ast_format_cap_is_empty(i->jointcap))
860                 what = i->jointcap;
861         else if (!(ast_format_cap_is_empty(i->cap)))
862                 what = i->cap;
863         else
864                 what = global_capability;
865
866         /* Set Frame packetization */
867         if (i->rtp)
868                 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(i->rtp), i->rtp, &i->prefs);
869
870         ast_codec_choose(&i->prefs, what, 1, &tmpfmt);
871         ast_format_cap_add(ast_channel_nativeformats(tmp), &tmpfmt);
872
873         ast_format_cap_iter_start(i->jointcap);
874         while (!(ast_format_cap_iter_next(i->jointcap, &tmpfmt))) {
875                 if (AST_FORMAT_GET_TYPE(tmpfmt.id) == AST_FORMAT_TYPE_VIDEO) {
876                         ast_format_cap_add(ast_channel_nativeformats(tmp), &tmpfmt);
877                 }
878         }
879         ast_format_cap_iter_end(i->jointcap);
880
881         if (i->rtp) {
882                 ast_channel_set_fd(tmp, 0, ast_rtp_instance_fd(i->rtp, 0));
883                 ast_channel_set_fd(tmp, 1, ast_rtp_instance_fd(i->rtp, 1));
884         }
885         if (i->vrtp) {
886                 ast_channel_set_fd(tmp, 2, ast_rtp_instance_fd(i->vrtp, 0));
887                 ast_channel_set_fd(tmp, 3, ast_rtp_instance_fd(i->vrtp, 1));
888         }
889         if (state == AST_STATE_RING)
890                 ast_channel_rings_set(tmp, 1);
891         ast_channel_adsicpe_set(tmp, AST_ADSI_UNAVAILABLE);
892
893
894         ast_best_codec(ast_channel_nativeformats(tmp), &tmpfmt);
895         ast_format_copy(ast_channel_writeformat(tmp), &tmpfmt);
896         ast_format_copy(ast_channel_rawwriteformat(tmp), &tmpfmt);
897         ast_format_copy(ast_channel_readformat(tmp), &tmpfmt);
898         ast_format_copy(ast_channel_rawreadformat(tmp), &tmpfmt);
899         ast_channel_tech_pvt_set(tmp, i);
900
901         ast_channel_callgroup_set(tmp, client->callgroup);
902         ast_channel_pickupgroup_set(tmp, client->pickupgroup);
903         ast_channel_caller(tmp)->id.name.presentation = client->callingpres;
904         ast_channel_caller(tmp)->id.number.presentation = client->callingpres;
905         if (!ast_strlen_zero(client->accountcode))
906                 ast_channel_accountcode_set(tmp, client->accountcode);
907         if (client->amaflags)
908                 ast_channel_amaflags_set(tmp, client->amaflags);
909         if (!ast_strlen_zero(client->language))
910                 ast_channel_language_set(tmp, client->language);
911         if (!ast_strlen_zero(client->musicclass))
912                 ast_channel_musicclass_set(tmp, client->musicclass);
913         i->owner = tmp;
914         ast_channel_context_set(tmp, client->context);
915         ast_channel_exten_set(tmp, i->exten);
916         /* Don't use ast_set_callerid() here because it will
917          * generate an unnecessary NewCallerID event  */
918         if (!ast_strlen_zero(i->cid_num)) {
919                 ast_channel_caller(tmp)->ani.number.valid = 1;
920                 ast_channel_caller(tmp)->ani.number.str = ast_strdup(i->cid_num);
921         }
922         if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s")) {
923                 ast_channel_dialed(tmp)->number.str = ast_strdup(i->exten);
924         }
925         ast_channel_priority_set(tmp, 1);
926         if (i->rtp)
927                 ast_jb_configure(tmp, &global_jbconf);
928         if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
929                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", ast_channel_name(tmp));
930                 ast_channel_hangupcause_set(tmp, AST_CAUSE_SWITCH_CONGESTION);
931                 ast_hangup(tmp);
932                 tmp = NULL;
933         }
934
935         return tmp;
936 }
937
938 static int jingle_action(struct jingle *client, struct jingle_pvt *p, const char *action)
939 {
940         iks *iq, *jingle = NULL;
941         int res = -1;
942
943         iq = iks_new("iq");
944         jingle = iks_new("jingle");
945         
946         if (iq) {
947                 iks_insert_attrib(iq, "type", "set");
948                 iks_insert_attrib(iq, "from", client->connection->jid->full);
949                 iks_insert_attrib(iq, "to", p->them);
950                 iks_insert_attrib(iq, "id", client->connection->mid);
951                 ast_aji_increment_mid(client->connection->mid);
952                 if (jingle) {
953                         iks_insert_attrib(jingle, "action", action);
954                         iks_insert_attrib(jingle, JINGLE_SID, p->sid);
955                         iks_insert_attrib(jingle, "initiator", p->initiator ? client->connection->jid->full : p->them);
956                         iks_insert_attrib(jingle, "xmlns", JINGLE_NS);
957
958                         iks_insert_node(iq, jingle);
959
960                         ast_aji_send(client->connection, iq);
961                         res = 0;
962                 }
963         }
964         
965         iks_delete(jingle);
966         iks_delete(iq);
967         
968         return res;
969 }
970
971 static void jingle_free_candidates(struct jingle_candidate *candidate)
972 {
973         struct jingle_candidate *last;
974         while (candidate) {
975                 last = candidate;
976                 candidate = candidate->next;
977                 ast_free(last);
978         }
979 }
980
981 static void jingle_free_pvt(struct jingle *client, struct jingle_pvt *p)
982 {
983         struct jingle_pvt *cur, *prev = NULL;
984         cur = client->p;
985         while (cur) {
986                 if (cur == p) {
987                         if (prev)
988                                 prev->next = p->next;
989                         else
990                                 client->p = p->next;
991                         break;
992                 }
993                 prev = cur;
994                 cur = cur->next;
995         }
996         if (p->ringrule)
997                 iks_filter_remove_rule(p->parent->connection->f, p->ringrule);
998         if (p->owner)
999                 ast_log(LOG_WARNING, "Uh oh, there's an owner, this is going to be messy.\n");
1000         if (p->rtp)
1001                 ast_rtp_instance_destroy(p->rtp);
1002         if (p->vrtp)
1003                 ast_rtp_instance_destroy(p->vrtp);
1004         jingle_free_candidates(p->theircandidates);
1005         p->cap = ast_format_cap_destroy(p->cap);
1006         p->jointcap = ast_format_cap_destroy(p->jointcap);
1007         p->peercap = ast_format_cap_destroy(p->peercap);
1008
1009         ast_free(p);
1010 }
1011
1012
1013 static int jingle_newcall(struct jingle *client, ikspak *pak)
1014 {
1015         struct jingle_pvt *p, *tmp = client->p;
1016         struct ast_channel *chan;
1017         int res;
1018         iks *codec, *content, *description;
1019         char *from = NULL;
1020
1021         /* Make sure our new call doesn't exist yet */
1022         from = iks_find_attrib(pak->x,"to");
1023         if(!from)
1024                 from = client->connection->jid->full;
1025
1026         while (tmp) {
1027                 if (iks_find_with_attrib(pak->x, JINGLE_NODE, JINGLE_SID, tmp->sid)) {
1028                         ast_log(LOG_NOTICE, "Ignoring duplicate call setup on SID %s\n", tmp->sid);
1029                         jingle_response(client, pak, "out-of-order", NULL);
1030                         return -1;
1031                 }
1032                 tmp = tmp->next;
1033         }
1034
1035         if (!strcasecmp(client->name, "guest")){
1036                 /* the guest account is not tied to any configured XMPP client,
1037                    let's set it now */
1038                 if (client->connection) {
1039                         ASTOBJ_UNREF(client->connection, ast_aji_client_destroy);
1040                 }
1041                 client->connection = ast_aji_get_client(from);
1042                 if (!client->connection) {
1043                         ast_log(LOG_ERROR, "No XMPP client to talk to, us (partial JID) : %s\n", from);
1044                         return -1;
1045                 }
1046         }
1047
1048         p = jingle_alloc(client, pak->from->partial, iks_find_attrib(pak->query, JINGLE_SID));
1049         if (!p) {
1050                 ast_log(LOG_WARNING, "Unable to allocate jingle structure!\n");
1051                 return -1;
1052         }
1053         chan = jingle_new(client, p, AST_STATE_DOWN, pak->from->user, NULL);
1054         if (!chan) {
1055                 jingle_free_pvt(client, p);
1056                 return -1;
1057         }
1058         ast_mutex_lock(&p->lock);
1059         ast_copy_string(p->them, pak->from->full, sizeof(p->them));
1060         if (iks_find_attrib(pak->query, JINGLE_SID)) {
1061                 ast_copy_string(p->sid, iks_find_attrib(pak->query, JINGLE_SID),
1062                                 sizeof(p->sid));
1063         }
1064         
1065         /* content points to the first <content/> tag */        
1066         content = iks_child(iks_child(pak->x));
1067         while (content) {
1068                 description = iks_find_with_attrib(content, "description", "xmlns", JINGLE_AUDIO_RTP_NS);
1069                 if (description) {
1070                         /* audio content found */
1071                         codec = iks_child(iks_child(content));
1072                         ast_copy_string(p->audio_content_name, iks_find_attrib(content, "name"), sizeof(p->audio_content_name));
1073
1074                         while (codec) {
1075                                 ast_rtp_codecs_payloads_set_m_type(ast_rtp_instance_get_codecs(p->rtp), p->rtp, atoi(iks_find_attrib(codec, "id")));
1076                                 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);
1077                                 codec = iks_next(codec);
1078                         }
1079                 }
1080                 
1081                 description = NULL;
1082                 codec = NULL;
1083
1084                 description = iks_find_with_attrib(content, "description", "xmlns", JINGLE_VIDEO_RTP_NS);
1085                 if (description) {
1086                         /* video content found */
1087                         codec = iks_child(iks_child(content));
1088                         ast_copy_string(p->video_content_name, iks_find_attrib(content, "name"), sizeof(p->video_content_name));
1089
1090                         while (codec) {
1091                                 ast_rtp_codecs_payloads_set_m_type(ast_rtp_instance_get_codecs(p->rtp), p->rtp, atoi(iks_find_attrib(codec, "id")));
1092                                 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);
1093                                 codec = iks_next(codec);
1094                         }
1095                 }
1096                 
1097                 content = iks_next(content);
1098         }
1099
1100         ast_mutex_unlock(&p->lock);
1101         ast_setstate(chan, AST_STATE_RING);
1102         res = ast_pbx_start(chan);
1103         
1104         switch (res) {
1105         case AST_PBX_FAILED:
1106                 ast_log(LOG_WARNING, "Failed to start PBX :(\n");
1107                 jingle_response(client, pak, "service-unavailable", NULL);
1108                 break;
1109         case AST_PBX_CALL_LIMIT:
1110                 ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
1111                 jingle_response(client, pak, "service-unavailable", NULL);
1112                 break;
1113         case AST_PBX_SUCCESS:
1114                 jingle_response(client, pak, NULL, NULL);
1115                 jingle_create_candidates(client, p,
1116                                          iks_find_attrib(pak->query, JINGLE_SID),
1117                                          iks_find_attrib(pak->x, "from"));
1118                 /* nothing to do */
1119                 break;
1120         }
1121
1122         return 1;
1123 }
1124
1125 static int jingle_update_stun(struct jingle *client, struct jingle_pvt *p)
1126 {
1127         struct jingle_candidate *tmp;
1128         struct hostent *hp;
1129         struct ast_hostent ahp;
1130         struct sockaddr_in sin;
1131         struct ast_sockaddr sin_tmp;
1132
1133         if (time(NULL) == p->laststun)
1134                 return 0;
1135
1136         tmp = p->theircandidates;
1137         p->laststun = time(NULL);
1138         while (tmp) {
1139                 char username[256];
1140                 hp = ast_gethostbyname(tmp->ip, &ahp);
1141                 sin.sin_family = AF_INET;
1142                 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
1143                 sin.sin_port = htons(tmp->port);
1144                 snprintf(username, sizeof(username), "%s:%s", tmp->ufrag, p->ourcandidates->ufrag);
1145
1146                 ast_sockaddr_from_sin(&sin_tmp, &sin);
1147                 ast_rtp_instance_stun_request(p->rtp, &sin_tmp, username);
1148                 tmp = tmp->next;
1149         }
1150         return 1;
1151 }
1152
1153 static int jingle_add_candidate(struct jingle *client, ikspak *pak)
1154 {
1155         struct jingle_pvt *p = NULL, *tmp = NULL;
1156         struct aji_client *c = client->connection;
1157         struct jingle_candidate *newcandidate = NULL;
1158         iks *traversenodes = NULL, *receipt = NULL;
1159
1160         for (tmp = client->p; tmp; tmp = tmp->next) {
1161                 if (iks_find_with_attrib(pak->x, JINGLE_NODE, JINGLE_SID, tmp->sid)) {
1162                         p = tmp;
1163                         break;
1164                 }
1165         }
1166
1167         if (!p)
1168                 return -1;
1169
1170         traversenodes = pak->query;
1171         while(traversenodes) {
1172                 if(!strcasecmp(iks_name(traversenodes), "jingle")) {
1173                         traversenodes = iks_child(traversenodes);
1174                         continue;
1175                 }
1176                 if(!strcasecmp(iks_name(traversenodes), "content")) {
1177                         traversenodes = iks_child(traversenodes);
1178                         continue;
1179                 }
1180                 if(!strcasecmp(iks_name(traversenodes), "transport")) {
1181                         traversenodes = iks_child(traversenodes);
1182                         continue;
1183                 }
1184
1185                 if(!strcasecmp(iks_name(traversenodes), "candidate")) {
1186                         newcandidate = ast_calloc(1, sizeof(*newcandidate));
1187                         if (!newcandidate)
1188                                 return 0;
1189                         ast_copy_string(newcandidate->ip, iks_find_attrib(traversenodes, "ip"), sizeof(newcandidate->ip));
1190                         newcandidate->port = atoi(iks_find_attrib(traversenodes, "port"));
1191                         ast_copy_string(newcandidate->password, iks_find_attrib(traversenodes, "pwd"), sizeof(newcandidate->password));
1192                         if (!strcasecmp(iks_find_attrib(traversenodes, "protocol"), "udp"))
1193                                 newcandidate->protocol = AJI_PROTOCOL_UDP;
1194                         else if (!strcasecmp(iks_find_attrib(traversenodes, "protocol"), "ssltcp"))
1195                                 newcandidate->protocol = AJI_PROTOCOL_SSLTCP;
1196                         
1197                         if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "host"))
1198                                 newcandidate->type = AJI_CONNECT_HOST;
1199                         else if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "prflx"))
1200                                 newcandidate->type = AJI_CONNECT_PRFLX;
1201                         else if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "relay"))
1202                                 newcandidate->type = AJI_CONNECT_RELAY;
1203                         else if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "srflx"))
1204                                 newcandidate->type = AJI_CONNECT_SRFLX;
1205
1206                         newcandidate->network = atoi(iks_find_attrib(traversenodes, "network"));
1207                         newcandidate->generation = atoi(iks_find_attrib(traversenodes, "generation"));
1208                         newcandidate->next = NULL;
1209                 
1210                         newcandidate->next = p->theircandidates;
1211                         p->theircandidates = newcandidate;
1212                         p->laststun = 0;
1213                         jingle_update_stun(p->parent, p);
1214                         newcandidate = NULL;
1215                 }
1216                 traversenodes = iks_next(traversenodes);
1217         }
1218         
1219         receipt = iks_new("iq");
1220         iks_insert_attrib(receipt, "type", "result");
1221         iks_insert_attrib(receipt, "from", c->jid->full);
1222         iks_insert_attrib(receipt, "to", iks_find_attrib(pak->x, "from"));
1223         iks_insert_attrib(receipt, "id", iks_find_attrib(pak->x, "id"));
1224         ast_aji_send(c, receipt);
1225
1226         iks_delete(receipt);
1227
1228         return 1;
1229 }
1230
1231 static struct ast_frame *jingle_rtp_read(struct ast_channel *ast, struct jingle_pvt *p)
1232 {
1233         struct ast_frame *f;
1234
1235         if (!p->rtp)
1236                 return &ast_null_frame;
1237         f = ast_rtp_instance_read(p->rtp, 0);
1238         jingle_update_stun(p->parent, p);
1239         if (p->owner) {
1240                 /* We already hold the channel lock */
1241                 if (f->frametype == AST_FRAME_VOICE) {
1242                         if (!(ast_format_cap_iscompatible(ast_channel_nativeformats(p->owner), &f->subclass.format))) {
1243                                 ast_debug(1, "Oooh, format changed to %s\n", ast_getformatname(&f->subclass.format));
1244                                 ast_format_cap_remove_bytype(ast_channel_nativeformats(p->owner), AST_FORMAT_TYPE_AUDIO);
1245                                 ast_format_cap_add(ast_channel_nativeformats(p->owner), &f->subclass.format);
1246                                 ast_set_read_format(p->owner, ast_channel_readformat(p->owner));
1247                                 ast_set_write_format(p->owner, ast_channel_writeformat(p->owner));
1248                         }
1249 /*                      if ((ast_test_flag(p, SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
1250                                 f = ast_dsp_process(p->owner, p->vad, f);
1251                                 if (f && (f->frametype == AST_FRAME_DTMF))
1252                                         ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass.codec);
1253                         } */
1254                 }
1255         }
1256         return f;
1257 }
1258
1259 static struct ast_frame *jingle_read(struct ast_channel *ast)
1260 {
1261         struct ast_frame *fr;
1262         struct jingle_pvt *p = ast_channel_tech_pvt(ast);
1263
1264         ast_mutex_lock(&p->lock);
1265         fr = jingle_rtp_read(ast, p);
1266         ast_mutex_unlock(&p->lock);
1267         return fr;
1268 }
1269
1270 /*! \brief Send frame to media channel (rtp) */
1271 static int jingle_write(struct ast_channel *ast, struct ast_frame *frame)
1272 {
1273         struct jingle_pvt *p = ast_channel_tech_pvt(ast);
1274         int res = 0;
1275         char buf[256];
1276
1277         switch (frame->frametype) {
1278         case AST_FRAME_VOICE:
1279                 if (!(ast_format_cap_iscompatible(ast_channel_nativeformats(ast), &frame->subclass.format))) {
1280                         ast_log(LOG_WARNING,
1281                                         "Asked to transmit frame type %s, while native formats is %s (read/write = %s/%s)\n",
1282                                         ast_getformatname(&frame->subclass.format),
1283                                         ast_getformatname_multiple(buf, sizeof(buf), ast_channel_nativeformats(ast)),
1284                                         ast_getformatname(ast_channel_readformat(ast)),
1285                                         ast_getformatname(ast_channel_writeformat(ast)));
1286                         return 0;
1287                 }
1288                 if (p) {
1289                         ast_mutex_lock(&p->lock);
1290                         if (p->rtp) {
1291                                 res = ast_rtp_instance_write(p->rtp, frame);
1292                         }
1293                         ast_mutex_unlock(&p->lock);
1294                 }
1295                 break;
1296         case AST_FRAME_VIDEO:
1297                 if (p) {
1298                         ast_mutex_lock(&p->lock);
1299                         if (p->vrtp) {
1300                                 res = ast_rtp_instance_write(p->vrtp, frame);
1301                         }
1302                         ast_mutex_unlock(&p->lock);
1303                 }
1304                 break;
1305         case AST_FRAME_IMAGE:
1306                 return 0;
1307                 break;
1308         default:
1309                 ast_log(LOG_WARNING, "Can't send %d type frames with Jingle write\n",
1310                                 frame->frametype);
1311                 return 0;
1312         }
1313
1314         return res;
1315 }
1316
1317 static int jingle_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1318 {
1319         struct jingle_pvt *p = ast_channel_tech_pvt(newchan);
1320         ast_mutex_lock(&p->lock);
1321
1322         if ((p->owner != oldchan)) {
1323                 ast_mutex_unlock(&p->lock);
1324                 return -1;
1325         }
1326         if (p->owner == oldchan)
1327                 p->owner = newchan;
1328         ast_mutex_unlock(&p->lock);
1329         return 0;
1330 }
1331
1332 static int jingle_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
1333 {
1334         int res = 0;
1335
1336         switch (condition) {
1337         case AST_CONTROL_HOLD:
1338                 ast_moh_start(ast, data, NULL);
1339                 break;
1340         case AST_CONTROL_UNHOLD:
1341                 ast_moh_stop(ast);
1342                 break;
1343         default:
1344                 ast_log(LOG_NOTICE, "Don't know how to indicate condition '%d'\n", condition);
1345                 /* fallthrough */
1346         case AST_CONTROL_PVT_CAUSE_CODE:
1347                 res = -1;
1348         }
1349
1350         return res;
1351 }
1352
1353 static int jingle_sendtext(struct ast_channel *chan, const char *text)
1354 {
1355         int res = 0;
1356         struct aji_client *client = NULL;
1357         struct jingle_pvt *p = ast_channel_tech_pvt(chan);
1358
1359
1360         if (!p->parent) {
1361                 ast_log(LOG_ERROR, "Parent channel not found\n");
1362                 return -1;
1363         }
1364         if (!p->parent->connection) {
1365                 ast_log(LOG_ERROR, "XMPP client not found\n");
1366                 return -1;
1367         }
1368         client = p->parent->connection;
1369         res = ast_aji_send_chat(client, p->them, text);
1370         return res;
1371 }
1372
1373 static int jingle_digit(struct ast_channel *ast, char digit, unsigned int duration)
1374 {
1375         struct jingle_pvt *p = ast_channel_tech_pvt(ast);
1376         struct jingle *client = p->parent;
1377         iks *iq, *jingle, *dtmf;
1378         char buffer[2] = {digit, '\0'};
1379         iq = iks_new("iq");
1380         jingle = iks_new("jingle");
1381         dtmf = iks_new("dtmf");
1382         if(!iq || !jingle || !dtmf) {
1383                 iks_delete(iq);
1384                 iks_delete(jingle);
1385                 iks_delete(dtmf);
1386                 ast_log(LOG_ERROR, "Did not send dtmf do to memory issue\n");
1387                 return -1;
1388         }
1389
1390         iks_insert_attrib(iq, "type", "set");
1391         iks_insert_attrib(iq, "to", p->them);
1392         iks_insert_attrib(iq, "from", client->connection->jid->full);
1393         iks_insert_attrib(iq, "id", client->connection->mid);
1394         ast_aji_increment_mid(client->connection->mid);
1395         iks_insert_attrib(jingle, "xmlns", JINGLE_NS);
1396         iks_insert_attrib(jingle, "action", "session-info");
1397         iks_insert_attrib(jingle, "initiator", p->initiator ? client->connection->jid->full : p->them);
1398         iks_insert_attrib(jingle, "sid", p->sid);
1399         iks_insert_attrib(dtmf, "xmlns", JINGLE_DTMF_NS);
1400         iks_insert_attrib(dtmf, "code", buffer);
1401         iks_insert_node(iq, jingle);
1402         iks_insert_node(jingle, dtmf);
1403
1404         ast_mutex_lock(&p->lock);
1405         if (ast_channel_dtmff(ast)->frametype == AST_FRAME_DTMF_BEGIN || duration == 0) {
1406                 iks_insert_attrib(dtmf, "action", "button-down");
1407         } else if (ast_channel_dtmff(ast)->frametype == AST_FRAME_DTMF_END || duration != 0) {
1408                 iks_insert_attrib(dtmf, "action", "button-up");
1409         }
1410         ast_aji_send(client->connection, iq);
1411
1412         iks_delete(iq);
1413         iks_delete(jingle);
1414         iks_delete(dtmf);
1415         ast_mutex_unlock(&p->lock);
1416         return 0;
1417 }
1418
1419 static int jingle_digit_begin(struct ast_channel *chan, char digit)
1420 {
1421         return jingle_digit(chan, digit, 0);
1422 }
1423
1424 static int jingle_digit_end(struct ast_channel *ast, char digit, unsigned int duration)
1425 {
1426         return jingle_digit(ast, digit, duration);
1427 }
1428
1429 static int jingle_sendhtml(struct ast_channel *ast, int subclass, const char *data, int datalen)
1430 {
1431         ast_log(LOG_NOTICE, "XXX Implement jingle sendhtml XXX\n");
1432
1433         return -1;
1434 }
1435 static int jingle_transmit_invite(struct jingle_pvt *p)
1436 {
1437         struct jingle *aux = NULL;
1438         struct aji_client *client = NULL;
1439         iks *iq, *jingle, *content, *description, *transport;
1440         iks *payload_eg711u, *payload_pcmu;
1441
1442         aux = p->parent;
1443         client = aux->connection;
1444         iq = iks_new("iq");
1445         jingle = iks_new(JINGLE_NODE);
1446         content = iks_new("content");
1447         description = iks_new("description");
1448         transport = iks_new("transport");
1449         payload_pcmu = iks_new("payload-type");
1450         payload_eg711u = iks_new("payload-type");
1451
1452         ast_copy_string(p->audio_content_name, "asterisk-audio-content", sizeof(p->audio_content_name));
1453
1454         iks_insert_attrib(iq, "type", "set");
1455         iks_insert_attrib(iq, "to", p->them);
1456         iks_insert_attrib(iq, "from", client->jid->full);
1457         iks_insert_attrib(iq, "id", client->mid);
1458         ast_aji_increment_mid(client->mid);
1459         iks_insert_attrib(jingle, "action", JINGLE_INITIATE);
1460         iks_insert_attrib(jingle, JINGLE_SID, p->sid);
1461         iks_insert_attrib(jingle, "initiator", client->jid->full);
1462         iks_insert_attrib(jingle, "xmlns", JINGLE_NS);
1463
1464         /* For now, we only send one audio based content */
1465         iks_insert_attrib(content, "creator", "initiator");
1466         iks_insert_attrib(content, "name", p->audio_content_name);
1467         iks_insert_attrib(content, "profile", "RTP/AVP");
1468         iks_insert_attrib(description, "xmlns", JINGLE_AUDIO_RTP_NS);
1469         iks_insert_attrib(transport, "xmlns", JINGLE_ICE_UDP_NS);
1470         iks_insert_attrib(payload_pcmu, "id", "0");
1471         iks_insert_attrib(payload_pcmu, "name", "PCMU");
1472         iks_insert_attrib(payload_eg711u, "id", "100");
1473         iks_insert_attrib(payload_eg711u, "name", "EG711U");
1474         iks_insert_node(description, payload_pcmu);
1475         iks_insert_node(description, payload_eg711u);
1476         iks_insert_node(content, description);
1477         iks_insert_node(content, transport);
1478         iks_insert_node(jingle, content);
1479         iks_insert_node(iq, jingle);
1480
1481         ast_aji_send(client, iq);
1482
1483         iks_delete(iq);
1484         iks_delete(jingle);
1485         iks_delete(content);
1486         iks_delete(description);
1487         iks_delete(transport);
1488         iks_delete(payload_eg711u);
1489         iks_delete(payload_pcmu);
1490         return 0;
1491 }
1492
1493 /* Not in use right now.
1494 static int jingle_auto_congest(void *nothing)
1495 {
1496         struct jingle_pvt *p = nothing;
1497
1498         ast_mutex_lock(&p->lock);
1499         if (p->owner) {
1500                 if (!ast_channel_trylock(p->owner)) {
1501                         ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
1502                         ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
1503                         ast_channel_unlock(p->owner);
1504                 }
1505         }
1506         ast_mutex_unlock(&p->lock);
1507         return 0;
1508 }
1509 */
1510
1511 /*! \brief Initiate new call, part of PBX interface 
1512  *      dest is the dial string */
1513 static int jingle_call(struct ast_channel *ast, const char *dest, int timeout)
1514 {
1515         struct jingle_pvt *p = ast_channel_tech_pvt(ast);
1516
1517         if ((ast_channel_state(ast) != AST_STATE_DOWN) && (ast_channel_state(ast) != AST_STATE_RESERVED)) {
1518                 ast_log(LOG_WARNING, "jingle_call called on %s, neither down nor reserved\n", ast_channel_name(ast));
1519                 return -1;
1520         }
1521
1522         ast_setstate(ast, AST_STATE_RING);
1523         ast_format_cap_copy(p->jointcap, p->cap);
1524         if (!p->ringrule) {
1525                 ast_copy_string(p->ring, p->parent->connection->mid, sizeof(p->ring));
1526                 p->ringrule = iks_filter_add_rule(p->parent->connection->f, jingle_ringing_ack, p,
1527                                                         IKS_RULE_ID, p->ring, IKS_RULE_DONE);
1528         } else
1529                 ast_log(LOG_WARNING, "Whoa, already have a ring rule!\n");
1530
1531         jingle_transmit_invite(p);
1532         jingle_create_candidates(p->parent, p, p->sid, p->them);
1533
1534         return 0;
1535 }
1536
1537 /*! \brief Hangup a call through the jingle proxy channel */
1538 static int jingle_hangup(struct ast_channel *ast)
1539 {
1540         struct jingle_pvt *p = ast_channel_tech_pvt(ast);
1541         struct jingle *client;
1542
1543         ast_mutex_lock(&p->lock);
1544         client = p->parent;
1545         p->owner = NULL;
1546         ast_channel_tech_pvt_set(ast, NULL);
1547         if (!p->alreadygone)
1548                 jingle_action(client, p, JINGLE_TERMINATE);
1549         ast_mutex_unlock(&p->lock);
1550
1551         jingle_free_pvt(client, p);
1552
1553         return 0;
1554 }
1555
1556 /*! \brief Part of PBX interface */
1557 static struct ast_channel *jingle_request(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, const char *data, int *cause)
1558 {
1559         struct jingle_pvt *p = NULL;
1560         struct jingle *client = NULL;
1561         char *sender = NULL, *to = NULL, *s = NULL;
1562         struct ast_channel *chan = NULL;
1563
1564         if (data) {
1565                 s = ast_strdupa(data);
1566                 sender = strsep(&s, "/");
1567                 if (sender && (sender[0] != '\0'))
1568                         to = strsep(&s, "/");
1569                 if (!to) {
1570                         ast_log(LOG_ERROR, "Bad arguments in Jingle Dialstring: %s\n", data);
1571                         return NULL;
1572                 }
1573                 if (!to) {
1574                         ast_log(LOG_ERROR, "Bad arguments in Jingle Dialstring: %s\n", (char*) data);
1575                         return NULL;
1576                 }
1577         }
1578
1579         client = find_jingle(to, sender);
1580         if (!client) {
1581                 ast_log(LOG_WARNING, "Could not find recipient.\n");
1582                 return NULL;
1583         }
1584         if (!strcasecmp(client->name, "guest")){
1585                 /* the guest account is not tied to any configured XMPP client,
1586                    let's set it now */
1587                 if (client->connection) {
1588                         ASTOBJ_UNREF(client->connection, ast_aji_client_destroy);
1589                 }
1590                 client->connection = ast_aji_get_client(sender);
1591                 if (!client->connection) {
1592                         ast_log(LOG_ERROR, "No XMPP client to talk to, us (partial JID) : %s\n", sender);
1593                         return NULL;
1594                 }
1595         }
1596        
1597         ASTOBJ_WRLOCK(client);
1598         p = jingle_alloc(client, to, NULL);
1599         if (p)
1600                 chan = jingle_new(client, p, AST_STATE_DOWN, to, requestor ? ast_channel_linkedid(requestor) : NULL);
1601         ASTOBJ_UNLOCK(client);
1602
1603         return chan;
1604 }
1605
1606 /*! \brief CLI command "jingle show channels" */
1607 static char *jingle_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1608 {
1609 #define FORMAT  "%-30.30s  %-30.30s  %-15.15s  %-5.5s %-5.5s \n"
1610         struct jingle_pvt *p;
1611         struct ast_channel *chan;
1612         int numchans = 0;
1613         char them[AJI_MAX_JIDLEN];
1614         char *jid = NULL;
1615         char *resource = NULL;
1616
1617         switch (cmd) {
1618         case CLI_INIT:
1619                 e->command = "jingle show channels";
1620                 e->usage =
1621                         "Usage: jingle show channels\n"
1622                         "       Shows current state of the Jingle channels.\n";
1623                 return NULL;
1624         case CLI_GENERATE:
1625                 return NULL;
1626         }
1627
1628         if (a->argc != 3)
1629                 return CLI_SHOWUSAGE;
1630
1631         ast_mutex_lock(&jinglelock);
1632         ast_cli(a->fd, FORMAT, "Channel", "Jabber ID", "Resource", "Read", "Write");
1633         ASTOBJ_CONTAINER_TRAVERSE(&jingle_list, 1, {
1634                 ASTOBJ_WRLOCK(iterator);
1635                 p = iterator->p;
1636                 while(p) {
1637                         chan = p->owner;
1638                         ast_copy_string(them, p->them, sizeof(them));
1639                         jid = them;
1640                         resource = strchr(them, '/');
1641                         if (!resource)
1642                                 resource = "None";
1643                         else {
1644                                 *resource = '\0';
1645                                 resource ++;
1646                         }
1647                         if (chan)
1648                                 ast_cli(a->fd, FORMAT, 
1649                                         ast_channel_name(chan),
1650                                         jid,
1651                                         resource,
1652                                         ast_getformatname(ast_channel_readformat(chan)),
1653                                         ast_getformatname(ast_channel_writeformat(chan))
1654                                         );
1655                         else 
1656                                 ast_log(LOG_WARNING, "No available channel\n");
1657                         numchans ++;
1658                         p = p->next;
1659                 }
1660                 ASTOBJ_UNLOCK(iterator);
1661         });
1662
1663         ast_mutex_unlock(&jinglelock);
1664
1665         ast_cli(a->fd, "%d active jingle channel%s\n", numchans, (numchans != 1) ? "s" : "");
1666         return CLI_SUCCESS;
1667 #undef FORMAT
1668 }
1669
1670 /*! \brief CLI command "jingle reload" */
1671 static char *jingle_do_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1672 {
1673         switch (cmd) {
1674         case CLI_INIT:
1675                 e->command = "jingle reload";
1676                 e->usage =
1677                         "Usage: jingle reload\n"
1678                         "       Reload jingle channel driver.\n";
1679                 return NULL;
1680         case CLI_GENERATE:
1681                 return NULL;
1682         }       
1683         
1684         return CLI_SUCCESS;
1685 }
1686
1687 static int jingle_parser(void *data, ikspak *pak)
1688 {
1689         struct jingle *client = ASTOBJ_REF((struct jingle *) data);
1690         ast_log(LOG_NOTICE, "Filter matched\n");
1691
1692         if (iks_find_with_attrib(pak->x, JINGLE_NODE, "action", JINGLE_INITIATE)) {
1693                 /* New call */
1694                 jingle_newcall(client, pak);
1695         } else if (iks_find_with_attrib(pak->x, JINGLE_NODE, "action", JINGLE_NEGOTIATE)) {
1696                 ast_debug(3, "About to add candidate!\n");
1697                 jingle_add_candidate(client, pak);
1698                 ast_debug(3, "Candidate Added!\n");
1699         } else if (iks_find_with_attrib(pak->x, JINGLE_NODE, "action", JINGLE_ACCEPT)) {
1700                 jingle_is_answered(client, pak);
1701         } else if (iks_find_with_attrib(pak->x, JINGLE_NODE, "action", JINGLE_INFO)) {
1702                 jingle_handle_dtmf(client, pak);
1703         } else if (iks_find_with_attrib(pak->x, JINGLE_NODE, "action", JINGLE_TERMINATE)) {
1704                 jingle_hangup_farend(client, pak);
1705         } else if (iks_find_with_attrib(pak->x, JINGLE_NODE, "action", "reject")) {
1706                 jingle_hangup_farend(client, pak);
1707         }
1708         ASTOBJ_UNREF(client, jingle_member_destroy);
1709         return IKS_FILTER_EAT;
1710 }
1711 /* Not using this anymore probably take out soon 
1712 static struct jingle_candidate *jingle_create_candidate(char *args)
1713 {
1714         char *name, *type, *preference, *protocol;
1715         struct jingle_candidate *res;
1716         res = ast_calloc(1, sizeof(*res));
1717         if (args)
1718                 name = args;
1719         if ((args = strchr(args, ','))) {
1720                 *args = '\0';
1721                 args++;
1722                 preference = args;
1723         }
1724         if ((args = strchr(args, ','))) {
1725                 *args = '\0';
1726                 args++;
1727                 protocol = args;
1728         }
1729         if ((args = strchr(args, ','))) {
1730                 *args = '\0';
1731                 args++;
1732                 type = args;
1733         }
1734         if (name)
1735                 ast_copy_string(res->name, name, sizeof(res->name));
1736         if (preference) {
1737                 res->preference = atof(preference);
1738         }
1739         if (protocol) {
1740                 if (!strcasecmp("udp", protocol))
1741                         res->protocol = AJI_PROTOCOL_UDP;
1742                 if (!strcasecmp("ssltcp", protocol))
1743                         res->protocol = AJI_PROTOCOL_SSLTCP;
1744         }
1745         if (type) {
1746                 if (!strcasecmp("host", type))
1747                         res->type = AJI_CONNECT_HOST;
1748                 if (!strcasecmp("prflx", type))
1749                         res->type = AJI_CONNECT_PRFLX;
1750                 if (!strcasecmp("relay", type))
1751                         res->type = AJI_CONNECT_RELAY;
1752                 if (!strcasecmp("srflx", type))
1753                         res->type = AJI_CONNECT_SRFLX;
1754         }
1755
1756         return res;
1757 }
1758 */
1759
1760 static int jingle_create_member(char *label, struct ast_variable *var, int allowguest,
1761                                                                 struct ast_codec_pref prefs, char *context,
1762                                                                 struct jingle *member)
1763 {
1764         struct aji_client *client;
1765
1766         if (!member)
1767                 ast_log(LOG_WARNING, "Out of memory.\n");
1768
1769         ast_copy_string(member->name, label, sizeof(member->name));
1770         ast_copy_string(member->user, label, sizeof(member->user));
1771         ast_copy_string(member->context, context, sizeof(member->context));
1772         member->allowguest = allowguest;
1773         member->prefs = prefs;
1774         while (var) {
1775 #if 0
1776                 struct jingle_candidate *candidate = NULL;
1777 #endif
1778                 if (!strcasecmp(var->name, "username"))
1779                         ast_copy_string(member->user, var->value, sizeof(member->user));
1780                 else if (!strcasecmp(var->name, "disallow"))
1781                         ast_parse_allow_disallow(&member->prefs, member->cap, var->value, 0);
1782                 else if (!strcasecmp(var->name, "allow"))
1783                         ast_parse_allow_disallow(&member->prefs, member->cap, var->value, 1);
1784                 else if (!strcasecmp(var->name, "context"))
1785                         ast_copy_string(member->context, var->value, sizeof(member->context));
1786 #if 0
1787                 else if (!strcasecmp(var->name, "candidate")) {
1788                         candidate = jingle_create_candidate(var->value);
1789                         if (candidate) {
1790                                 candidate->next = member->ourcandidates;
1791                                 member->ourcandidates = candidate;
1792                         }
1793                 }
1794 #endif
1795                 else if (!strcasecmp(var->name, "connection")) {
1796                         if ((client = ast_aji_get_client(var->value))) {
1797                                 member->connection = client;
1798                                 iks_filter_add_rule(client->f, jingle_parser, member,
1799                                                     IKS_RULE_TYPE, IKS_PAK_IQ,
1800                                                     IKS_RULE_FROM_PARTIAL, member->user,
1801                                                     IKS_RULE_NS, JINGLE_NS,
1802                                                     IKS_RULE_DONE);
1803                         } else {
1804                                 ast_log(LOG_ERROR, "connection referenced not found!\n");
1805                                 return 0;
1806                         }
1807                 }
1808                 var = var->next;
1809         }
1810         if (member->connection && member->user)
1811                 member->buddy = ASTOBJ_CONTAINER_FIND(&member->connection->buddies, member->user);
1812         else {
1813                 ast_log(LOG_ERROR, "No Connection or Username!\n");
1814         }
1815         return 1;
1816 }
1817
1818 static int jingle_load_config(void)
1819 {
1820         char *cat = NULL;
1821         struct ast_config *cfg = NULL;
1822         char context[100];
1823         int allowguest = 1;
1824         struct ast_variable *var;
1825         struct jingle *member;
1826         struct hostent *hp;
1827         struct ast_hostent ahp;
1828         struct ast_codec_pref prefs;
1829         struct aji_client_container *clients;
1830         struct jingle_candidate *global_candidates = NULL;
1831         struct ast_flags config_flags = { 0 };
1832
1833         cfg = ast_config_load(JINGLE_CONFIG, config_flags);
1834         if (!cfg || cfg == CONFIG_STATUS_FILEINVALID) {
1835                 return 0;
1836         }
1837
1838         /* Copy the default jb config over global_jbconf */
1839         memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
1840
1841         cat = ast_category_browse(cfg, NULL);
1842         for (var = ast_variable_browse(cfg, "general"); var; var = var->next) {
1843                 /* handle jb conf */
1844                 if (!ast_jb_read_conf(&global_jbconf, var->name, var->value))
1845                         continue;
1846
1847                 if (!strcasecmp(var->name, "allowguest"))
1848                         allowguest =
1849                                 (ast_true(ast_variable_retrieve(cfg, "general", "allowguest"))) ? 1 : 0;
1850                 else if (!strcasecmp(var->name, "disallow"))
1851                         ast_parse_allow_disallow(&prefs, global_capability, var->value, 0);
1852                 else if (!strcasecmp(var->name, "allow"))
1853                         ast_parse_allow_disallow(&prefs, global_capability, var->value, 1);
1854                 else if (!strcasecmp(var->name, "context"))
1855                         ast_copy_string(context, var->value, sizeof(context));
1856                 else if (!strcasecmp(var->name, "externip"))
1857                         ast_copy_string(externip, var->value, sizeof(externip));
1858                 else if (!strcasecmp(var->name, "bindaddr")) {
1859                         if (!(hp = ast_gethostbyname(var->value, &ahp))) {
1860                                 ast_log(LOG_WARNING, "Invalid address: %s\n", var->value);
1861                         } else {
1862                                 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
1863                         }
1864                 }
1865 /*  Idea to allow for custom candidates  */
1866 /*
1867                 else if (!strcasecmp(var->name, "candidate")) {
1868                         candidate = jingle_create_candidate(var->value);
1869                         if (candidate) {
1870                                 candidate->next = global_candidates;
1871                                 global_candidates = candidate;
1872                         }
1873                 }
1874 */
1875         }
1876         while (cat) {
1877                 if (strcasecmp(cat, "general")) {
1878                         var = ast_variable_browse(cfg, cat);
1879                         member = ast_calloc(1, sizeof(*member));
1880                         ASTOBJ_INIT(member);
1881                         ASTOBJ_WRLOCK(member);
1882                         member->cap = ast_format_cap_alloc_nolock();
1883                         if (!strcasecmp(cat, "guest")) {
1884                                 ast_copy_string(member->name, "guest", sizeof(member->name));
1885                                 ast_copy_string(member->user, "guest", sizeof(member->user));
1886                                 ast_copy_string(member->context, context, sizeof(member->context));
1887                                 member->allowguest = allowguest;
1888                                 member->prefs = prefs;
1889                                 while (var) {
1890                                         if (!strcasecmp(var->name, "disallow"))
1891                                                 ast_parse_allow_disallow(&member->prefs, member->cap,
1892                                                                                                  var->value, 0);
1893                                         else if (!strcasecmp(var->name, "allow"))
1894                                                 ast_parse_allow_disallow(&member->prefs, member->cap,
1895                                                                                                  var->value, 1);
1896                                         else if (!strcasecmp(var->name, "context"))
1897                                                 ast_copy_string(member->context, var->value,
1898                                                                                 sizeof(member->context));
1899                                         else if (!strcasecmp(var->name, "parkinglot"))
1900                                                 ast_copy_string(member->parkinglot, var->value,
1901                                                                                 sizeof(member->parkinglot));
1902 /*  Idea to allow for custom candidates  */
1903 /*
1904                                         else if (!strcasecmp(var->name, "candidate")) {
1905                                                 candidate = jingle_create_candidate(var->value);
1906                                                 if (candidate) {
1907                                                         candidate->next = member->ourcandidates;
1908                                                         member->ourcandidates = candidate;
1909                                                 }
1910                                         }
1911 */
1912                                         var = var->next;
1913                                 }
1914                                 ASTOBJ_UNLOCK(member);
1915                                 clients = ast_aji_get_clients();
1916                                 if (clients) {
1917                                         ASTOBJ_CONTAINER_TRAVERSE(clients, 1, {
1918                                                 ASTOBJ_WRLOCK(iterator);
1919                                                 ASTOBJ_WRLOCK(member);
1920                                                 if (member->connection) {
1921                                                         ASTOBJ_UNREF(member->connection, ast_aji_client_destroy);
1922                                                 }
1923                                                 member->connection = NULL;
1924                                                 iks_filter_add_rule(iterator->f, jingle_parser, member, IKS_RULE_TYPE, IKS_PAK_IQ, IKS_RULE_NS, JINGLE_NS, IKS_RULE_DONE);
1925                                                 iks_filter_add_rule(iterator->f, jingle_parser, member, IKS_RULE_TYPE, IKS_PAK_IQ, IKS_RULE_NS, JINGLE_DTMF_NS, IKS_RULE_DONE);
1926                                                 ASTOBJ_UNLOCK(member);
1927                                                 ASTOBJ_UNLOCK(iterator);
1928                                         });
1929                                         ASTOBJ_CONTAINER_LINK(&jingle_list, member);
1930                                 } else {
1931                                         ASTOBJ_UNLOCK(member);
1932                                         ASTOBJ_UNREF(member, jingle_member_destroy);
1933                                 }
1934                         } else {
1935                                 ASTOBJ_UNLOCK(member);
1936                                 if (jingle_create_member(cat, var, allowguest, prefs, context, member))
1937                                         ASTOBJ_CONTAINER_LINK(&jingle_list, member);
1938                                 ASTOBJ_UNREF(member, jingle_member_destroy);
1939                         }
1940                 }
1941                 cat = ast_category_browse(cfg, cat);
1942         }
1943         ast_config_destroy(cfg);
1944         jingle_free_candidates(global_candidates);
1945         return 1;
1946 }
1947
1948 /*!
1949  * \brief Load the module
1950  *
1951  * Module loading including tests for configuration or dependencies.
1952  * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
1953  * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
1954  * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the 
1955  * configuration file or other non-critical problem return 
1956  * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
1957  */
1958 static int load_module(void)
1959 {
1960         struct ast_sockaddr ourip_tmp;
1961         struct ast_sockaddr bindaddr_tmp;
1962         struct ast_format tmpfmt;
1963
1964         char *jabber_loaded = ast_module_helper("", "res_jabber.so", 0, 0, 0, 0);
1965
1966         if (!(jingle_tech.capabilities = ast_format_cap_alloc())) {
1967                 return AST_MODULE_LOAD_DECLINE;
1968         }
1969
1970         ast_format_cap_add_all_by_type(jingle_tech.capabilities, AST_FORMAT_TYPE_AUDIO);
1971         if (!(global_capability = ast_format_cap_alloc())) {
1972                 return AST_MODULE_LOAD_DECLINE;
1973         }
1974         ast_format_cap_add(global_capability, ast_format_set(&tmpfmt, AST_FORMAT_ULAW, 0));
1975         ast_format_cap_add(global_capability, ast_format_set(&tmpfmt, AST_FORMAT_GSM, 0));
1976         ast_format_cap_add(global_capability, ast_format_set(&tmpfmt, AST_FORMAT_ALAW, 0));
1977         ast_format_cap_add(global_capability, ast_format_set(&tmpfmt, AST_FORMAT_H263, 0));
1978
1979         free(jabber_loaded);
1980         if (!jabber_loaded) {
1981                 /* Dependency module has a different name, if embedded */
1982                 jabber_loaded = ast_module_helper("", "res_jabber", 0, 0, 0, 0);
1983                 free(jabber_loaded);
1984                 if (!jabber_loaded) {
1985                         ast_log(LOG_ERROR, "chan_jingle.so depends upon res_jabber.so\n");
1986                         return AST_MODULE_LOAD_DECLINE;
1987                 }
1988         }
1989
1990         ASTOBJ_CONTAINER_INIT(&jingle_list);
1991         if (!jingle_load_config()) {
1992                 ast_log(LOG_ERROR, "Unable to read config file %s. Not loading module.\n", JINGLE_CONFIG);
1993                 return AST_MODULE_LOAD_DECLINE;
1994         }
1995
1996         sched = ast_sched_context_create();
1997         if (!sched) {
1998                 ast_log(LOG_WARNING, "Unable to create schedule context\n");
1999         }
2000
2001         io = io_context_create();
2002         if (!io) {
2003                 ast_log(LOG_WARNING, "Unable to create I/O context\n");
2004         }
2005
2006         ast_sockaddr_from_sin(&bindaddr_tmp, &bindaddr);
2007         if (ast_find_ourip(&ourip_tmp, &bindaddr_tmp, AF_INET)) {
2008                 ast_log(LOG_WARNING, "Unable to get own IP address, Jingle disabled\n");
2009                 return 0;
2010         }
2011         __ourip.s_addr = htonl(ast_sockaddr_ipv4(&ourip_tmp));
2012
2013         ast_rtp_glue_register(&jingle_rtp_glue);
2014         ast_cli_register_multiple(jingle_cli, ARRAY_LEN(jingle_cli));
2015         /* Make sure we can register our channel type */
2016         if (ast_channel_register(&jingle_tech)) {
2017                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", channel_type);
2018                 return -1;
2019         }
2020         return 0;
2021 }
2022
2023 /*! \brief Reload module */
2024 static int reload(void)
2025 {
2026         return 0;
2027 }
2028
2029 /*! \brief Unload the jingle channel from Asterisk */
2030 static int unload_module(void)
2031 {
2032         struct jingle_pvt *privates = NULL;
2033         ast_cli_unregister_multiple(jingle_cli, ARRAY_LEN(jingle_cli));
2034         /* First, take us out of the channel loop */
2035         ast_channel_unregister(&jingle_tech);
2036         ast_rtp_glue_unregister(&jingle_rtp_glue);
2037
2038         if (!ast_mutex_lock(&jinglelock)) {
2039                 /* Hangup all interfaces if they have an owner */
2040                 ASTOBJ_CONTAINER_TRAVERSE(&jingle_list, 1, {
2041                         ASTOBJ_WRLOCK(iterator);
2042                         privates = iterator->p;
2043                         while(privates) {
2044                                 if (privates->owner)
2045                                         ast_softhangup(privates->owner, AST_SOFTHANGUP_APPUNLOAD);
2046                                 privates = privates->next;
2047                         }
2048                         iterator->p = NULL;
2049                         ASTOBJ_UNLOCK(iterator);
2050                 });
2051                 ast_mutex_unlock(&jinglelock);
2052         } else {
2053                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
2054                 return -1;
2055         }
2056         ASTOBJ_CONTAINER_DESTROYALL(&jingle_list, jingle_member_destroy);
2057         ASTOBJ_CONTAINER_DESTROY(&jingle_list);
2058
2059         global_capability = ast_format_cap_destroy(global_capability);
2060         return 0;
2061 }
2062
2063 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Jingle Channel Driver",
2064                 .load = load_module,
2065                 .unload = unload_module,
2066                 .reload = reload,
2067                 .load_pri = AST_MODPRI_CHANNEL_DRIVER,
2068                );