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