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