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