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