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