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