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