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