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