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