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