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