Do not link the guest account with any configured XMPP client (in
[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         char audio_content_name[100];    /*!< name attribute of content tag */
115         struct ast_rtp *rtp;             /*!< RTP audio session */
116         char video_content_name[100];    /*!< name attribute of content tag */
117         struct ast_rtp *vrtp;            /*!< RTP video session */
118         int jointcapability;             /*!< Supported capability at both ends (codecs ) */
119         int peercapability;
120         struct jingle_pvt *next;        /* Next entity */
121 };
122
123 struct jingle_candidate {
124         unsigned int component;          /*!< ex. : 1 for RTP, 2 for RTCP */
125         unsigned int foundation;         /*!< Function of IP, protocol, type */
126         unsigned int generation;
127         char ip[16];
128         unsigned int network;
129         unsigned int port;
130         unsigned int priority;
131         enum jingle_protocol protocol;
132         char password[100];
133         enum jingle_connect_type type;
134         char ufrag[100];
135         unsigned int preference;
136         struct jingle_candidate *next;
137 };
138
139 struct jingle {
140         ASTOBJ_COMPONENTS(struct jingle);
141         struct aji_client *connection;
142         struct aji_buddy *buddy;
143         struct jingle_pvt *p;
144         struct ast_codec_pref prefs;
145         int amaflags;                   /*!< AMA Flags */
146         char user[100];
147         char context[100];
148         char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */
149         int capability;
150         ast_group_t callgroup;  /*!< Call group */
151         ast_group_t pickupgroup;        /*!< Pickup group */
152         int callingpres;                /*!< Calling presentation */
153         int allowguest;
154         char language[MAX_LANGUAGE];    /*!<  Default language for prompts */
155         char musicclass[MAX_MUSICCLASS];        /*!<  Music on Hold class */
156         char parkinglot[AST_MAX_CONTEXT];   /*!< Parkinglot */
157 };
158
159 struct jingle_container {
160         ASTOBJ_CONTAINER_COMPONENTS(struct jingle);
161 };
162
163 static const char desc[] = "Jingle Channel";
164 static const char type[] = "Jingle";
165
166 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
167
168 AST_MUTEX_DEFINE_STATIC(jinglelock); /*!< Protect the interface list (of jingle_pvt's) */
169
170 /* Forward declarations */
171 static struct ast_channel *jingle_request(const char *type, int format, void *data, int *cause);
172 static int jingle_digit_begin(struct ast_channel *ast, char digit);
173 static int jingle_digit_end(struct ast_channel *ast, char digit, unsigned int duration);
174 static int jingle_call(struct ast_channel *ast, char *dest, int timeout);
175 static int jingle_hangup(struct ast_channel *ast);
176 static int jingle_answer(struct ast_channel *ast);
177 static int jingle_newcall(struct jingle *client, ikspak *pak);
178 static struct ast_frame *jingle_read(struct ast_channel *ast);
179 static int jingle_write(struct ast_channel *ast, struct ast_frame *f);
180 static int jingle_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
181 static int jingle_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
182 static int jingle_sendhtml(struct ast_channel *ast, int subclass, const char *data, int datalen);
183 static struct jingle_pvt *jingle_alloc(struct jingle *client, const char *from, const char *sid);
184 static char *jingle_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
185 static char *jingle_do_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
186 /*----- RTP interface functions */
187 static int jingle_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp,
188                                                            struct ast_rtp *vrtp, struct ast_rtp *tpeer, int codecs, int nat_active);
189 static enum ast_rtp_get_result jingle_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
190 static int jingle_get_codec(struct ast_channel *chan);
191
192 /*! \brief PBX interface structure for channel registration */
193 static const struct ast_channel_tech jingle_tech = {
194         .type = "Jingle",
195         .description = "Jingle Channel Driver",
196         .capabilities = AST_FORMAT_AUDIO_MASK,
197         .requester = jingle_request,
198         .send_digit_begin = jingle_digit_begin,
199         .send_digit_end = jingle_digit_end,
200         .bridge = ast_rtp_bridge,
201         .call = jingle_call,
202         .hangup = jingle_hangup,
203         .answer = jingle_answer,
204         .read = jingle_read,
205         .write = jingle_write,
206         .exception = jingle_read,
207         .indicate = jingle_indicate,
208         .fixup = jingle_fixup,
209         .send_html = jingle_sendhtml,
210         .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER
211 };
212
213 static struct sockaddr_in bindaddr = { 0, };    /*!< The address we bind to */
214
215 static struct sched_context *sched;     /*!< The scheduling context */
216 static struct io_context *io;   /*!< The IO context */
217 static struct in_addr __ourip;
218
219
220 /*! \brief RTP driver interface */
221 static struct ast_rtp_protocol jingle_rtp = {
222         type: "Jingle",
223         get_rtp_info: jingle_get_rtp_peer,
224         set_rtp_peer: jingle_set_rtp_peer,
225         get_codec: jingle_get_codec,
226 };
227
228 static struct ast_cli_entry jingle_cli[] = {
229         AST_CLI_DEFINE(jingle_do_reload, "Reload Jingle configuration"),
230         AST_CLI_DEFINE(jingle_show_channels, "Show Jingle channels"),
231 };
232
233
234 static char externip[16];
235
236 static struct jingle_container jingle_list;
237
238 static void jingle_member_destroy(struct jingle *obj)
239 {
240         ast_free(obj);
241 }
242
243 static struct jingle *find_jingle(char *name, char *connection)
244 {
245         struct jingle *jingle = NULL;
246
247         jingle = ASTOBJ_CONTAINER_FIND(&jingle_list, name);
248         if (!jingle && strchr(name, '@'))
249                 jingle = ASTOBJ_CONTAINER_FIND_FULL(&jingle_list, name, user,,, strcasecmp);
250
251         if (!jingle) {                          
252                 /* guest call */
253                 ASTOBJ_CONTAINER_TRAVERSE(&jingle_list, 1, {
254                         ASTOBJ_RDLOCK(iterator);
255                         if (!strcasecmp(iterator->name, "guest")) {
256                                 jingle = iterator;
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 *codec, *content, *description;
959         char *from = NULL;
960
961         /* Make sure our new call doesn't exist yet */
962         from = iks_find_attrib(pak->x,"to");
963         if(!from)
964                 from = client->connection->jid->full;
965
966         while (tmp) {
967                 if (iks_find_with_attrib(pak->x, JINGLE_NODE, JINGLE_SID, tmp->sid)) {
968                         ast_log(LOG_NOTICE, "Ignoring duplicate call setup on SID %s\n", tmp->sid);
969                         jingle_response(client, pak, "out-of-order", NULL);
970                         return -1;
971                 }
972                 tmp = tmp->next;
973         }
974
975         if (!strcasecmp(client->name, "guest")){
976                 /* the guest account is not tied to any configured XMPP client,
977                    let's set it now */
978                 client->connection = ast_aji_get_client(from);
979                 if (!client->connection) {
980                         ast_log(LOG_ERROR, "No XMPP client to talk to, us (partial JID) : %s\n", from);
981                         return -1;
982                 }
983         }
984
985         p = jingle_alloc(client, pak->from->partial, iks_find_attrib(pak->query, JINGLE_SID));
986         if (!p) {
987                 ast_log(LOG_WARNING, "Unable to allocate jingle structure!\n");
988                 return -1;
989         }
990         chan = jingle_new(client, p, AST_STATE_DOWN, pak->from->user);
991         if (!chan) {
992                 jingle_free_pvt(client, p);
993                 return -1;
994         }
995         ast_mutex_lock(&p->lock);
996         ast_copy_string(p->them, pak->from->full, sizeof(p->them));
997         if (iks_find_attrib(pak->query, JINGLE_SID)) {
998                 ast_copy_string(p->sid, iks_find_attrib(pak->query, JINGLE_SID),
999                                 sizeof(p->sid));
1000         }
1001         
1002         /* content points to the first <content/> tag */        
1003         content = iks_child(iks_child(pak->x));
1004         while (content) {
1005                 description = iks_find_with_attrib(content, "description", "xmlns", JINGLE_AUDIO_RTP_NS);
1006                 if (description) {
1007                         /* audio content found */
1008                         codec = iks_child(iks_child(content));
1009                         ast_copy_string(p->audio_content_name, iks_find_attrib(content, "name"), sizeof(p->audio_content_name));
1010
1011                         while (codec) {
1012                                 ast_rtp_set_m_type(p->rtp, atoi(iks_find_attrib(codec, "id")));
1013                                 ast_rtp_set_rtpmap_type(p->rtp, atoi(iks_find_attrib(codec, "id")), "audio", iks_find_attrib(codec, "name"), 0);
1014                                 codec = iks_next(codec);
1015                         }
1016                 }
1017                 
1018                 description = NULL;
1019                 codec = NULL;
1020
1021                 description = iks_find_with_attrib(content, "description", "xmlns", JINGLE_VIDEO_RTP_NS);
1022                 if (description) {
1023                         /* video content found */
1024                         codec = iks_child(iks_child(content));
1025                         ast_copy_string(p->video_content_name, iks_find_attrib(content, "name"), sizeof(p->video_content_name));
1026
1027                         while (codec) {
1028                                 ast_rtp_set_m_type(p->rtp, atoi(iks_find_attrib(codec, "id")));
1029                                 ast_rtp_set_rtpmap_type(p->rtp, atoi(iks_find_attrib(codec, "id")), "audio", iks_find_attrib(codec, "name"), 0);
1030                                 codec = iks_next(codec);
1031                         }
1032                 }
1033                 
1034                 content = iks_next(content);
1035         }
1036
1037         ast_mutex_unlock(&p->lock);
1038         ast_setstate(chan, AST_STATE_RING);
1039         res = ast_pbx_start(chan);
1040         
1041         switch (res) {
1042         case AST_PBX_FAILED:
1043                 ast_log(LOG_WARNING, "Failed to start PBX :(\n");
1044                 jingle_response(client, pak, "service-unavailable", NULL);
1045                 break;
1046         case AST_PBX_CALL_LIMIT:
1047                 ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
1048                 jingle_response(client, pak, "service-unavailable", NULL);
1049                 break;
1050         case AST_PBX_SUCCESS:
1051                 jingle_response(client, pak, NULL, NULL);
1052                 jingle_create_candidates(client, p,
1053                                          iks_find_attrib(pak->query, JINGLE_SID),
1054                                          iks_find_attrib(pak->x, "from"));
1055                 /* nothing to do */
1056                 break;
1057         }
1058
1059         return 1;
1060 }
1061
1062 static int jingle_update_stun(struct jingle *client, struct jingle_pvt *p)
1063 {
1064         struct jingle_candidate *tmp;
1065         struct hostent *hp;
1066         struct ast_hostent ahp;
1067         struct sockaddr_in sin;
1068
1069         if (time(NULL) == p->laststun)
1070                 return 0;
1071
1072         tmp = p->theircandidates;
1073         p->laststun = time(NULL);
1074         while (tmp) {
1075                 char username[256];
1076                 hp = ast_gethostbyname(tmp->ip, &ahp);
1077                 sin.sin_family = AF_INET;
1078                 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
1079                 sin.sin_port = htons(tmp->port);
1080                 snprintf(username, sizeof(username), "%s:%s", tmp->ufrag, p->ourcandidates->ufrag);
1081
1082                 ast_rtp_stun_request(p->rtp, &sin, username);
1083                 tmp = tmp->next;
1084         }
1085         return 1;
1086 }
1087
1088 static int jingle_add_candidate(struct jingle *client, ikspak *pak)
1089 {
1090         struct jingle_pvt *p = NULL, *tmp = NULL;
1091         struct aji_client *c = client->connection;
1092         struct jingle_candidate *newcandidate = NULL;
1093         iks *traversenodes = NULL, *receipt = NULL;
1094
1095         for (tmp = client->p; tmp; tmp = tmp->next) {
1096                 if (iks_find_with_attrib(pak->x, JINGLE_NODE, JINGLE_SID, tmp->sid)) {
1097                         p = tmp;
1098                         break;
1099                 }
1100         }
1101
1102         if (!p)
1103                 return -1;
1104
1105         traversenodes = pak->query;
1106         while(traversenodes) {
1107                 if(!strcasecmp(iks_name(traversenodes), "jingle")) {
1108                         traversenodes = iks_child(traversenodes);
1109                         continue;
1110                 }
1111                 if(!strcasecmp(iks_name(traversenodes), "content")) {
1112                         traversenodes = iks_child(traversenodes);
1113                         continue;
1114                 }
1115                 if(!strcasecmp(iks_name(traversenodes), "transport")) {
1116                         traversenodes = iks_child(traversenodes);
1117                         continue;
1118                 }
1119
1120                 if(!strcasecmp(iks_name(traversenodes), "candidate")) {
1121                         newcandidate = ast_calloc(1, sizeof(*newcandidate));
1122                         if (!newcandidate)
1123                                 return 0;
1124                         ast_copy_string(newcandidate->ip, iks_find_attrib(traversenodes, "ip"), sizeof(newcandidate->ip));
1125                         newcandidate->port = atoi(iks_find_attrib(traversenodes, "port"));
1126                         ast_copy_string(newcandidate->password, iks_find_attrib(traversenodes, "pwd"), sizeof(newcandidate->password));
1127                         if (!strcasecmp(iks_find_attrib(traversenodes, "protocol"), "udp"))
1128                                 newcandidate->protocol = AJI_PROTOCOL_UDP;
1129                         else if (!strcasecmp(iks_find_attrib(traversenodes, "protocol"), "ssltcp"))
1130                                 newcandidate->protocol = AJI_PROTOCOL_SSLTCP;
1131                         
1132                         if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "host"))
1133                                 newcandidate->type = AJI_CONNECT_HOST;
1134                         else if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "prflx"))
1135                                 newcandidate->type = AJI_CONNECT_PRFLX;
1136                         else if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "relay"))
1137                                 newcandidate->type = AJI_CONNECT_RELAY;
1138                         else if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "srflx"))
1139                                 newcandidate->type = AJI_CONNECT_SRFLX;
1140
1141                         newcandidate->network = atoi(iks_find_attrib(traversenodes, "network"));
1142                         newcandidate->generation = atoi(iks_find_attrib(traversenodes, "generation"));
1143                         newcandidate->next = NULL;
1144                 
1145                         newcandidate->next = p->theircandidates;
1146                         p->theircandidates = newcandidate;
1147                         p->laststun = 0;
1148                         jingle_update_stun(p->parent, p);
1149                         newcandidate = NULL;
1150                 }
1151                 traversenodes = iks_next(traversenodes);
1152         }
1153         
1154         receipt = iks_new("iq");
1155         iks_insert_attrib(receipt, "type", "result");
1156         iks_insert_attrib(receipt, "from", c->jid->full);
1157         iks_insert_attrib(receipt, "to", iks_find_attrib(pak->x, "from"));
1158         iks_insert_attrib(receipt, "id", iks_find_attrib(pak->x, "id"));
1159         ast_aji_send(c, receipt);
1160
1161         iks_delete(receipt);
1162
1163         return 1;
1164 }
1165
1166 static struct ast_frame *jingle_rtp_read(struct ast_channel *ast, struct jingle_pvt *p)
1167 {
1168         struct ast_frame *f;
1169
1170         if (!p->rtp)
1171                 return &ast_null_frame;
1172         f = ast_rtp_read(p->rtp);
1173         jingle_update_stun(p->parent, p);
1174         if (p->owner) {
1175                 /* We already hold the channel lock */
1176                 if (f->frametype == AST_FRAME_VOICE) {
1177                         if (f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
1178                                 ast_debug(1, "Oooh, format changed to %d\n", f->subclass);
1179                                 p->owner->nativeformats =
1180                                         (p->owner->nativeformats & AST_FORMAT_VIDEO_MASK) | f->subclass;
1181                                 ast_set_read_format(p->owner, p->owner->readformat);
1182                                 ast_set_write_format(p->owner, p->owner->writeformat);
1183                         }
1184 /*                      if ((ast_test_flag(p, SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
1185                                 f = ast_dsp_process(p->owner, p->vad, f);
1186                                 if (f && (f->frametype == AST_FRAME_DTMF))
1187                                         ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass);
1188                         } */
1189                 }
1190         }
1191         return f;
1192 }
1193
1194 static struct ast_frame *jingle_read(struct ast_channel *ast)
1195 {
1196         struct ast_frame *fr;
1197         struct jingle_pvt *p = ast->tech_pvt;
1198
1199         ast_mutex_lock(&p->lock);
1200         fr = jingle_rtp_read(ast, p);
1201         ast_mutex_unlock(&p->lock);
1202         return fr;
1203 }
1204
1205 /*! \brief Send frame to media channel (rtp) */
1206 static int jingle_write(struct ast_channel *ast, struct ast_frame *frame)
1207 {
1208         struct jingle_pvt *p = ast->tech_pvt;
1209         int res = 0;
1210
1211         switch (frame->frametype) {
1212         case AST_FRAME_VOICE:
1213                 if (!(frame->subclass & ast->nativeformats)) {
1214                         ast_log(LOG_WARNING,
1215                                         "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
1216                                         frame->subclass, ast->nativeformats, ast->readformat,
1217                                         ast->writeformat);
1218                         return 0;
1219                 }
1220                 if (p) {
1221                         ast_mutex_lock(&p->lock);
1222                         if (p->rtp) {
1223                                 res = ast_rtp_write(p->rtp, frame);
1224                         }
1225                         ast_mutex_unlock(&p->lock);
1226                 }
1227                 break;
1228         case AST_FRAME_VIDEO:
1229                 if (p) {
1230                         ast_mutex_lock(&p->lock);
1231                         if (p->vrtp) {
1232                                 res = ast_rtp_write(p->vrtp, frame);
1233                         }
1234                         ast_mutex_unlock(&p->lock);
1235                 }
1236                 break;
1237         case AST_FRAME_IMAGE:
1238                 return 0;
1239                 break;
1240         default:
1241                 ast_log(LOG_WARNING, "Can't send %d type frames with Jingle write\n",
1242                                 frame->frametype);
1243                 return 0;
1244         }
1245
1246         return res;
1247 }
1248
1249 static int jingle_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1250 {
1251         struct jingle_pvt *p = newchan->tech_pvt;
1252         ast_mutex_lock(&p->lock);
1253
1254         if ((p->owner != oldchan)) {
1255                 ast_mutex_unlock(&p->lock);
1256                 return -1;
1257         }
1258         if (p->owner == oldchan)
1259                 p->owner = newchan;
1260         ast_mutex_unlock(&p->lock);
1261         return 0;
1262 }
1263
1264 static int jingle_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
1265 {
1266         int res = 0;
1267
1268         switch (condition) {
1269         case AST_CONTROL_HOLD:
1270                 ast_moh_start(ast, data, NULL);
1271                 break;
1272         case AST_CONTROL_UNHOLD:
1273                 ast_moh_stop(ast);
1274                 break;
1275         default:
1276                 ast_log(LOG_NOTICE, "Don't know how to indicate condition '%d'\n", condition);
1277                 res = -1;
1278         }
1279
1280         return res;
1281 }
1282
1283 static int jingle_digit(struct ast_channel *ast, char digit, unsigned int duration)
1284 {
1285         struct jingle_pvt *p = ast->tech_pvt;
1286         struct jingle *client = p->parent;
1287         iks *iq, *jingle, *dtmf;
1288         char buffer[2] = {digit, '\0'};
1289         iq = iks_new("iq");
1290         jingle = iks_new("jingle");
1291         dtmf = iks_new("dtmf");
1292         if(!iq || !jingle || !dtmf) {
1293                 iks_delete(iq);
1294                 iks_delete(jingle);
1295                 iks_delete(dtmf);
1296                 ast_log(LOG_ERROR, "Did not send dtmf do to memory issue\n");
1297                 return -1;
1298         }
1299
1300         iks_insert_attrib(iq, "type", "set");
1301         iks_insert_attrib(iq, "to", p->them);
1302         iks_insert_attrib(iq, "from", client->connection->jid->full);
1303         iks_insert_attrib(iq, "id", client->connection->mid);
1304         ast_aji_increment_mid(client->connection->mid);
1305         iks_insert_attrib(jingle, "xmlns", JINGLE_NS);
1306         iks_insert_attrib(jingle, "action", "session-info");
1307         iks_insert_attrib(jingle, "initiator", p->initiator ? client->connection->jid->full : p->them);
1308         iks_insert_attrib(jingle, "sid", p->sid);
1309         iks_insert_attrib(dtmf, "xmlns", JINGLE_DTMF_NS);
1310         iks_insert_attrib(dtmf, "code", buffer);
1311         iks_insert_node(iq, jingle);
1312         iks_insert_node(jingle, dtmf);
1313
1314         ast_mutex_lock(&p->lock);
1315         if (ast->dtmff.frametype == AST_FRAME_DTMF_BEGIN || duration == 0) {
1316                 iks_insert_attrib(dtmf, "action", "button-down");
1317         } else if (ast->dtmff.frametype == AST_FRAME_DTMF_END || duration != 0) {
1318                 iks_insert_attrib(dtmf, "action", "button-up");
1319         }
1320         ast_aji_send(client->connection, iq);
1321
1322         iks_delete(iq);
1323         iks_delete(jingle);
1324         iks_delete(dtmf);
1325         ast_mutex_unlock(&p->lock);
1326         return 0;
1327 }
1328
1329 static int jingle_digit_begin(struct ast_channel *chan, char digit)
1330 {
1331         return jingle_digit(chan, digit, 0);
1332 }
1333
1334 static int jingle_digit_end(struct ast_channel *ast, char digit, unsigned int duration)
1335 {
1336         return jingle_digit(ast, digit, duration);
1337 }
1338
1339 static int jingle_sendhtml(struct ast_channel *ast, int subclass, const char *data, int datalen)
1340 {
1341         ast_log(LOG_NOTICE, "XXX Implement jingle sendhtml XXX\n");
1342
1343         return -1;
1344 }
1345 static int jingle_transmit_invite(struct jingle_pvt *p)
1346 {
1347         struct jingle *aux = NULL;
1348         struct aji_client *client = NULL;
1349         iks *iq, *jingle, *content, *description, *transport;
1350         iks *payload_eg711u, *payload_pcmu;
1351
1352         aux = p->parent;
1353         client = aux->connection;
1354         iq = iks_new("iq");
1355         jingle = iks_new(JINGLE_NODE);
1356         content = iks_new("content");
1357         description = iks_new("description");
1358         transport = iks_new("transport");
1359         payload_pcmu = iks_new("payload-type");
1360         payload_eg711u = iks_new("payload-type");
1361
1362         ast_copy_string(p->audio_content_name, "asterisk-audio-content", sizeof(p->audio_content_name));
1363
1364         iks_insert_attrib(iq, "type", "set");
1365         iks_insert_attrib(iq, "to", p->them);
1366         iks_insert_attrib(iq, "from", client->jid->full);
1367         iks_insert_attrib(iq, "id", client->mid);
1368         ast_aji_increment_mid(client->mid);
1369         iks_insert_attrib(jingle, "action", JINGLE_INITIATE);
1370         iks_insert_attrib(jingle, JINGLE_SID, p->sid);
1371         iks_insert_attrib(jingle, "initiator", client->jid->full);
1372         iks_insert_attrib(jingle, "xmlns", JINGLE_NS);
1373
1374         /* For now, we only send one audio based content */
1375         iks_insert_attrib(content, "creator", "initiator");
1376         iks_insert_attrib(content, "name", p->audio_content_name);
1377         iks_insert_attrib(content, "profile", "RTP/AVP");
1378         iks_insert_attrib(description, "xmlns", JINGLE_AUDIO_RTP_NS);
1379         iks_insert_attrib(transport, "xmlns", JINGLE_ICE_UDP_NS);
1380         iks_insert_attrib(payload_pcmu, "id", "0");
1381         iks_insert_attrib(payload_pcmu, "name", "PCMU");
1382         iks_insert_attrib(payload_eg711u, "id", "100");
1383         iks_insert_attrib(payload_eg711u, "name", "EG711U");
1384         iks_insert_node(description, payload_pcmu);
1385         iks_insert_node(description, payload_eg711u);
1386         iks_insert_node(content, description);
1387         iks_insert_node(content, transport);
1388         iks_insert_node(jingle, content);
1389         iks_insert_node(iq, jingle);
1390
1391         ast_aji_send(client, iq);
1392
1393         iks_delete(iq);
1394         iks_delete(jingle);
1395         iks_delete(content);
1396         iks_delete(description);
1397         iks_delete(transport);
1398         iks_delete(payload_eg711u);
1399         iks_delete(payload_pcmu);
1400         return 0;
1401 }
1402
1403 /* Not in use right now.
1404 static int jingle_auto_congest(void *nothing)
1405 {
1406         struct jingle_pvt *p = nothing;
1407
1408         ast_mutex_lock(&p->lock);
1409         if (p->owner) {
1410                 if (!ast_channel_trylock(p->owner)) {
1411                         ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
1412                         ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
1413                         ast_channel_unlock(p->owner);
1414                 }
1415         }
1416         ast_mutex_unlock(&p->lock);
1417         return 0;
1418 }
1419 */
1420
1421 /*! \brief Initiate new call, part of PBX interface 
1422  *      dest is the dial string */
1423 static int jingle_call(struct ast_channel *ast, char *dest, int timeout)
1424 {
1425         struct jingle_pvt *p = ast->tech_pvt;
1426
1427         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
1428                 ast_log(LOG_WARNING, "jingle_call called on %s, neither down nor reserved\n", ast->name);
1429                 return -1;
1430         }
1431
1432         ast_setstate(ast, AST_STATE_RING);
1433         p->jointcapability = p->capability;
1434         if (!p->ringrule) {
1435                 ast_copy_string(p->ring, p->parent->connection->mid, sizeof(p->ring));
1436                 p->ringrule = iks_filter_add_rule(p->parent->connection->f, jingle_ringing_ack, p,
1437                                                         IKS_RULE_ID, p->ring, IKS_RULE_DONE);
1438         } else
1439                 ast_log(LOG_WARNING, "Whoa, already have a ring rule!\n");
1440
1441         jingle_transmit_invite(p);
1442         jingle_create_candidates(p->parent, p, p->sid, p->them);
1443
1444         return 0;
1445 }
1446
1447 /*! \brief Hangup a call through the jingle proxy channel */
1448 static int jingle_hangup(struct ast_channel *ast)
1449 {
1450         struct jingle_pvt *p = ast->tech_pvt;
1451         struct jingle *client;
1452
1453         ast_mutex_lock(&p->lock);
1454         client = p->parent;
1455         p->owner = NULL;
1456         ast->tech_pvt = NULL;
1457         if (!p->alreadygone)
1458                 jingle_action(client, p, JINGLE_TERMINATE);
1459         ast_mutex_unlock(&p->lock);
1460
1461         jingle_free_pvt(client, p);
1462
1463         return 0;
1464 }
1465
1466 /*! \brief Part of PBX interface */
1467 static struct ast_channel *jingle_request(const char *type, int format, void *data, int *cause)
1468 {
1469         struct jingle_pvt *p = NULL;
1470         struct jingle *client = NULL;
1471         char *sender = NULL, *to = NULL, *s = NULL;
1472         struct ast_channel *chan = NULL;
1473
1474         if (data) {
1475                 s = ast_strdupa(data);
1476                 if (s) {
1477                         sender = strsep(&s, "/");
1478                         if (sender && (sender[0] != '\0'))
1479                                 to = strsep(&s, "/");
1480                         if (!to) {
1481                                 ast_log(LOG_ERROR, "Bad arguments in Jingle Dialstring: %s\n", (char*) data);
1482                                 return NULL;
1483                         }
1484                 }
1485         }
1486
1487         client = find_jingle(to, sender);
1488         if (!client) {
1489                 ast_log(LOG_WARNING, "Could not find recipient.\n");
1490                 return NULL;
1491         }
1492         if (!strcasecmp(client->name, "guest")){
1493                 /* the guest account is not tied to any configured XMPP client,
1494                    let's set it now */
1495                 client->connection = ast_aji_get_client(sender);
1496                 if (!client->connection) {
1497                         ast_log(LOG_ERROR, "No XMPP client to talk to, us (partial JID) : %s\n", sender);
1498                         return NULL;
1499                 }
1500         }
1501        
1502         ASTOBJ_WRLOCK(client);
1503         p = jingle_alloc(client, to, NULL);
1504         if (p)
1505                 chan = jingle_new(client, p, AST_STATE_DOWN, to);
1506         ASTOBJ_UNLOCK(client);
1507
1508         return chan;
1509 }
1510
1511 /*! \brief CLI command "jingle show channels" */
1512 static char *jingle_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1513 {
1514 #define FORMAT  "%-30.30s  %-30.30s  %-15.15s  %-5.5s %-5.5s \n"
1515         struct jingle_pvt *p;
1516         struct ast_channel *chan;
1517         int numchans = 0;
1518         char them[AJI_MAX_JIDLEN];
1519         char *jid = NULL;
1520         char *resource = NULL;
1521
1522         switch (cmd) {
1523         case CLI_INIT:
1524                 e->command = "jingle show channels";
1525                 e->usage =
1526                         "Usage: jingle show channels\n"
1527                         "       Shows current state of the Jingle channels.\n";
1528                 return NULL;
1529         case CLI_GENERATE:
1530                 return NULL;
1531         }
1532
1533         if (a->argc != 3)
1534                 return CLI_SHOWUSAGE;
1535
1536         ast_mutex_lock(&jinglelock);
1537         ast_cli(a->fd, FORMAT, "Channel", "Jabber ID", "Resource", "Read", "Write");
1538         ASTOBJ_CONTAINER_TRAVERSE(&jingle_list, 1, {
1539                 ASTOBJ_WRLOCK(iterator);
1540                 p = iterator->p;
1541                 while(p) {
1542                         chan = p->owner;
1543                         ast_copy_string(them, p->them, sizeof(them));
1544                         jid = them;
1545                         resource = strchr(them, '/');
1546                         if (!resource)
1547                                 resource = "None";
1548                         else {
1549                                 *resource = '\0';
1550                                 resource ++;
1551                         }
1552                         if (chan)
1553                                 ast_cli(a->fd, FORMAT, 
1554                                         chan->name,
1555                                         jid,
1556                                         resource,
1557                                         ast_getformatname(chan->readformat),
1558                                         ast_getformatname(chan->writeformat)                                    
1559                                         );
1560                         else 
1561                                 ast_log(LOG_WARNING, "No available channel\n");
1562                         numchans ++;
1563                         p = p->next;
1564                 }
1565                 ASTOBJ_UNLOCK(iterator);
1566         });
1567
1568         ast_mutex_unlock(&jinglelock);
1569
1570         ast_cli(a->fd, "%d active jingle channel%s\n", numchans, (numchans != 1) ? "s" : "");
1571         return CLI_SUCCESS;
1572 #undef FORMAT
1573 }
1574
1575 /*! \brief CLI command "jingle reload" */
1576 static char *jingle_do_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1577 {
1578         switch (cmd) {
1579         case CLI_INIT:
1580                 e->command = "jingle reload";
1581                 e->usage =
1582                         "Usage: jingle reload\n"
1583                         "       Reload jingle channel driver.\n";
1584                 return NULL;
1585         case CLI_GENERATE:
1586                 return NULL;
1587         }       
1588         
1589         return CLI_SUCCESS;
1590 }
1591
1592 static int jingle_parser(void *data, ikspak *pak)
1593 {
1594         struct jingle *client = ASTOBJ_REF((struct jingle *) data);
1595         ast_log(LOG_NOTICE, "Filter matched\n");
1596
1597         if (iks_find_with_attrib(pak->x, JINGLE_NODE, "action", JINGLE_INITIATE)) {
1598                 /* New call */
1599                 jingle_newcall(client, pak);
1600         } else if (iks_find_with_attrib(pak->x, JINGLE_NODE, "action", JINGLE_NEGOTIATE)) {
1601                 ast_debug(3, "About to add candidate!\n");
1602                 jingle_add_candidate(client, pak);
1603                 ast_debug(3, "Candidate Added!\n");
1604         } else if (iks_find_with_attrib(pak->x, JINGLE_NODE, "action", JINGLE_ACCEPT)) {
1605                 jingle_is_answered(client, pak);
1606         } else if (iks_find_with_attrib(pak->x, JINGLE_NODE, "action", JINGLE_INFO)) {
1607                 jingle_handle_dtmf(client, pak);
1608         } else if (iks_find_with_attrib(pak->x, JINGLE_NODE, "action", JINGLE_TERMINATE)) {
1609                 jingle_hangup_farend(client, pak);
1610         } else if (iks_find_with_attrib(pak->x, JINGLE_NODE, "action", "reject")) {
1611                 jingle_hangup_farend(client, pak);
1612         }
1613         ASTOBJ_UNREF(client, jingle_member_destroy);
1614         return IKS_FILTER_EAT;
1615 }
1616 /* Not using this anymore probably take out soon 
1617 static struct jingle_candidate *jingle_create_candidate(char *args)
1618 {
1619         char *name, *type, *preference, *protocol;
1620         struct jingle_candidate *res;
1621         res = ast_calloc(1, sizeof(*res));
1622         if (args)
1623                 name = args;
1624         if ((args = strchr(args, ','))) {
1625                 *args = '\0';
1626                 args++;
1627                 preference = args;
1628         }
1629         if ((args = strchr(args, ','))) {
1630                 *args = '\0';
1631                 args++;
1632                 protocol = args;
1633         }
1634         if ((args = strchr(args, ','))) {
1635                 *args = '\0';
1636                 args++;
1637                 type = args;
1638         }
1639         if (name)
1640                 ast_copy_string(res->name, name, sizeof(res->name));
1641         if (preference) {
1642                 res->preference = atof(preference);
1643         }
1644         if (protocol) {
1645                 if (!strcasecmp("udp", protocol))
1646                         res->protocol = AJI_PROTOCOL_UDP;
1647                 if (!strcasecmp("ssltcp", protocol))
1648                         res->protocol = AJI_PROTOCOL_SSLTCP;
1649         }
1650         if (type) {
1651                 if (!strcasecmp("host", type))
1652                         res->type = AJI_CONNECT_HOST;
1653                 if (!strcasecmp("prflx", type))
1654                         res->type = AJI_CONNECT_PRFLX;
1655                 if (!strcasecmp("relay", type))
1656                         res->type = AJI_CONNECT_RELAY;
1657                 if (!strcasecmp("srflx", type))
1658                         res->type = AJI_CONNECT_SRFLX;
1659         }
1660
1661         return res;
1662 }
1663 */
1664
1665 static int jingle_create_member(char *label, struct ast_variable *var, int allowguest,
1666                                                                 struct ast_codec_pref prefs, char *context,
1667                                                                 struct jingle *member)
1668 {
1669         struct aji_client *client;
1670
1671         if (!member)
1672                 ast_log(LOG_WARNING, "Out of memory.\n");
1673
1674         ast_copy_string(member->name, label, sizeof(member->name));
1675         ast_copy_string(member->user, label, sizeof(member->user));
1676         ast_copy_string(member->context, context, sizeof(member->context));
1677         member->allowguest = allowguest;
1678         member->prefs = prefs;
1679         while (var) {
1680 #if 0
1681                 struct jingle_candidate *candidate = NULL;
1682 #endif
1683                 if (!strcasecmp(var->name, "username"))
1684                         ast_copy_string(member->user, var->value, sizeof(member->user));
1685                 else if (!strcasecmp(var->name, "disallow"))
1686                         ast_parse_allow_disallow(&member->prefs, &member->capability, var->value, 0);
1687                 else if (!strcasecmp(var->name, "allow"))
1688                         ast_parse_allow_disallow(&member->prefs, &member->capability, var->value, 1);
1689                 else if (!strcasecmp(var->name, "context"))
1690                         ast_copy_string(member->context, var->value, sizeof(member->context));
1691 #if 0
1692                 else if (!strcasecmp(var->name, "candidate")) {
1693                         candidate = jingle_create_candidate(var->value);
1694                         if (candidate) {
1695                                 candidate->next = member->ourcandidates;
1696                                 member->ourcandidates = candidate;
1697                         }
1698                 }
1699 #endif
1700                 else if (!strcasecmp(var->name, "connection")) {
1701                         if ((client = ast_aji_get_client(var->value))) {
1702                                 member->connection = client;
1703                                 iks_filter_add_rule(client->f, jingle_parser, member,
1704                                                     IKS_RULE_TYPE, IKS_PAK_IQ,
1705                                                     IKS_RULE_FROM_PARTIAL, member->user,
1706                                                     IKS_RULE_NS, JINGLE_NS,
1707                                                     IKS_RULE_DONE);
1708                         } else {
1709                                 ast_log(LOG_ERROR, "connection referenced not found!\n");
1710                                 return 0;
1711                         }
1712                 }
1713                 var = var->next;
1714         }
1715         if (member->connection && member->user)
1716                 member->buddy = ASTOBJ_CONTAINER_FIND(&member->connection->buddies, member->user);
1717         else {
1718                 ast_log(LOG_ERROR, "No Connection or Username!\n");
1719         }
1720         return 1;
1721 }
1722
1723 static int jingle_load_config(void)
1724 {
1725         char *cat = NULL;
1726         struct ast_config *cfg = NULL;
1727         char context[100];
1728         int allowguest = 1;
1729         struct ast_variable *var;
1730         struct jingle *member;
1731         struct hostent *hp;
1732         struct ast_hostent ahp;
1733         struct ast_codec_pref prefs;
1734         struct aji_client_container *clients;
1735         struct jingle_candidate *global_candidates = NULL;
1736         struct ast_flags config_flags = { 0 };
1737
1738         cfg = ast_config_load(JINGLE_CONFIG, config_flags);
1739         if (!cfg)
1740                 return 0;
1741
1742         /* Copy the default jb config over global_jbconf */
1743         memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
1744
1745         cat = ast_category_browse(cfg, NULL);
1746         for (var = ast_variable_browse(cfg, "general"); var; var = var->next) {
1747                 /* handle jb conf */
1748                 if (!ast_jb_read_conf(&global_jbconf, var->name, var->value))
1749                         continue;
1750
1751                 if (!strcasecmp(var->name, "allowguest"))
1752                         allowguest =
1753                                 (ast_true(ast_variable_retrieve(cfg, "general", "allowguest"))) ? 1 : 0;
1754                 else if (!strcasecmp(var->name, "disallow"))
1755                         ast_parse_allow_disallow(&prefs, &global_capability, var->value, 0);
1756                 else if (!strcasecmp(var->name, "allow"))
1757                         ast_parse_allow_disallow(&prefs, &global_capability, var->value, 1);
1758                 else if (!strcasecmp(var->name, "context"))
1759                         ast_copy_string(context, var->value, sizeof(context));
1760                 else if (!strcasecmp(var->name, "externip"))
1761                         ast_copy_string(externip, var->value, sizeof(externip));
1762                 else if (!strcasecmp(var->name, "bindaddr")) {
1763                         if (!(hp = ast_gethostbyname(var->value, &ahp))) {
1764                                 ast_log(LOG_WARNING, "Invalid address: %s\n", var->value);
1765                         } else {
1766                                 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
1767                         }
1768                 }
1769 /*  Idea to allow for custom candidates  */
1770 /*
1771                 else if (!strcasecmp(var->name, "candidate")) {
1772                         candidate = jingle_create_candidate(var->value);
1773                         if (candidate) {
1774                                 candidate->next = global_candidates;
1775                                 global_candidates = candidate;
1776                         }
1777                 }
1778 */
1779         }
1780         while (cat) {
1781                 if (strcasecmp(cat, "general")) {
1782                         var = ast_variable_browse(cfg, cat);
1783                         member = ast_calloc(1, sizeof(*member));
1784                         ASTOBJ_INIT(member);
1785                         ASTOBJ_WRLOCK(member);
1786                         if (!strcasecmp(cat, "guest")) {
1787                                 ast_copy_string(member->name, "guest", sizeof(member->name));
1788                                 ast_copy_string(member->user, "guest", sizeof(member->user));
1789                                 ast_copy_string(member->context, context, sizeof(member->context));
1790                                 member->allowguest = allowguest;
1791                                 member->prefs = prefs;
1792                                 while (var) {
1793                                         if (!strcasecmp(var->name, "disallow"))
1794                                                 ast_parse_allow_disallow(&member->prefs, &member->capability,
1795                                                                                                  var->value, 0);
1796                                         else if (!strcasecmp(var->name, "allow"))
1797                                                 ast_parse_allow_disallow(&member->prefs, &member->capability,
1798                                                                                                  var->value, 1);
1799                                         else if (!strcasecmp(var->name, "context"))
1800                                                 ast_copy_string(member->context, var->value,
1801                                                                                 sizeof(member->context));
1802                                         else if (!strcasecmp(var->name, "parkinglot"))
1803                                                 ast_copy_string(member->parkinglot, var->value,
1804                                                                                 sizeof(member->parkinglot));
1805 /*  Idea to allow for custom candidates  */
1806 /*
1807                                         else if (!strcasecmp(var->name, "candidate")) {
1808                                                 candidate = jingle_create_candidate(var->value);
1809                                                 if (candidate) {
1810                                                         candidate->next = member->ourcandidates;
1811                                                         member->ourcandidates = candidate;
1812                                                 }
1813                                         }
1814 */
1815                                         var = var->next;
1816                                 }
1817                                 ASTOBJ_UNLOCK(member);
1818                                 clients = ast_aji_get_clients();
1819                                 if (clients) {
1820                                         ASTOBJ_CONTAINER_TRAVERSE(clients, 1, {
1821                                                 ASTOBJ_WRLOCK(iterator);
1822                                                 ASTOBJ_WRLOCK(member);
1823                                                 member->connection = NULL;
1824                                                 iks_filter_add_rule(iterator->f, jingle_parser, member, IKS_RULE_TYPE, IKS_PAK_IQ, IKS_RULE_NS, JINGLE_NS, IKS_RULE_DONE);
1825                                                 iks_filter_add_rule(iterator->f, jingle_parser, member, IKS_RULE_TYPE, IKS_PAK_IQ, IKS_RULE_NS, JINGLE_DTMF_NS, IKS_RULE_DONE);
1826                                                 ASTOBJ_UNLOCK(member);
1827                                                 ASTOBJ_UNLOCK(iterator);
1828                                         });
1829                                         ASTOBJ_CONTAINER_LINK(&jingle_list, member);
1830                                 } else {
1831                                         ASTOBJ_UNLOCK(member);
1832                                         ASTOBJ_UNREF(member, jingle_member_destroy);
1833                                 }
1834                         } else {
1835                                 ASTOBJ_UNLOCK(member);
1836                                 if (jingle_create_member(cat, var, allowguest, prefs, context, member))
1837                                         ASTOBJ_CONTAINER_LINK(&jingle_list, member);
1838                                 ASTOBJ_UNREF(member, jingle_member_destroy);
1839                         }
1840                 }
1841                 cat = ast_category_browse(cfg, cat);
1842         }
1843         jingle_free_candidates(global_candidates);
1844         return 1;
1845 }
1846
1847 /*! \brief Load module into PBX, register channel */
1848 static int load_module(void)
1849 {
1850         char *jabber_loaded = ast_module_helper("", "res_jabber.so", 0, 0, 0, 0);
1851         free(jabber_loaded);
1852         if (!jabber_loaded) {
1853                 /* Dependency module has a different name, if embedded */
1854                 jabber_loaded = ast_module_helper("", "res_jabber", 0, 0, 0, 0);
1855                 free(jabber_loaded);
1856                 if (!jabber_loaded) {
1857                         ast_log(LOG_ERROR, "chan_jingle.so depends upon res_jabber.so\n");
1858                         return AST_MODULE_LOAD_DECLINE;
1859                 }
1860         }
1861
1862         ASTOBJ_CONTAINER_INIT(&jingle_list);
1863         if (!jingle_load_config()) {
1864                 ast_log(LOG_ERROR, "Unable to read config file %s. Not loading module.\n", JINGLE_CONFIG);
1865                 return AST_MODULE_LOAD_DECLINE;
1866         }
1867
1868         sched = sched_context_create();
1869         if (!sched) 
1870                 ast_log(LOG_WARNING, "Unable to create schedule context\n");
1871
1872         io = io_context_create();
1873         if (!io) 
1874                 ast_log(LOG_WARNING, "Unable to create I/O context\n");
1875
1876         if (ast_find_ourip(&__ourip, bindaddr)) {
1877                 ast_log(LOG_WARNING, "Unable to get own IP address, Jingle disabled\n");
1878                 return 0;
1879         }
1880
1881         ast_rtp_proto_register(&jingle_rtp);
1882         ast_cli_register_multiple(jingle_cli, sizeof(jingle_cli) / sizeof(jingle_cli[0]));
1883         /* Make sure we can register our channel type */
1884         if (ast_channel_register(&jingle_tech)) {
1885                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
1886                 return -1;
1887         }
1888         return 0;
1889 }
1890
1891 /*! \brief Reload module */
1892 static int reload(void)
1893 {
1894         return 0;
1895 }
1896
1897 /*! \brief Unload the jingle channel from Asterisk */
1898 static int unload_module(void)
1899 {
1900         struct jingle_pvt *privates = NULL;
1901         ast_cli_unregister_multiple(jingle_cli, sizeof(jingle_cli) / sizeof(jingle_cli[0]));
1902         /* First, take us out of the channel loop */
1903         ast_channel_unregister(&jingle_tech);
1904         ast_rtp_proto_unregister(&jingle_rtp);
1905
1906         if (!ast_mutex_lock(&jinglelock)) {
1907                 /* Hangup all interfaces if they have an owner */
1908                 ASTOBJ_CONTAINER_TRAVERSE(&jingle_list, 1, {
1909                         ASTOBJ_WRLOCK(iterator);
1910                         privates = iterator->p;
1911                         while(privates) {
1912                                 if (privates->owner)
1913                                         ast_softhangup(privates->owner, AST_SOFTHANGUP_APPUNLOAD);
1914                                 privates = privates->next;
1915                         }
1916                         iterator->p = NULL;
1917                         ASTOBJ_UNLOCK(iterator);
1918                 });
1919                 ast_mutex_unlock(&jinglelock);
1920         } else {
1921                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
1922                 return -1;
1923         }
1924         ASTOBJ_CONTAINER_DESTROYALL(&jingle_list, jingle_member_destroy);
1925         ASTOBJ_CONTAINER_DESTROY(&jingle_list);
1926         return 0;
1927 }
1928
1929 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Jingle Channel Driver",
1930                 .load = load_module,
1931                 .unload = unload_module,
1932                 .reload = reload,
1933                );