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