Merged revisions 87906 via svnmerge from
[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         AST_CLI_DEFINE(jingle_do_reload, "Reload Jingle configuration"),
240         AST_CLI_DEFINE(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
1068         for (tmp = client->p; tmp; tmp = tmp->next) {
1069                 if (iks_find_with_attrib(pak->x, JINGLE_NODE, JINGLE_SID, tmp->sid)) {
1070                         p = tmp;
1071                         break;
1072                 }
1073         }
1074
1075         if (!p)
1076                 return -1;
1077
1078         traversenodes = pak->query;
1079         while(traversenodes) {
1080                 if(!strcasecmp(iks_name(traversenodes), "jingle")) {
1081                         traversenodes = iks_child(traversenodes);
1082                         continue;
1083                 }
1084                 if(!strcasecmp(iks_name(traversenodes), "content")) {
1085                         traversenodes = iks_child(traversenodes);
1086                         continue;
1087                 }
1088                 if(!strcasecmp(iks_name(traversenodes), "transport")) {
1089                         traversenodes = iks_child(traversenodes);
1090                         continue;
1091                 }
1092
1093                 if(!strcasecmp(iks_name(traversenodes), "candidate")) {
1094                         newcandidate = ast_calloc(1, sizeof(*newcandidate));
1095                         if (!newcandidate)
1096                                 return 0;
1097                         ast_copy_string(newcandidate->ip, iks_find_attrib(traversenodes, "ip"), sizeof(newcandidate->ip));
1098                         newcandidate->port = atoi(iks_find_attrib(traversenodes, "port"));
1099                         ast_copy_string(newcandidate->password, iks_find_attrib(traversenodes, "pwd"), sizeof(newcandidate->password));
1100                         if (!strcasecmp(iks_find_attrib(traversenodes, "protocol"), "udp"))
1101                                 newcandidate->protocol = AJI_PROTOCOL_UDP;
1102                         else if (!strcasecmp(iks_find_attrib(traversenodes, "protocol"), "ssltcp"))
1103                                 newcandidate->protocol = AJI_PROTOCOL_SSLTCP;
1104                         
1105                         if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "host"))
1106                                 newcandidate->type = AJI_CONNECT_HOST;
1107                         else if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "prflx"))
1108                                 newcandidate->type = AJI_CONNECT_PRFLX;
1109                         else if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "relay"))
1110                                 newcandidate->type = AJI_CONNECT_RELAY;
1111                         else if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "srflx"))
1112                                 newcandidate->type = AJI_CONNECT_SRFLX;
1113
1114                         newcandidate->network = atoi(iks_find_attrib(traversenodes, "network"));
1115                         newcandidate->generation = atoi(iks_find_attrib(traversenodes, "generation"));
1116                         newcandidate->next = NULL;
1117                 
1118                         newcandidate->next = p->theircandidates;
1119                         p->theircandidates = newcandidate;
1120                         p->laststun = 0;
1121                         jingle_update_stun(p->parent, p);
1122                         newcandidate = NULL;
1123                 }
1124                 traversenodes = iks_next(traversenodes);
1125         }
1126         
1127         receipt = iks_new("iq");
1128         iks_insert_attrib(receipt, "type", "result");
1129         iks_insert_attrib(receipt, "from", c->jid->full);
1130         iks_insert_attrib(receipt, "to", iks_find_attrib(pak->x, "from"));
1131         iks_insert_attrib(receipt, "id", iks_find_attrib(pak->x, "id"));
1132         iks_send(c->p, receipt);
1133         iks_delete(receipt);
1134
1135         return 1;
1136 }
1137
1138 static struct ast_frame *jingle_rtp_read(struct ast_channel *ast, struct jingle_pvt *p)
1139 {
1140         struct ast_frame *f;
1141
1142         if (!p->rtp)
1143                 return &ast_null_frame;
1144         f = ast_rtp_read(p->rtp);
1145         jingle_update_stun(p->parent, p);
1146         if (p->owner) {
1147                 /* We already hold the channel lock */
1148                 if (f->frametype == AST_FRAME_VOICE) {
1149                         if (f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
1150                                 ast_debug(1, "Oooh, format changed to %d\n", f->subclass);
1151                                 p->owner->nativeformats =
1152                                         (p->owner->nativeformats & AST_FORMAT_VIDEO_MASK) | f->subclass;
1153                                 ast_set_read_format(p->owner, p->owner->readformat);
1154                                 ast_set_write_format(p->owner, p->owner->writeformat);
1155                         }
1156 /*                      if ((ast_test_flag(p, SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
1157                                 f = ast_dsp_process(p->owner, p->vad, f);
1158                                 if (f && (f->frametype == AST_FRAME_DTMF))
1159                                         ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass);
1160                         } */
1161                 }
1162         }
1163         return f;
1164 }
1165
1166 static struct ast_frame *jingle_read(struct ast_channel *ast)
1167 {
1168         struct ast_frame *fr;
1169         struct jingle_pvt *p = ast->tech_pvt;
1170
1171         ast_mutex_lock(&p->lock);
1172         fr = jingle_rtp_read(ast, p);
1173         ast_mutex_unlock(&p->lock);
1174         return fr;
1175 }
1176
1177 /*! \brief Send frame to media channel (rtp) */
1178 static int jingle_write(struct ast_channel *ast, struct ast_frame *frame)
1179 {
1180         struct jingle_pvt *p = ast->tech_pvt;
1181         int res = 0;
1182
1183         switch (frame->frametype) {
1184         case AST_FRAME_VOICE:
1185                 if (!(frame->subclass & ast->nativeformats)) {
1186                         ast_log(LOG_WARNING,
1187                                         "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
1188                                         frame->subclass, ast->nativeformats, ast->readformat,
1189                                         ast->writeformat);
1190                         return 0;
1191                 }
1192                 if (p) {
1193                         ast_mutex_lock(&p->lock);
1194                         if (p->rtp) {
1195                                 res = ast_rtp_write(p->rtp, frame);
1196                         }
1197                         ast_mutex_unlock(&p->lock);
1198                 }
1199                 break;
1200         case AST_FRAME_VIDEO:
1201                 if (p) {
1202                         ast_mutex_lock(&p->lock);
1203                         if (p->vrtp) {
1204                                 res = ast_rtp_write(p->vrtp, frame);
1205                         }
1206                         ast_mutex_unlock(&p->lock);
1207                 }
1208                 break;
1209         case AST_FRAME_IMAGE:
1210                 return 0;
1211                 break;
1212         default:
1213                 ast_log(LOG_WARNING, "Can't send %d type frames with Jingle write\n",
1214                                 frame->frametype);
1215                 return 0;
1216         }
1217
1218         return res;
1219 }
1220
1221 static int jingle_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1222 {
1223         struct jingle_pvt *p = newchan->tech_pvt;
1224         ast_mutex_lock(&p->lock);
1225
1226         if ((p->owner != oldchan)) {
1227                 ast_mutex_unlock(&p->lock);
1228                 return -1;
1229         }
1230         if (p->owner == oldchan)
1231                 p->owner = newchan;
1232         ast_mutex_unlock(&p->lock);
1233         return 0;
1234 }
1235
1236 static int jingle_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
1237 {
1238         int res = 0;
1239
1240         switch (condition) {
1241         case AST_CONTROL_HOLD:
1242                 ast_moh_start(ast, data, NULL);
1243                 break;
1244         case AST_CONTROL_UNHOLD:
1245                 ast_moh_stop(ast);
1246                 break;
1247         default:
1248                 ast_log(LOG_NOTICE, "Don't know how to indicate condition '%d'\n", condition);
1249                 res = -1;
1250         }
1251
1252         return res;
1253 }
1254
1255 static int jingle_digit(struct ast_channel *ast, char digit, unsigned int duration)
1256 {
1257         struct jingle_pvt *p = ast->tech_pvt;
1258         struct jingle *client = p->parent;
1259         iks *iq, *jingle, *dtmf;
1260         char buffer[2] = {digit, '\0'};
1261         iq = iks_new("iq");
1262         jingle = iks_new("jingle");
1263         dtmf = iks_new("dtmf");
1264         if(!iq || !jingle || !dtmf) {
1265                 if(iq)
1266                         iks_delete(iq);
1267                 if(jingle)
1268                         iks_delete(jingle);
1269                 if(dtmf)
1270                         iks_delete(dtmf);
1271                 ast_log(LOG_ERROR, "Did not send dtmf do to memory issue\n");
1272                 return -1;
1273         }
1274
1275         iks_insert_attrib(iq, "type", "set");
1276         iks_insert_attrib(iq, "to", p->them);
1277         iks_insert_attrib(iq, "from", client->connection->jid->full);
1278         iks_insert_attrib(iq, "id", client->connection->mid);
1279         ast_aji_increment_mid(client->connection->mid);
1280         iks_insert_attrib(jingle, "xmlns", JINGLE_NS);
1281         iks_insert_attrib(jingle, "action", "session-info");
1282         iks_insert_attrib(jingle, "initiator", p->initiator ? client->connection->jid->full : p->them);
1283         iks_insert_attrib(jingle, "sid", p->sid);
1284         iks_insert_attrib(dtmf, "xmlns", JINGLE_DTMF_NS);
1285         iks_insert_attrib(dtmf, "code", buffer);
1286         iks_insert_node(iq, jingle);
1287         iks_insert_node(jingle, dtmf);
1288
1289         ast_mutex_lock(&p->lock);
1290         if (ast->dtmff.frametype == AST_FRAME_DTMF_BEGIN || duration == 0) {
1291                 iks_insert_attrib(dtmf, "action", "button-down");
1292         } else if (ast->dtmff.frametype == AST_FRAME_DTMF_END || duration != 0) {
1293                 iks_insert_attrib(dtmf, "action", "button-up");
1294         }
1295         iks_send(client->connection->p, iq);
1296         iks_delete(iq);
1297         iks_delete(jingle);
1298         iks_delete(dtmf);
1299         ast_mutex_unlock(&p->lock);
1300         return 0;
1301 }
1302
1303 static int jingle_digit_begin(struct ast_channel *chan, char digit)
1304 {
1305         return jingle_digit(chan, digit, 0);
1306 }
1307
1308 static int jingle_digit_end(struct ast_channel *ast, char digit, unsigned int duration)
1309 {
1310         return jingle_digit(ast, digit, duration);
1311 }
1312
1313 static int jingle_sendhtml(struct ast_channel *ast, int subclass, const char *data, int datalen)
1314 {
1315         ast_log(LOG_NOTICE, "XXX Implement jingle sendhtml XXX\n");
1316
1317         return -1;
1318 }
1319 static int jingle_transmit_invite(struct jingle_pvt *p)
1320 {
1321         struct jingle *aux = NULL;
1322         struct aji_client *client = NULL;
1323         iks *iq, *jingle, *content, *description, *transport;
1324         iks *payload_eg711u, *payload_pcmu;
1325
1326         aux = p->parent;
1327         client = aux->connection;
1328         iq = iks_new("iq");
1329         jingle = iks_new(JINGLE_NODE);
1330         content = iks_new("content");
1331         description = iks_new("description");
1332         transport = iks_new("transport");
1333         payload_pcmu = iks_new("payload-type");
1334         payload_eg711u = iks_new("payload-type");
1335
1336         iks_insert_attrib(iq, "type", "set");
1337         iks_insert_attrib(iq, "to", p->them);
1338         iks_insert_attrib(iq, "from", client->jid->full);
1339         iks_insert_attrib(iq, "id", client->mid);
1340         ast_aji_increment_mid(client->mid);
1341         iks_insert_attrib(jingle, "action", JINGLE_INITIATE);
1342         iks_insert_attrib(jingle, JINGLE_SID, p->sid);
1343         iks_insert_attrib(jingle, "initiator", client->jid->full);
1344         iks_insert_attrib(jingle, "xmlns", JINGLE_NS);
1345         iks_insert_attrib(content, "creator", "initiator");
1346         iks_insert_attrib(content, "name", "asterisk-audio-content");
1347         iks_insert_attrib(content, "profile", "RTP/AVP");
1348         iks_insert_attrib(description, "xmlns", JINGLE_AUDIO_RTP_NS);
1349         iks_insert_attrib(transport, "xmlns", JINGLE_ICE_UDP_NS);
1350         iks_insert_attrib(payload_pcmu, "id", "0");
1351         iks_insert_attrib(payload_pcmu, "name", "PCMU");
1352         iks_insert_attrib(payload_eg711u, "id", "100");
1353         iks_insert_attrib(payload_eg711u, "name", "EG711U");
1354
1355         iks_insert_node(description, payload_pcmu);
1356         iks_insert_node(description, payload_eg711u);
1357         iks_insert_node(content, description);
1358         iks_insert_node(content, transport);
1359         iks_insert_node(jingle, content);
1360         iks_insert_node(iq, jingle);
1361
1362         iks_send(client->p, iq);
1363
1364         iks_delete(iq);
1365         iks_delete(jingle);
1366         iks_delete(content);
1367         iks_delete(description);
1368         iks_delete(transport);
1369         iks_delete(payload_eg711u);
1370         iks_delete(payload_pcmu);
1371         return 0;
1372 }
1373
1374 /* Not in use right now.
1375 static int jingle_auto_congest(void *nothing)
1376 {
1377         struct jingle_pvt *p = nothing;
1378
1379         ast_mutex_lock(&p->lock);
1380         if (p->owner) {
1381                 if (!ast_channel_trylock(p->owner)) {
1382                         ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
1383                         ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
1384                         ast_channel_unlock(p->owner);
1385                 }
1386         }
1387         ast_mutex_unlock(&p->lock);
1388         return 0;
1389 }
1390 */
1391
1392 /*! \brief Initiate new call, part of PBX interface 
1393  *      dest is the dial string */
1394 static int jingle_call(struct ast_channel *ast, char *dest, int timeout)
1395 {
1396         struct jingle_pvt *p = ast->tech_pvt;
1397
1398         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
1399                 ast_log(LOG_WARNING, "jingle_call called on %s, neither down nor reserved\n", ast->name);
1400                 return -1;
1401         }
1402
1403         ast_setstate(ast, AST_STATE_RING);
1404         p->jointcapability = p->capability;
1405         if (!p->ringrule) {
1406                 ast_copy_string(p->ring, p->parent->connection->mid, sizeof(p->ring));
1407                 p->ringrule = iks_filter_add_rule(p->parent->connection->f, jingle_ringing_ack, p,
1408                                                         IKS_RULE_ID, p->ring, IKS_RULE_DONE);
1409         } else
1410                 ast_log(LOG_WARNING, "Whoa, already have a ring rule!\n");
1411
1412         jingle_transmit_invite(p);
1413         jingle_create_candidates(p->parent, p, p->sid, p->them);
1414
1415         return 0;
1416 }
1417
1418 /*! \brief Hangup a call through the jingle proxy channel */
1419 static int jingle_hangup(struct ast_channel *ast)
1420 {
1421         struct jingle_pvt *p = ast->tech_pvt;
1422         struct jingle *client;
1423
1424         ast_mutex_lock(&p->lock);
1425         client = p->parent;
1426         p->owner = NULL;
1427         ast->tech_pvt = NULL;
1428         if (!p->alreadygone)
1429                 jingle_action(client, p, JINGLE_TERMINATE);
1430         ast_mutex_unlock(&p->lock);
1431
1432         jingle_free_pvt(client, p);
1433
1434         return 0;
1435 }
1436
1437 /*! \brief Part of PBX interface */
1438 static struct ast_channel *jingle_request(const char *type, int format, void *data, int *cause)
1439 {
1440         struct jingle_pvt *p = NULL;
1441         struct jingle *client = NULL;
1442         char *sender = NULL, *to = NULL, *s = NULL;
1443         struct ast_channel *chan = NULL;
1444
1445         if (data) {
1446                 s = ast_strdupa(data);
1447                 if (s) {
1448                         sender = strsep(&s, "/");
1449                         if (sender && (sender[0] != '\0'))
1450                                 to = strsep(&s, "/");
1451                         if (!to) {
1452                                 ast_log(LOG_ERROR, "Bad arguments in Jingle Dialstring: %s\n", (char*) data);
1453                                 return NULL;
1454                         }
1455                 }
1456         }
1457         client = find_jingle(to, sender);
1458         if (!client) {
1459                 ast_log(LOG_WARNING, "Could not find recipient.\n");
1460                 return NULL;
1461         }
1462         ASTOBJ_WRLOCK(client);
1463         p = jingle_alloc(client, to, NULL);
1464         if (p)
1465                 chan = jingle_new(client, p, AST_STATE_DOWN, to);
1466         ASTOBJ_UNLOCK(client);
1467
1468         return chan;
1469 }
1470
1471 /*! \brief CLI command "jingle show channels" */
1472 static char *jingle_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1473 {
1474 #define FORMAT  "%-30.30s  %-30.30s  %-15.15s  %-5.5s %-5.5s \n"
1475         struct jingle_pvt *p;
1476         struct ast_channel *chan;
1477         int numchans = 0;
1478         char them[AJI_MAX_JIDLEN];
1479         char *jid = NULL;
1480         char *resource = NULL;
1481
1482         switch (cmd) {
1483         case CLI_INIT:
1484                 e->command = "jingle show channels";
1485                 e->usage =
1486                         "Usage: jingle show channels\n"
1487                         "       Shows current state of the Jingle channels.\n";
1488                 return NULL;
1489         case CLI_GENERATE:
1490                 return NULL;
1491         }
1492
1493         if (a->argc != 3)
1494                 return CLI_SHOWUSAGE;
1495
1496         ast_mutex_lock(&jinglelock);
1497         ast_cli(a->fd, FORMAT, "Channel", "Jabber ID", "Resource", "Read", "Write");
1498         ASTOBJ_CONTAINER_TRAVERSE(&jingle_list, 1, {
1499                 ASTOBJ_WRLOCK(iterator);
1500                 p = iterator->p;
1501                 while(p) {
1502                         chan = p->owner;
1503                         ast_copy_string(them, p->them, sizeof(them));
1504                         jid = them;
1505                         resource = strchr(them, '/');
1506                         if (!resource)
1507                                 resource = "None";
1508                         else {
1509                                 *resource = '\0';
1510                                 resource ++;
1511                         }
1512                         if (chan)
1513                                 ast_cli(a->fd, FORMAT, 
1514                                         chan->name,
1515                                         jid,
1516                                         resource,
1517                                         ast_getformatname(chan->readformat),
1518                                         ast_getformatname(chan->writeformat)                                    
1519                                         );
1520                         else 
1521                                 ast_log(LOG_WARNING, "No available channel\n");
1522                         numchans ++;
1523                         p = p->next;
1524                 }
1525                 ASTOBJ_UNLOCK(iterator);
1526         });
1527
1528         ast_mutex_unlock(&jinglelock);
1529
1530         ast_cli(a->fd, "%d active jingle channel%s\n", numchans, (numchans != 1) ? "s" : "");
1531         return CLI_SUCCESS;
1532 #undef FORMAT
1533 }
1534
1535 /*! \brief CLI command "jingle reload" */
1536 static char *jingle_do_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1537 {
1538         switch (cmd) {
1539         case CLI_INIT:
1540                 e->command = "jingle reload";
1541                 e->usage =
1542                         "Usage: jingle reload\n"
1543                         "       Reload jingle channel driver.\n";
1544                 return NULL;
1545         case CLI_GENERATE:
1546                 return NULL;
1547         }       
1548         
1549         return CLI_SUCCESS;
1550 }
1551
1552 static int jingle_parser(void *data, ikspak *pak)
1553 {
1554         struct jingle *client = ASTOBJ_REF((struct jingle *) data);
1555         ast_log(LOG_NOTICE, "Filter matched\n");
1556
1557         if (iks_find_with_attrib(pak->x, JINGLE_NODE, "action", JINGLE_INITIATE)) {
1558                 /* New call */
1559                 jingle_newcall(client, pak);
1560         } else if (iks_find_with_attrib(pak->x, JINGLE_NODE, "action", JINGLE_NEGOTIATE)) {
1561                 ast_debug(3, "About to add candidate!\n");
1562                 jingle_add_candidate(client, pak);
1563                 ast_debug(3, "Candidate Added!\n");
1564         } else if (iks_find_with_attrib(pak->x, JINGLE_NODE, "action", JINGLE_ACCEPT)) {
1565                 jingle_is_answered(client, pak);
1566         } else if (iks_find_with_attrib(pak->x, JINGLE_NODE, "action", JINGLE_INFO)) {
1567                 jingle_handle_dtmf(client, pak);
1568         } else if (iks_find_with_attrib(pak->x, JINGLE_NODE, "action", JINGLE_TERMINATE)) {
1569                 jingle_hangup_farend(client, pak);
1570         } else if (iks_find_with_attrib(pak->x, JINGLE_NODE, "action", "reject")) {
1571                 jingle_hangup_farend(client, pak);
1572         }
1573         ASTOBJ_UNREF(client, jingle_member_destroy);
1574         return IKS_FILTER_EAT;
1575 }
1576 /* Not using this anymore probably take out soon 
1577 static struct jingle_candidate *jingle_create_candidate(char *args)
1578 {
1579         char *name, *type, *preference, *protocol;
1580         struct jingle_candidate *res;
1581         res = ast_calloc(1, sizeof(*res));
1582         if (args)
1583                 name = args;
1584         if ((args = strchr(args, ','))) {
1585                 *args = '\0';
1586                 args++;
1587                 preference = args;
1588         }
1589         if ((args = strchr(args, ','))) {
1590                 *args = '\0';
1591                 args++;
1592                 protocol = args;
1593         }
1594         if ((args = strchr(args, ','))) {
1595                 *args = '\0';
1596                 args++;
1597                 type = args;
1598         }
1599         if (name)
1600                 ast_copy_string(res->name, name, sizeof(res->name));
1601         if (preference) {
1602                 res->preference = atof(preference);
1603         }
1604         if (protocol) {
1605                 if (!strcasecmp("udp", protocol))
1606                         res->protocol = AJI_PROTOCOL_UDP;
1607                 if (!strcasecmp("ssltcp", protocol))
1608                         res->protocol = AJI_PROTOCOL_SSLTCP;
1609         }
1610         if (type) {
1611                 if (!strcasecmp("host", type))
1612                         res->type = AJI_CONNECT_HOST;
1613                 if (!strcasecmp("prflx", type))
1614                         res->type = AJI_CONNECT_PRFLX;
1615                 if (!strcasecmp("relay", type))
1616                         res->type = AJI_CONNECT_RELAY;
1617                 if (!strcasecmp("srflx", type))
1618                         res->type = AJI_CONNECT_SRFLX;
1619         }
1620
1621         return res;
1622 }
1623 */
1624
1625 static int jingle_create_member(char *label, struct ast_variable *var, int allowguest,
1626                                                                 struct ast_codec_pref prefs, char *context,
1627                                                                 struct jingle *member)
1628 {
1629         struct aji_client *client;
1630
1631         if (!member)
1632                 ast_log(LOG_WARNING, "Out of memory.\n");
1633
1634         ast_copy_string(member->name, label, sizeof(member->name));
1635         ast_copy_string(member->user, label, sizeof(member->user));
1636         ast_copy_string(member->context, context, sizeof(member->context));
1637         member->allowguest = allowguest;
1638         member->prefs = prefs;
1639         while (var) {
1640 #if 0
1641                 struct jingle_candidate *candidate = NULL;
1642 #endif
1643                 if (!strcasecmp(var->name, "username"))
1644                         ast_copy_string(member->user, var->value, sizeof(member->user));
1645                 else if (!strcasecmp(var->name, "disallow"))
1646                         ast_parse_allow_disallow(&member->prefs, &member->capability, var->value, 0);
1647                 else if (!strcasecmp(var->name, "allow"))
1648                         ast_parse_allow_disallow(&member->prefs, &member->capability, var->value, 1);
1649                 else if (!strcasecmp(var->name, "context"))
1650                         ast_copy_string(member->context, var->value, sizeof(member->context));
1651 #if 0
1652                 else if (!strcasecmp(var->name, "candidate")) {
1653                         candidate = jingle_create_candidate(var->value);
1654                         if (candidate) {
1655                                 candidate->next = member->ourcandidates;
1656                                 member->ourcandidates = candidate;
1657                         }
1658                 }
1659 #endif
1660                 else if (!strcasecmp(var->name, "connection")) {
1661                         if ((client = ast_aji_get_client(var->value))) {
1662                                 member->connection = client;
1663                                 iks_filter_add_rule(client->f, jingle_parser, member,
1664                                                     IKS_RULE_TYPE, IKS_PAK_IQ,
1665                                                     IKS_RULE_FROM_PARTIAL, member->user,
1666                                                     IKS_RULE_NS, JINGLE_NS,
1667                                                     IKS_RULE_DONE);
1668                         } else {
1669                                 ast_log(LOG_ERROR, "connection referenced not found!\n");
1670                                 return 0;
1671                         }
1672                 }
1673                 var = var->next;
1674         }
1675         if (member->connection && member->user)
1676                 member->buddy = ASTOBJ_CONTAINER_FIND(&member->connection->buddies, member->user);
1677         else {
1678                 ast_log(LOG_ERROR, "No Connection or Username!\n");
1679         }
1680         return 1;
1681 }
1682
1683 static int jingle_load_config(void)
1684 {
1685         char *cat = NULL;
1686         struct ast_config *cfg = NULL;
1687         char context[100];
1688         int allowguest = 1;
1689         struct ast_variable *var;
1690         struct jingle *member;
1691         struct hostent *hp;
1692         struct ast_hostent ahp;
1693         struct ast_codec_pref prefs;
1694         struct aji_client_container *clients;
1695         struct jingle_candidate *global_candidates = NULL;
1696         struct ast_flags config_flags = { 0 };
1697
1698         cfg = ast_config_load(JINGLE_CONFIG, config_flags);
1699         if (!cfg)
1700                 return 0;
1701
1702         /* Copy the default jb config over global_jbconf */
1703         memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
1704
1705         cat = ast_category_browse(cfg, NULL);
1706         for (var = ast_variable_browse(cfg, "general"); var; var = var->next) {
1707                 /* handle jb conf */
1708                 if (!ast_jb_read_conf(&global_jbconf, var->name, var->value))
1709                         continue;
1710
1711                 if (!strcasecmp(var->name, "allowguest"))
1712                         allowguest =
1713                                 (ast_true(ast_variable_retrieve(cfg, "general", "allowguest"))) ? 1 : 0;
1714                 else if (!strcasecmp(var->name, "disallow"))
1715                         ast_parse_allow_disallow(&prefs, &global_capability, var->value, 0);
1716                 else if (!strcasecmp(var->name, "allow"))
1717                         ast_parse_allow_disallow(&prefs, &global_capability, var->value, 1);
1718                 else if (!strcasecmp(var->name, "context"))
1719                         ast_copy_string(context, var->value, sizeof(context));
1720                 else if (!strcasecmp(var->name, "externip"))
1721                         ast_copy_string(externip, var->value, sizeof(externip));
1722                 else if (!strcasecmp(var->name, "bindaddr")) {
1723                         if (!(hp = ast_gethostbyname(var->value, &ahp))) {
1724                                 ast_log(LOG_WARNING, "Invalid address: %s\n", var->value);
1725                         } else {
1726                                 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
1727                         }
1728                 }
1729 /*  Idea to allow for custom candidates  */
1730 /*
1731                 else if (!strcasecmp(var->name, "candidate")) {
1732                         candidate = jingle_create_candidate(var->value);
1733                         if (candidate) {
1734                                 candidate->next = global_candidates;
1735                                 global_candidates = candidate;
1736                         }
1737                 }
1738 */
1739         }
1740         while (cat) {
1741                 if (strcasecmp(cat, "general")) {
1742                         var = ast_variable_browse(cfg, cat);
1743                         member = ast_calloc(1, sizeof(*member));
1744                         ASTOBJ_INIT(member);
1745                         ASTOBJ_WRLOCK(member);
1746                         if (!strcasecmp(cat, "guest")) {
1747                                 ast_copy_string(member->name, "guest", sizeof(member->name));
1748                                 ast_copy_string(member->user, "guest", sizeof(member->user));
1749                                 ast_copy_string(member->context, context, sizeof(member->context));
1750                                 member->allowguest = allowguest;
1751                                 member->prefs = prefs;
1752                                 while (var) {
1753                                         if (!strcasecmp(var->name, "disallow"))
1754                                                 ast_parse_allow_disallow(&member->prefs, &member->capability,
1755                                                                                                  var->value, 0);
1756                                         else if (!strcasecmp(var->name, "allow"))
1757                                                 ast_parse_allow_disallow(&member->prefs, &member->capability,
1758                                                                                                  var->value, 1);
1759                                         else if (!strcasecmp(var->name, "context"))
1760                                                 ast_copy_string(member->context, var->value,
1761                                                                                 sizeof(member->context));
1762 /*  Idea to allow for custom candidates  */
1763 /*
1764                                         else if (!strcasecmp(var->name, "candidate")) {
1765                                                 candidate = jingle_create_candidate(var->value);
1766                                                 if (candidate) {
1767                                                         candidate->next = member->ourcandidates;
1768                                                         member->ourcandidates = candidate;
1769                                                 }
1770                                         }
1771 */
1772                                         var = var->next;
1773                                 }
1774                                 ASTOBJ_UNLOCK(member);
1775                                 clients = ast_aji_get_clients();
1776                                 if (clients) {
1777                                         ASTOBJ_CONTAINER_TRAVERSE(clients, 1, {
1778                                                 ASTOBJ_WRLOCK(iterator);
1779                                                 ASTOBJ_WRLOCK(member);
1780                                                 member->connection = iterator;
1781                                                 iks_filter_add_rule(iterator->f, jingle_parser, member, IKS_RULE_TYPE, IKS_PAK_IQ, IKS_RULE_NS, JINGLE_NS, IKS_RULE_DONE);
1782                                                 iks_filter_add_rule(iterator->f, jingle_parser, member, IKS_RULE_TYPE, IKS_PAK_IQ, IKS_RULE_NS, JINGLE_DTMF_NS, IKS_RULE_DONE);
1783                                                 ASTOBJ_UNLOCK(member);
1784                                                 ASTOBJ_CONTAINER_LINK(&jingle_list, member);
1785                                                 ASTOBJ_UNLOCK(iterator);
1786                                         });
1787                                 } else {
1788                                         ASTOBJ_UNLOCK(member);
1789                                         ASTOBJ_UNREF(member, jingle_member_destroy);
1790                                 }
1791                         } else {
1792                                 ASTOBJ_UNLOCK(member);
1793                                 if (jingle_create_member(cat, var, allowguest, prefs, context, member))
1794                                         ASTOBJ_CONTAINER_LINK(&jingle_list, member);
1795                                 ASTOBJ_UNREF(member, jingle_member_destroy);
1796                         }
1797                 }
1798                 cat = ast_category_browse(cfg, cat);
1799         }
1800         jingle_free_candidates(global_candidates);
1801         return 1;
1802 }
1803
1804 /*! \brief Load module into PBX, register channel */
1805 static int load_module(void)
1806 {
1807 #ifdef HAVE_GNUTLS      
1808         gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
1809 #endif /* HAVE_GNUTLS */
1810
1811         ASTOBJ_CONTAINER_INIT(&jingle_list);
1812         if (!jingle_load_config()) {
1813                 ast_log(LOG_ERROR, "Unable to read config file %s. Not loading module.\n", JINGLE_CONFIG);
1814                 return AST_MODULE_LOAD_DECLINE;
1815         }
1816
1817         sched = sched_context_create();
1818         if (!sched) 
1819                 ast_log(LOG_WARNING, "Unable to create schedule context\n");
1820
1821         io = io_context_create();
1822         if (!io) 
1823                 ast_log(LOG_WARNING, "Unable to create I/O context\n");
1824
1825         if (ast_find_ourip(&__ourip, bindaddr)) {
1826                 ast_log(LOG_WARNING, "Unable to get own IP address, Jingle disabled\n");
1827                 return 0;
1828         }
1829
1830         ast_rtp_proto_register(&jingle_rtp);
1831         ast_cli_register_multiple(jingle_cli, sizeof(jingle_cli) / sizeof(jingle_cli[0]));
1832         /* Make sure we can register our channel type */
1833         if (ast_channel_register(&jingle_tech)) {
1834                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
1835                 return -1;
1836         }
1837         return 0;
1838 }
1839
1840 /*! \brief Reload module */
1841 static int reload(void)
1842 {
1843         return 0;
1844 }
1845
1846 /*! \brief Unload the jingle channel from Asterisk */
1847 static int unload_module(void)
1848 {
1849         struct jingle_pvt *privates = NULL;
1850         ast_cli_unregister_multiple(jingle_cli, sizeof(jingle_cli) / sizeof(jingle_cli[0]));
1851         /* First, take us out of the channel loop */
1852         ast_channel_unregister(&jingle_tech);
1853         ast_rtp_proto_unregister(&jingle_rtp);
1854
1855         if (!ast_mutex_lock(&jinglelock)) {
1856                 /* Hangup all interfaces if they have an owner */
1857                 ASTOBJ_CONTAINER_TRAVERSE(&jingle_list, 1, {
1858                         ASTOBJ_WRLOCK(iterator);
1859                         privates = iterator->p;
1860                         while(privates) {
1861                                 if (privates->owner)
1862                                         ast_softhangup(privates->owner, AST_SOFTHANGUP_APPUNLOAD);
1863                                 privates = privates->next;
1864                         }
1865                         iterator->p = NULL;
1866                         ASTOBJ_UNLOCK(iterator);
1867                 });
1868                 ast_mutex_unlock(&jinglelock);
1869         } else {
1870                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
1871                 return -1;
1872         }
1873         ASTOBJ_CONTAINER_DESTROYALL(&jingle_list, jingle_member_destroy);
1874         ASTOBJ_CONTAINER_DESTROY(&jingle_list);
1875         return 0;
1876 }
1877
1878 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Jingle Channel Driver",
1879                 .load = load_module,
1880                 .unload = unload_module,
1881                 .reload = reload,
1882                );