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