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