Merge in VLDTMF support with Zaptel/Core done by the ever great Darumkilla Russell...
[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         ast_log(LOG_DEBUG, "The client is %s\n", client->name);
491         /* Make sure our new call doesn't exist yet */
492         for (tmp = client->p; tmp; tmp = tmp->next) {
493                 if (iks_find_with_attrib(pak->x, GOOGLE_NODE, GOOGLE_SID, tmp->sid))
494                         break;
495         }
496
497         if (tmp) {
498                 if (tmp->owner)
499                         ast_queue_control(tmp->owner, AST_CONTROL_ANSWER);
500         } else
501                 ast_log(LOG_NOTICE, "Whoa, didn't find call!\n");
502         jingle_response(client, pak, NULL, NULL);
503         return 1;
504 }
505
506 static int jingle_handle_dtmf(struct jingle *client, ikspak *pak)
507 {
508         struct jingle_pvt *tmp;
509         iks *dtmfnode = NULL;
510         char *dtmf;
511         /* Make sure our new call doesn't exist yet */
512         for (tmp = client->p; tmp; tmp = tmp->next) {
513                 if (iks_find_with_attrib(pak->x, GOOGLE_NODE, GOOGLE_SID, tmp->sid))
514                         break;
515         }
516
517         if (tmp) {
518                 if(iks_find_with_attrib(pak->x, "dtmf-method", "method", "rtp")) {
519                         jingle_response(client,pak,
520                                         "feature-not-implemented xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'",
521                                         "unsupported-dtmf-method xmlns='http://jabber.org/protocol/jingle/info/dtmf#errors'");
522                         return -1;
523                 }
524                 if ((dtmfnode  = iks_find(pak->x, "dtmf"))) {
525                         if((dtmf = iks_find_attrib(dtmfnode, "code"))) {
526                                 if(iks_find_with_attrib(pak->x, "dtmf", "action", "button-up")) {
527                                         struct ast_frame f = {AST_FRAME_DTMF_BEGIN, };
528                                         f.subclass = dtmf[0];
529                                         ast_queue_frame(tmp->owner, &f);
530                                         ast_verbose("JINGLE! DTMF-relay event received: %c\n", f.subclass);
531                                 } else if(iks_find_with_attrib(pak->x, "dtmf", "action", "button-down")) {
532                                         struct ast_frame f = {AST_FRAME_DTMF_END, };
533                                         f.subclass = dtmf[0];
534                                         ast_queue_frame(tmp->owner, &f);
535                                         ast_verbose("JINGLE! DTMF-relay event received: %c\n", f.subclass);
536                                 } else if(iks_find_attrib(pak->x, "dtmf")) { /* 250 millasecond default */
537                                         struct ast_frame f = {AST_FRAME_DTMF, };
538                                         f.subclass = dtmf[0];
539                                         ast_queue_frame(tmp->owner, &f);
540                                         ast_verbose("JINGLE! DTMF-relay event received: %c\n", f.subclass);
541                                 }
542                         }
543                 }
544                 jingle_response(client, pak, NULL, NULL);
545                 return 1;
546         } else
547                 ast_log(LOG_NOTICE, "Whoa, didn't find call!\n");
548
549         jingle_response(client, pak, NULL, NULL);
550         return 1;
551 }
552
553
554 static int jingle_hangup_farend(struct jingle *client, ikspak *pak)
555 {
556         struct jingle_pvt *tmp;
557
558         ast_log(LOG_DEBUG, "The client is %s\n", client->name);
559         /* Make sure our new call doesn't exist yet */
560         for (tmp = client->p; tmp; tmp = tmp->next) {
561                 if (iks_find_with_attrib(pak->x, GOOGLE_NODE, GOOGLE_SID, tmp->sid))
562                         break;
563         }
564
565         if (tmp) {
566                 tmp->alreadygone = 1;
567                 ast_queue_hangup(tmp->owner);
568         } else
569                 ast_log(LOG_NOTICE, "Whoa, didn't find call!\n");
570         jingle_response(client, pak, NULL, NULL);
571         return 1;
572 }
573
574 static int jingle_create_candidates(struct jingle *client, struct jingle_pvt *p, char *sid, char *from)
575 {
576         struct jingle_candidate *tmp;
577         struct aji_client *c = client->connection;
578         struct jingle_candidate *ours1 = NULL, *ours2 = NULL;
579         struct sockaddr_in sin;
580         struct sockaddr_in dest;
581         struct in_addr us;
582         iks *iq, *jingle, *candidate;
583         char user[17], pass[17], preference[5], port[7];
584
585
586         iq = iks_new("iq");
587         jingle = iks_new(GOOGLE_NODE);
588         candidate = iks_new("candidate");
589         if (!iq || !jingle || !candidate) {
590                 ast_log(LOG_ERROR, "Memory allocation error\n");
591                 goto safeout;
592         }
593         ours1 = ast_calloc(1, sizeof(*ours1));
594         ours2 = ast_calloc(1, sizeof(*ours2));
595         if (!ours1 || !ours2)
596                 goto safeout;
597         iks_insert_node(iq, jingle);
598         iks_insert_node(jingle, candidate);
599
600         for (; p; p = p->next) {
601                 if (!strcasecmp(p->sid, sid))
602                         break;
603         }
604
605         if (!p) {
606                 ast_log(LOG_NOTICE, "No matching jingle session - SID %s!\n", sid);
607                 goto safeout;
608         }
609
610         ast_rtp_get_us(p->rtp, &sin);
611         ast_find_ourip(&us, bindaddr);
612
613         /* Setup our jingle candidates */
614         ast_copy_string(ours1->name, "rtp", sizeof(ours1->name));
615         ours1->port = ntohs(sin.sin_port);
616         ours1->preference = 1;
617         snprintf(user, sizeof(user), "%08lx%08lx", ast_random(), ast_random());
618         snprintf(pass, sizeof(pass), "%08lx%08lx", ast_random(), ast_random());
619         ast_copy_string(ours1->username, user, sizeof(ours1->username));
620         ast_copy_string(ours1->password, pass, sizeof(ours1->password));
621         ast_copy_string(ours1->ip, ast_inet_ntoa(us), sizeof(ours1->ip));
622         ours1->protocol = AJI_PROTOCOL_UDP;
623         ours1->type = AJI_CONNECT_LOCAL;
624         ours1->generation = 0;
625         p->ourcandidates = ours1;
626
627         if (!ast_strlen_zero(externip)) {
628                 /* XXX We should really stun for this one not just go with externip XXX */
629                 snprintf(user, sizeof(user), "%08lx%08lx", ast_random(), ast_random());
630                 snprintf(pass, sizeof(pass), "%08lx%08lx", ast_random(), ast_random());
631                 ast_copy_string(ours2->username, user, sizeof(ours2->username));
632                 ast_copy_string(ours2->password, pass, sizeof(ours2->password));
633                 ast_copy_string(ours2->ip, externip, sizeof(ours2->ip));
634                 ast_copy_string(ours2->name, "rtp", sizeof(ours1->name));
635                 ours2->port = ntohs(sin.sin_port);
636                 ours2->preference = 0.9;
637                 ours2->protocol = AJI_PROTOCOL_UDP;
638                 ours2->type = AJI_CONNECT_STUN;
639                 ours2->generation = 0;
640                 ours1->next = ours2;
641                 ours2 = NULL;
642         }
643         ours1 = NULL;
644         dest.sin_addr = __ourip;
645         dest.sin_port = sin.sin_port;
646
647
648         for (tmp = p->ourcandidates; tmp; tmp = tmp->next) {
649                 snprintf(port, sizeof(port), "%d", tmp->port);
650                 snprintf(preference, sizeof(preference), "%.2f", tmp->preference);
651                 iks_insert_attrib(iq, "from", c->jid->full);
652                 iks_insert_attrib(iq, "to", from);
653                 iks_insert_attrib(iq, "type", "set");
654                 iks_insert_attrib(iq, "id", c->mid);
655                 ast_aji_increment_mid(c->mid);
656                 iks_insert_attrib(jingle, "type", "candidates");
657                 iks_insert_attrib(jingle, "id", sid);
658                 iks_insert_attrib(jingle, "initiator", (p->initiator) ? c->jid->full : from);
659                 iks_insert_attrib(jingle, "xmlns", GOOGLE_NS);
660                 iks_insert_attrib(candidate, "name", tmp->name);
661                 iks_insert_attrib(candidate, "address", tmp->ip);
662                 iks_insert_attrib(candidate, "port", port);
663                 iks_insert_attrib(candidate, "username", tmp->username);
664                 iks_insert_attrib(candidate, "password", tmp->password);
665                 iks_insert_attrib(candidate, "preference", preference);
666                 if (tmp->protocol == AJI_PROTOCOL_UDP)
667                         iks_insert_attrib(candidate, "protocol", "udp");
668                 if (tmp->protocol == AJI_PROTOCOL_SSLTCP)
669                         iks_insert_attrib(candidate, "protocol", "ssltcp");
670                 if (tmp->type == AJI_CONNECT_STUN)
671                         iks_insert_attrib(candidate, "type", "stun");
672                 if (tmp->type == AJI_CONNECT_LOCAL)
673                         iks_insert_attrib(candidate, "type", "local");
674                 if (tmp->type == AJI_CONNECT_RELAY)
675                         iks_insert_attrib(candidate, "type", "relay");
676                 iks_insert_attrib(candidate, "network", "0");
677                 iks_insert_attrib(candidate, "generation", "0");
678                 iks_send(c->p, iq);
679         }
680         p->laststun = 0;
681
682 safeout:
683         if (ours1)
684                 free(ours1);
685         if (ours2)
686                 free(ours2);
687         if (iq)
688                 iks_delete(iq);
689         if (jingle)
690                 iks_delete(jingle);
691         if (candidate)
692                 iks_delete(candidate);
693         return 1;
694 }
695
696 static struct jingle_pvt *jingle_alloc(struct jingle *client, const char *from, const char *sid)
697 {
698         struct jingle_pvt *tmp = NULL;
699         struct aji_resource *resources = NULL;
700         struct aji_buddy *buddy;
701         char idroster[200];
702
703         if (option_debug)
704                 ast_log(LOG_DEBUG, "The client is %s for alloc\n", client->name);
705         if (!sid && !strchr(from, '/')) {       /* I started call! */
706                 if (!strcasecmp(client->name, "guest")) {
707                         buddy = ASTOBJ_CONTAINER_FIND(&client->connection->buddies, from);
708                         if (buddy)
709                                 resources = buddy->resources;
710                 } else 
711                         resources = client->buddy->resources;
712                 while (resources) {
713                         if (resources->cap->jingle) {
714                                 break;
715                         }
716                         resources = resources->next;
717                 }
718                 if (resources)
719                         snprintf(idroster, sizeof(idroster), "%s/%s", from, resources->resource);
720                 else {
721                         ast_log(LOG_ERROR, "no jingle capable clients to talk to.\n");
722                         return NULL;
723                 }
724         }
725         if (!(tmp = ast_calloc(1, sizeof(*tmp)))) {
726                 return NULL;
727         }
728         if (sid) {
729                 ast_copy_string(tmp->sid, sid, sizeof(tmp->sid));
730                 ast_copy_string(tmp->from, from, sizeof(tmp->from));
731         } else {
732                 snprintf(tmp->sid, sizeof(tmp->sid), "%08lx%08lx", ast_random(), ast_random());
733                 ast_copy_string(tmp->from, idroster, sizeof(tmp->from));
734                 tmp->initiator = 1;
735         }
736         tmp->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
737         tmp->parent = client;
738         if (!tmp->rtp) {
739                 ast_log(LOG_WARNING, "Out of RTP sessions?\n");
740                 free(tmp);
741                 return NULL;
742         }
743         ast_copy_string(tmp->exten, "s", sizeof(tmp->exten));
744         ast_mutex_init(&tmp->lock);
745         ast_mutex_lock(&jinglelock);
746         tmp->next = client->p;
747         client->p = tmp;
748         ast_mutex_unlock(&jinglelock);
749         return tmp;
750 }
751
752 /*! \brief Start new jingle channel */
753 static struct ast_channel *jingle_new(struct jingle *client, struct jingle_pvt *i, int state, const char *title)
754 {
755         struct ast_channel *tmp;
756         int fmt;
757         int what;
758
759         tmp = ast_channel_alloc(1);
760         if (!tmp) {
761                 ast_log(LOG_WARNING, "Unable to allocate Jingle channel structure!\n");
762                 return NULL;
763         }
764         tmp->tech = &jingle_tech;
765
766         /* Select our native format based on codec preference until we receive
767            something from another device to the contrary. */
768         if (i->jointcapability)
769                 what = i->jointcapability;
770         else if (i->capability)
771                 what = i->capability;
772         else
773                 what = global_capability;
774         tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | (i->jointcapability & AST_FORMAT_VIDEO_MASK);
775         fmt = ast_best_codec(tmp->nativeformats);
776
777         if (title)
778                 ast_string_field_build(tmp, name, "Jingle/%s-%04lx", title, ast_random() & 0xffff);
779         else
780                 ast_string_field_build(tmp, name, "Jingle/%s-%04lx", i->from, ast_random() & 0xffff);
781
782         if (i->rtp) {
783                 tmp->fds[0] = ast_rtp_fd(i->rtp);
784                 tmp->fds[1] = ast_rtcp_fd(i->rtp);
785         }
786         if (i->vrtp) {
787                 tmp->fds[2] = ast_rtp_fd(i->vrtp);
788                 tmp->fds[3] = ast_rtcp_fd(i->vrtp);
789         }
790         if (state == AST_STATE_RING)
791                 tmp->rings = 1;
792         tmp->adsicpe = AST_ADSI_UNAVAILABLE;
793         tmp->writeformat = fmt;
794         tmp->rawwriteformat = fmt;
795         tmp->readformat = fmt;
796         tmp->rawreadformat = fmt;
797         tmp->tech_pvt = i;
798
799         tmp->callgroup = client->callgroup;
800         tmp->pickupgroup = client->pickupgroup;
801         tmp->cid.cid_pres = client->callingpres;
802         if (!ast_strlen_zero(client->accountcode))
803                 ast_string_field_set(tmp, accountcode, client->accountcode);
804         if (client->amaflags)
805                 tmp->amaflags = client->amaflags;
806         if (!ast_strlen_zero(client->language))
807                 ast_string_field_set(tmp, language, client->language);
808         if (!ast_strlen_zero(client->musicclass))
809                 ast_string_field_set(tmp, musicclass, client->musicclass);
810         i->owner = tmp;
811         ast_mutex_lock(&usecnt_lock);
812         usecnt++;
813         ast_mutex_unlock(&usecnt_lock);
814         ast_copy_string(tmp->context, client->context, sizeof(tmp->context));
815         ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
816         ast_set_callerid(tmp, i->cid_num, i->cid_name, i->cid_num);
817         if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
818                 tmp->cid.cid_dnid = ast_strdup(i->exten);
819         tmp->priority = 1;
820         ast_setstate(tmp, state);
821         if (i->rtp)
822                 ast_jb_configure(tmp, &global_jbconf);
823         if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
824                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
825                 tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
826                 ast_hangup(tmp);
827                 tmp = NULL;
828         }
829
830         return tmp;
831 }
832
833 static int jingle_action(struct jingle *client, struct jingle_pvt *p, const char *action)
834 {
835         iks *request, *session = NULL;
836         int res = -1;
837
838         request = iks_new("iq");
839         if (request) {
840                 iks_insert_attrib(request, "type", "set");
841                 iks_insert_attrib(request, "from", client->connection->jid->full);
842                 iks_insert_attrib(request, "to", p->from);
843                 iks_insert_attrib(request, "id", client->connection->mid);
844                 ast_aji_increment_mid(client->connection->mid);
845                 session = iks_new("session");
846                 if (session) {
847                         iks_insert_attrib(session, "type", action);
848                         iks_insert_attrib(session, "id", p->sid);
849                         iks_insert_attrib(session, "initiator",
850                                                           p->initiator ? client->connection->jid->full : p->from);
851                         iks_insert_attrib(session, "xmlns", "http://www.google.com/session");
852                         iks_insert_node(request, session);
853                         iks_send(client->connection->p, request);
854                         iks_delete(session);
855                         res = 0;
856                 }
857                 iks_delete(request);
858         }
859         return res;
860 }
861
862 static void jingle_free_candidates(struct jingle_candidate *candidate)
863 {
864         struct jingle_candidate *last;
865         while (candidate) {
866                 last = candidate;
867                 candidate = candidate->next;
868                 free(last);
869         }
870 }
871
872 static void jingle_free_pvt(struct jingle *client, struct jingle_pvt *p)
873 {
874         struct jingle_pvt *cur, *prev = NULL;
875         cur = client->p;
876         while (cur) {
877                 if (cur == p) {
878                         if (prev)
879                                 prev->next = p->next;
880                         else
881                                 client->p = p->next;
882                         break;
883                 }
884                 prev = cur;
885                 cur = cur->next;
886         }
887         if (p->ringrule)
888                 iks_filter_remove_rule(p->parent->connection->f, p->ringrule);
889         if (p->owner)
890                 ast_log(LOG_WARNING, "Uh oh, there's an owner, this is going to be messy.\n");
891         if (p->rtp)
892                 ast_rtp_destroy(p->rtp);
893         if (p->vrtp)
894                 ast_rtp_destroy(p->vrtp);
895         jingle_free_candidates(p->theircandidates);
896         free(p);
897 }
898
899
900 static int jingle_newcall(struct jingle *client, ikspak *pak)
901 {
902         struct jingle_pvt *p, *tmp = client->p;
903         struct ast_channel *chan;
904         int res;
905         iks *codec;
906
907         /* Make sure our new call doesn't exist yet */
908         while (tmp) {
909                 if (iks_find_with_attrib(pak->x, GOOGLE_NODE, GOOGLE_SID, tmp->sid)) {
910                         ast_log(LOG_NOTICE, "Ignoring duplicate call setup on SID %s\n", tmp->sid);
911                         jingle_response(client, pak, "out-of-order", NULL);
912                         return -1;
913                 }
914                 tmp = tmp->next;
915         }
916
917         p = jingle_alloc(client, pak->from->partial, iks_find_attrib(pak->query, GOOGLE_SID));
918         if (!p) {
919                 ast_log(LOG_WARNING, "Unable to allocate jingle structure!\n");
920                 return -1;
921         }
922         chan = jingle_new(client, p, AST_STATE_DOWN, pak->from->user);
923         if (chan) {
924                 ast_mutex_lock(&p->lock);
925                 ast_copy_string(p->from, pak->from->full, sizeof(p->from));
926                 if (iks_find_attrib(pak->query, GOOGLE_SID)) {
927                         ast_copy_string(p->sid, iks_find_attrib(pak->query, GOOGLE_SID),
928                                                         sizeof(p->sid));
929                 }
930
931                 codec = iks_child(iks_child(iks_child(pak->x)));
932                 while (codec) {
933                         ast_rtp_set_m_type(p->rtp, atoi(iks_find_attrib(codec, "id")));
934                         ast_rtp_set_rtpmap_type(p->rtp, atoi(iks_find_attrib(codec, "id")), "audio",
935                                                 iks_find_attrib(codec, "name"), 0);
936                         codec = iks_next(codec);
937                 }
938                 
939                 ast_mutex_unlock(&p->lock);
940                 ast_setstate(chan, AST_STATE_RING);
941                 res = ast_pbx_start(chan);
942
943                 switch (res) {
944                 case AST_PBX_FAILED:
945                         ast_log(LOG_WARNING, "Failed to start PBX :(\n");
946                         jingle_response(client, pak, "service-unavailable", NULL);
947                         break;
948                 case AST_PBX_CALL_LIMIT:
949                         ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
950                         jingle_response(client, pak, "service-unavailable", NULL);
951                         break;
952                 case AST_PBX_SUCCESS:
953                         jingle_response(client, pak, NULL, NULL);
954                         jingle_create_candidates(client, p,
955                                         iks_find_attrib(pak->query, GOOGLE_SID),
956                                         iks_find_attrib(pak->x, "from"));
957                         /* nothing to do */
958                         break;
959                 }
960         } else {
961                 jingle_free_pvt(client, p);
962         }
963         return 1;
964 }
965
966 static int jingle_update_stun(struct jingle *client, struct jingle_pvt *p)
967 {
968         struct jingle_candidate *tmp;
969         struct hostent *hp;
970         struct ast_hostent ahp;
971         struct sockaddr_in sin;
972
973         if (time(NULL) == p->laststun)
974                 return 0;
975
976         tmp = p->theircandidates;
977         p->laststun = time(NULL);
978         while (tmp) {
979                 char username[256];
980                 hp = ast_gethostbyname(tmp->ip, &ahp);
981                 sin.sin_family = AF_INET;
982                 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
983                 sin.sin_port = htons(tmp->port);
984                 snprintf(username, sizeof(username), "%s%s", tmp->username,
985                                  p->ourcandidates->username);
986
987                 ast_rtp_stun_request(p->rtp, &sin, username);
988                 tmp = tmp->next;
989         }
990         return 1;
991 }
992
993 static int jingle_add_candidate(struct jingle *client, ikspak *pak)
994 {
995         struct jingle_pvt *p = NULL, *tmp = NULL;
996         struct aji_client *c = client->connection;
997         struct jingle_candidate *newcandidate = NULL;
998         iks  *traversenodes = NULL, *receipt = NULL;
999         newcandidate = ast_calloc(1, sizeof(*newcandidate));
1000         if (!newcandidate)
1001                 return 0;
1002         for (tmp = client->p; tmp; tmp = tmp->next) {
1003                 if (iks_find_with_attrib(pak->x, GOOGLE_NODE, GOOGLE_SID, tmp->sid)) {
1004                         p = tmp;
1005                         break;
1006                 }
1007         }
1008
1009         if (!p)
1010                 return -1;
1011
1012         traversenodes = pak->query;
1013         while(traversenodes) {
1014                 if(!strcasecmp(iks_name(traversenodes), "session")) {
1015                         traversenodes = iks_child(traversenodes);
1016                         continue;
1017                 }
1018                 if(!strcasecmp(iks_name(traversenodes), "candidate")) {
1019                         newcandidate = ast_calloc(1, sizeof(*newcandidate));
1020                         if (!newcandidate)
1021                                 return 0;
1022                         ast_copy_string(newcandidate->name, iks_find_attrib(traversenodes, "name"),
1023                                                         sizeof(newcandidate->name));
1024                         ast_copy_string(newcandidate->ip, iks_find_attrib(traversenodes, "address"),
1025                                                         sizeof(newcandidate->ip));
1026                         newcandidate->port = atoi(iks_find_attrib(traversenodes, "port"));
1027                         ast_copy_string(newcandidate->username, iks_find_attrib(traversenodes, "username"),
1028                                                         sizeof(newcandidate->username));
1029                         ast_copy_string(newcandidate->password, iks_find_attrib(traversenodes, "password"),
1030                                                         sizeof(newcandidate->password));
1031                         newcandidate->preference = atof(iks_find_attrib(traversenodes, "preference"));
1032                         if (!strcasecmp(iks_find_attrib(traversenodes, "protocol"), "udp"))
1033                                 newcandidate->protocol = AJI_PROTOCOL_UDP;
1034                         if (!strcasecmp(iks_find_attrib(traversenodes, "protocol"), "ssltcp"))
1035                                 newcandidate->protocol = AJI_PROTOCOL_SSLTCP;
1036                 
1037                         if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "stun"))
1038                                 newcandidate->type = AJI_CONNECT_STUN;
1039                         if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "local"))
1040                                 newcandidate->type = AJI_CONNECT_LOCAL;
1041                         if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "relay"))
1042                                 newcandidate->type = AJI_CONNECT_RELAY;
1043                         ast_copy_string(newcandidate->network, iks_find_attrib(traversenodes, "network"),
1044                                                         sizeof(newcandidate->network));
1045                         newcandidate->generation = atoi(iks_find_attrib(traversenodes, "generation"));
1046                         newcandidate->next = NULL;
1047                 
1048                         newcandidate->next = p->theircandidates;
1049                         p->theircandidates = newcandidate;
1050                         p->laststun = 0;
1051                         jingle_update_stun(p->parent, p);
1052                         newcandidate = NULL;
1053                 }
1054                 traversenodes = iks_next(traversenodes);
1055         }
1056         
1057         receipt = iks_new("iq");
1058         iks_insert_attrib(receipt, "type", "result");
1059         iks_insert_attrib(receipt, "from", c->jid->full);
1060         iks_insert_attrib(receipt, "to", iks_find_attrib(pak->x, "from"));
1061         iks_insert_attrib(receipt, "id", iks_find_attrib(pak->x, "id"));
1062         iks_send(c->p, receipt);
1063         iks_delete(receipt);
1064
1065         return 1;
1066 }
1067
1068 static struct ast_frame *jingle_rtp_read(struct ast_channel *ast, struct jingle_pvt *p)
1069 {
1070         struct ast_frame *f;
1071
1072         if (!p->rtp)
1073                 return &ast_null_frame;
1074         f = ast_rtp_read(p->rtp);
1075         jingle_update_stun(p->parent, p);
1076         if (p->owner) {
1077                 /* We already hold the channel lock */
1078                 if (f->frametype == AST_FRAME_VOICE) {
1079                         if (f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
1080                                 if (option_debug)
1081                                         ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
1082                                 p->owner->nativeformats =
1083                                         (p->owner->nativeformats & AST_FORMAT_VIDEO_MASK) | f->subclass;
1084                                 ast_set_read_format(p->owner, p->owner->readformat);
1085                                 ast_set_write_format(p->owner, p->owner->writeformat);
1086                         }
1087 /*                      if ((ast_test_flag(p, SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
1088                                 f = ast_dsp_process(p->owner, p->vad, f);
1089                                 if (option_debug && f && (f->frametype == AST_FRAME_DTMF))
1090                                         ast_log(LOG_DEBUG, "* Detected inband DTMF '%c'\n", f->subclass);
1091                         } */
1092                 }
1093         }
1094         return f;
1095 }
1096
1097 static struct ast_frame *jingle_read(struct ast_channel *ast)
1098 {
1099         struct ast_frame *fr;
1100         struct jingle_pvt *p = ast->tech_pvt;
1101
1102         ast_mutex_lock(&p->lock);
1103         fr = jingle_rtp_read(ast, p);
1104         ast_mutex_unlock(&p->lock);
1105         return fr;
1106 }
1107
1108 /*! \brief Send frame to media channel (rtp) */
1109 static int jingle_write(struct ast_channel *ast, struct ast_frame *frame)
1110 {
1111         struct jingle_pvt *p = ast->tech_pvt;
1112         int res = 0;
1113
1114         switch (frame->frametype) {
1115         case AST_FRAME_VOICE:
1116                 if (!(frame->subclass & ast->nativeformats)) {
1117                         ast_log(LOG_WARNING,
1118                                         "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
1119                                         frame->subclass, ast->nativeformats, ast->readformat,
1120                                         ast->writeformat);
1121                         return 0;
1122                 }
1123                 if (p) {
1124                         ast_mutex_lock(&p->lock);
1125                         if (p->rtp) {
1126                                 res = ast_rtp_write(p->rtp, frame);
1127                         }
1128                         ast_mutex_unlock(&p->lock);
1129                 }
1130                 break;
1131         case AST_FRAME_VIDEO:
1132                 if (p) {
1133                         ast_mutex_lock(&p->lock);
1134                         if (p->vrtp) {
1135                                 res = ast_rtp_write(p->vrtp, frame);
1136                         }
1137                         ast_mutex_unlock(&p->lock);
1138                 }
1139                 break;
1140         case AST_FRAME_IMAGE:
1141                 return 0;
1142                 break;
1143         default:
1144                 ast_log(LOG_WARNING, "Can't send %d type frames with Jingle write\n",
1145                                 frame->frametype);
1146                 return 0;
1147         }
1148
1149         return res;
1150 }
1151
1152 static int jingle_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1153 {
1154         struct jingle_pvt *p = newchan->tech_pvt;
1155         ast_mutex_lock(&p->lock);
1156
1157         if ((p->owner != oldchan)) {
1158                 ast_mutex_unlock(&p->lock);
1159                 return -1;
1160         }
1161         if (p->owner == oldchan)
1162                 p->owner = newchan;
1163         ast_mutex_unlock(&p->lock);
1164         return 0;
1165 }
1166
1167 static int jingle_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
1168 {
1169         int res = 0;
1170
1171         switch (condition) {
1172         case AST_CONTROL_HOLD:
1173                 ast_moh_start(ast, data, NULL);
1174                 break;
1175         case AST_CONTROL_UNHOLD:
1176                 ast_moh_stop(ast);
1177                 break;
1178         default:
1179                 ast_log(LOG_NOTICE, "Don't know how to indicate condition '%d'\n", condition);
1180                 res = -1;
1181         }
1182
1183         return res;
1184 }
1185
1186 static int jingle_digit_begin(struct ast_channel *chan, char digit)
1187 {
1188         /* XXX Does jingle have a concept of the length of a dtmf digit ? */
1189         return 0;
1190 }
1191
1192 static int jingle_digit_end(struct ast_channel *ast, char digit)
1193 {
1194         struct jingle_pvt *p = ast->tech_pvt;
1195         struct jingle *client = p->parent;
1196         iks *iq, *jingle, *dtmf;
1197         char buffer[2] = {digit, '\0'};
1198         iq = iks_new("iq");
1199         jingle = iks_new("jingle");
1200         dtmf = iks_new("dtmf");
1201         if(!iq || !jingle || !dtmf) {
1202                 if(iq)
1203                         iks_delete(iq);
1204                 if(jingle)
1205                         iks_delete(jingle);
1206                 if(dtmf)
1207                         iks_delete(dtmf);
1208                 ast_log(LOG_ERROR, "Did not send dtmf do to memory issue\n");
1209                 return -1;
1210         }
1211
1212         iks_insert_attrib(iq, "type", "set");
1213         iks_insert_attrib(iq, "to", p->from);
1214         iks_insert_attrib(iq, "from", client->connection->jid->full);
1215         iks_insert_attrib(iq, "id", client->connection->mid);
1216         ast_aji_increment_mid(client->connection->mid);
1217         iks_insert_attrib(jingle, "xmlns", "http://jabber.org/protocol/jingle");
1218         iks_insert_attrib(jingle, "action", "content-info");
1219         iks_insert_attrib(jingle, "initiator", p->initiator ? client->connection->jid->full : p->from);
1220         iks_insert_attrib(jingle, "sid", p->sid);
1221         iks_insert_attrib(dtmf, "xmlns", "http://jabber.org/protocol/jingle/info/dtmf");
1222         iks_insert_attrib(dtmf, "code", buffer);
1223         iks_insert_node(iq, jingle);
1224         iks_insert_node(jingle, dtmf);
1225
1226         ast_mutex_lock(&p->lock);
1227         if(ast->dtmff.frametype == AST_FRAME_DTMF) {
1228                 ast_verbose("Sending 250ms dtmf!\n");
1229         } else if (ast->dtmff.frametype == AST_FRAME_DTMF_BEGIN) {
1230                 iks_insert_attrib(dtmf, "action", "button-down");
1231         } else if (ast->dtmff.frametype == AST_FRAME_DTMF_END) {
1232                 iks_insert_attrib(dtmf, "action", "button-up");
1233         }
1234         iks_send(client->connection->p, iq);
1235         iks_delete(iq);
1236         iks_delete(jingle);
1237         iks_delete(dtmf);
1238         ast_mutex_unlock(&p->lock);
1239         return 0;
1240 }
1241
1242 static int jingle_sendhtml(struct ast_channel *ast, int subclass, const char *data, int datalen)
1243 {
1244         ast_log(LOG_NOTICE, "XXX Implement jingle sendhtml XXX\n");
1245
1246         return -1;
1247 }
1248 static int jingle_transmit_invite(struct jingle_pvt *p)
1249 {
1250         struct jingle *jingle = NULL;
1251         struct aji_client *client = NULL;
1252         iks *iq, *desc, *session;
1253         iks *payload_eg711u, *payload_pcmu;
1254
1255         jingle = p->parent;
1256         client = jingle->connection;
1257         iq = iks_new("iq");
1258         desc = iks_new("description");
1259         session = iks_new("session");
1260         iks_insert_attrib(iq, "type", "set");
1261         iks_insert_attrib(iq, "to", p->from);
1262         iks_insert_attrib(iq, "from", client->jid->full);
1263         iks_insert_attrib(iq, "id", client->mid);
1264         ast_aji_increment_mid(client->mid);
1265         iks_insert_attrib(session, "type", "initiate");
1266         iks_insert_attrib(session, "id", p->sid);
1267         iks_insert_attrib(session, "initiator", client->jid->full);
1268         iks_insert_attrib(session, "xmlns", "http://www.google.com/session");
1269         iks_insert_attrib(desc, "xmlns", "http://www.google.com/session/phone");
1270         payload_pcmu = iks_new("payload-type");
1271         iks_insert_attrib(payload_pcmu, "id", "0");
1272         iks_insert_attrib(payload_pcmu, "name", "PCMU");
1273         payload_eg711u = iks_new("payload-type");
1274         iks_insert_attrib(payload_eg711u, "id", "100");
1275         iks_insert_attrib(payload_eg711u, "name", "EG711U");
1276         iks_insert_node(desc, payload_pcmu);
1277         iks_insert_node(desc, payload_eg711u);
1278         iks_insert_node(iq, session);
1279         iks_insert_node(session, desc);
1280         iks_send(client->p, iq);
1281         iks_delete(iq);
1282         iks_delete(desc);
1283         iks_delete(session);
1284         iks_delete(payload_eg711u);
1285         iks_delete(payload_pcmu);
1286         return 0;
1287 }
1288
1289 /* Not in use right now.
1290 static int jingle_auto_congest(void *nothing)
1291 {
1292         struct jingle_pvt *p = nothing;
1293
1294         ast_mutex_lock(&p->lock);
1295         if (p->owner) {
1296                 if (!ast_channel_trylock(p->owner)) {
1297                         ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
1298                         ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
1299                         ast_channel_unlock(p->owner);
1300                 }
1301         }
1302         ast_mutex_unlock(&p->lock);
1303         return 0;
1304 }
1305 */
1306
1307 /*! \brief Initiate new call, part of PBX interface 
1308  *      dest is the dial string */
1309 static int jingle_call(struct ast_channel *ast, char *dest, int timeout)
1310 {
1311         struct jingle_pvt *p = ast->tech_pvt;
1312
1313         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
1314                 ast_log(LOG_WARNING, "jingle_call called on %s, neither down nor reserved\n", ast->name);
1315                 return -1;
1316         }
1317
1318         ast_setstate(ast, AST_STATE_RING);
1319         p->jointcapability = p->capability;
1320         if (!p->ringrule) {
1321                 ast_copy_string(p->ring, p->parent->connection->mid, sizeof(p->ring));
1322                 p->ringrule = iks_filter_add_rule(p->parent->connection->f, jingle_ringing_ack, p,
1323                                                         IKS_RULE_ID, p->ring, IKS_RULE_DONE);
1324         } else
1325                 ast_log(LOG_WARNING, "Whoa, already have a ring rule!\n");
1326
1327         jingle_transmit_invite(p);
1328         jingle_create_candidates(p->parent, p, p->sid, p->from);
1329
1330         return 0;
1331 }
1332
1333 /*! \brief Hangup a call through the jingle proxy channel */
1334 static int jingle_hangup(struct ast_channel *ast)
1335 {
1336         struct jingle_pvt *p = ast->tech_pvt;
1337         struct jingle *client;
1338
1339         ast_mutex_lock(&p->lock);
1340         client = p->parent;
1341         p->owner = NULL;
1342         ast->tech_pvt = NULL;
1343         if (!p->alreadygone)
1344                 jingle_action(client, p, "terminate");
1345         ast_mutex_unlock(&p->lock);
1346
1347         jingle_free_pvt(client, p);
1348         ast_mutex_lock(&usecnt_lock);
1349         usecnt--;
1350         ast_mutex_unlock(&usecnt_lock);
1351
1352         return 0;
1353 }
1354
1355 /*! \brief Part of PBX interface */
1356 static struct ast_channel *jingle_request(const char *type, int format, void *data, int *cause)
1357 {
1358         struct jingle_pvt *p = NULL;
1359         struct jingle *client = NULL;
1360         char *sender = NULL, *to = NULL, *s = NULL;
1361         struct ast_channel *chan = NULL;
1362
1363         if (data) {
1364                 s = ast_strdupa((char *) data);
1365                 if (s) {
1366                         sender = strsep(&s, "/");
1367                         if (sender && (sender[0] != '\0'))
1368                                 to = strsep(&s, "/");
1369                         if (!to) {
1370                                 ast_log(LOG_ERROR, "Bad arguments in Jingle Dialstring: %s\n", (char*) data);
1371                                 if (s)
1372                                         free(s);
1373                                 return NULL;
1374                         }
1375                 }
1376         }
1377         client = find_jingle(to, sender);
1378         if (!client) {
1379                 ast_log(LOG_WARNING, "Could not find recipient.\n");
1380                 if (s)
1381                         free(s);
1382                 return NULL;
1383         }
1384         p = jingle_alloc(client, to, NULL);
1385         if (p)
1386                 chan = jingle_new(client, p, AST_STATE_DOWN, to);
1387
1388         return chan;
1389 }
1390
1391 #if 0
1392 /*! \brief CLI command "jingle show channels" */
1393 static int jingle_show(int fd, int argc, char **argv)
1394 {
1395         struct jingle_pvt *p = NULL;
1396         struct jingle *peer = NULL;
1397         struct jingle_candidate *tmp;
1398         struct jingle *client = NULL;
1399         client = ast_aji_get_client("asterisk");
1400         if (argc != 3)
1401                 return RESULT_SHOWUSAGE;
1402         ast_mutex_lock(&jinglelock);
1403         if (client)
1404                 p = jingles->p;
1405         while (p) {
1406                 ast_mutex_lock(&p->lock);
1407                 ast_cli(fd, "SID = %s\n", p->sid);
1408                 tmp = p->candidates;
1409                 while (tmp) {
1410                         ast_verbose("port %d\n", tmp->port);
1411                         tmp = tmp->next;
1412                 }
1413                 ast_mutex_unlock(&p->lock);
1414                 p = p->next;
1415         }
1416         if (!jingles->p)
1417                 ast_cli(fd, "No jingle channels in use\n");
1418         ast_mutex_unlock(&jinglelock);
1419         return RESULT_SUCCESS;
1420 }
1421 #endif
1422
1423 static int jingle_parser(void *data, ikspak *pak)
1424 {
1425         struct jingle *client = ASTOBJ_REF((struct jingle *) data);
1426
1427         if (iks_find_with_attrib(pak->x, GOOGLE_NODE, "type", JINGLE_INITIATE)) {
1428                 /* New call */
1429                 jingle_newcall(client, pak);
1430         } else if (iks_find_with_attrib(pak->x, GOOGLE_NODE, "type", GOOGLE_NEGOTIATE)) {
1431                 if (option_debug > 2)
1432                         ast_log(LOG_DEBUG, "About to add candidate!\n");
1433                 jingle_add_candidate(client, pak);
1434                 if (option_debug > 2)
1435                         ast_log(LOG_DEBUG, "Candidate Added!\n");
1436         } else if (iks_find_with_attrib(pak->x, GOOGLE_NODE, "type", GOOGLE_ACCEPT)) {
1437                 jingle_is_answered(client, pak);
1438         } else if (iks_find_with_attrib(pak->x, GOOGLE_NODE, "type", "content-info")) {
1439                 jingle_handle_dtmf(client, pak);
1440         } else if (iks_find_with_attrib(pak->x, GOOGLE_NODE, "type", "terminate")) {
1441                 jingle_hangup_farend(client, pak);
1442         } else if (iks_find_with_attrib(pak->x, GOOGLE_NODE, "type", "reject")) {
1443                 jingle_hangup_farend(client, pak);
1444         }
1445         ASTOBJ_UNREF(client, jingle_member_destroy);
1446         return IKS_FILTER_EAT;
1447 }
1448 /* Not using this anymore probably take out soon 
1449 static struct jingle_candidate *jingle_create_candidate(char *args)
1450 {
1451         char *name, *type, *preference, *protocol;
1452         struct jingle_candidate *res;
1453         res = malloc(sizeof(struct jingle_candidate));
1454         memset(res, 0, sizeof(struct jingle_candidate));
1455         if (args)
1456                 name = args;
1457         if ((args = strchr(args, ','))) {
1458                 *args = '\0';
1459                 args++;
1460                 preference = args;
1461         }
1462         if ((args = strchr(args, ','))) {
1463                 *args = '\0';
1464                 args++;
1465                 protocol = args;
1466         }
1467         if ((args = strchr(args, ','))) {
1468                 *args = '\0';
1469                 args++;
1470                 type = args;
1471         }
1472         if (name)
1473                 ast_copy_string(res->name, name, sizeof(res->name));
1474         if (preference) {
1475                 res->preference = atof(preference);
1476         }
1477         if (protocol) {
1478                 if (!strcasecmp("udp", protocol))
1479                         res->protocol = AJI_PROTOCOL_UDP;
1480                 if (!strcasecmp("ssltcp", protocol))
1481                         res->protocol = AJI_PROTOCOL_SSLTCP;
1482         }
1483         if (type) {
1484                 if (!strcasecmp("stun", type))
1485                         res->type = AJI_CONNECT_STUN;
1486                 if (!strcasecmp("local", type))
1487                         res->type = AJI_CONNECT_LOCAL;
1488                 if (!strcasecmp("relay", type))
1489                         res->type = AJI_CONNECT_RELAY;
1490         }
1491
1492         return res;
1493 }
1494 */
1495
1496 static int jingle_create_member(char *label, struct ast_variable *var, int allowguest,
1497                                                                 struct ast_codec_pref prefs, char *context,
1498                                                                 struct jingle *member)
1499 {
1500         struct aji_client *client;
1501
1502         if (!member)
1503                 ast_log(LOG_WARNING, "Out of memory.\n");
1504
1505         ast_copy_string(member->name, label, sizeof(member->name));
1506         ast_copy_string(member->user, label, sizeof(member->user));
1507         ast_copy_string(member->context, context, sizeof(member->context));
1508         member->allowguest = allowguest;
1509         member->prefs = prefs;
1510         while (var) {
1511 #if 0
1512                 struct jingle_candidate *candidate = NULL;
1513 #endif
1514                 if (!strcasecmp(var->name, "username"))
1515                         ast_copy_string(member->user, var->value, sizeof(member->user));
1516                 else if (!strcasecmp(var->name, "disallow"))
1517                         ast_parse_allow_disallow(&member->prefs, &member->capability, var->value, 0);
1518                 else if (!strcasecmp(var->name, "allow"))
1519                         ast_parse_allow_disallow(&member->prefs, &member->capability, var->value, 1);
1520                 else if (!strcasecmp(var->name, "context"))
1521                         ast_copy_string(member->context, var->value, sizeof(member->context));
1522 #if 0
1523                 else if (!strcasecmp(var->name, "candidate")) {
1524                         candidate = jingle_create_candidate(var->value);
1525                         if (candidate) {
1526                                 candidate->next = member->ourcandidates;
1527                                 member->ourcandidates = candidate;
1528                         }
1529                 }
1530 #endif
1531                 else if (!strcasecmp(var->name, "connection")) {
1532                         if ((client = ast_aji_get_client(var->value))) {
1533                                 member->connection = client;
1534                                 iks_filter_add_rule(client->f, jingle_parser, member, IKS_RULE_TYPE,
1535                                                                         IKS_PAK_IQ, IKS_RULE_FROM_PARTIAL, member->user,
1536                                                                         IKS_RULE_NS, "http://www.google.com/session",
1537                                                                         IKS_RULE_DONE);
1538                         } else {
1539                                 ast_log(LOG_ERROR, "connection referenced not found!\n");
1540                                 return 0;
1541                         }
1542                 }
1543                 var = var->next;
1544         }
1545         if (member->connection && member->user)
1546                 member->buddy = ASTOBJ_CONTAINER_FIND(&member->connection->buddies, member->user);
1547         else {
1548                 ast_log(LOG_ERROR, "No Connection or Username!\n");
1549         }
1550         return 1;
1551 }
1552
1553 static int jingle_load_config(void)
1554 {
1555         char *cat = NULL;
1556         struct ast_config *cfg = NULL;
1557         char context[100];
1558         int allowguest = 1;
1559         struct ast_variable *var;
1560         struct jingle *member;
1561         struct ast_codec_pref prefs;
1562         struct aji_client_container *clients;
1563         struct jingle_candidate *global_candidates = NULL;
1564
1565         cfg = ast_config_load(JINGLE_CONFIG);
1566         if (!cfg)
1567                 return 0;
1568
1569         /* Copy the default jb config over global_jbconf */
1570         memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
1571
1572         cat = ast_category_browse(cfg, NULL);
1573         for (var = ast_variable_browse(cfg, "general"); var; var = var->next) {
1574                 /* handle jb conf */
1575                 if (!ast_jb_read_conf(&global_jbconf, var->name, var->value))
1576                         continue;
1577
1578                 if (!strcasecmp(var->name, "allowguest"))
1579                         allowguest =
1580                                 (ast_true(ast_variable_retrieve(cfg, "general", "allowguest"))) ? 1 : 0;
1581                 else if (!strcasecmp(var->name, "disallow"))
1582                         ast_parse_allow_disallow(&prefs, &global_capability, var->value, 0);
1583                 else if (!strcasecmp(var->name, "allow"))
1584                         ast_parse_allow_disallow(&prefs, &global_capability, var->value, 1);
1585                 else if (!strcasecmp(var->name, "context"))
1586                         ast_copy_string(context, var->value, sizeof(context));
1587                 else if (!strcasecmp(var->name, "externip"))
1588                         ast_copy_string(externip, var->value, sizeof(externip));
1589 /*  Idea to allow for custom candidates  */
1590 /*
1591                 else if (!strcasecmp(var->name, "candidate")) {
1592                         candidate = jingle_create_candidate(var->value);
1593                         if (candidate) {
1594                                 candidate->next = global_candidates;
1595                                 global_candidates = candidate;
1596                         }
1597                 }
1598 */
1599         }
1600         while (cat) {
1601                 if (strcasecmp(cat, "general")) {
1602                         var = ast_variable_browse(cfg, cat);
1603                         member = (struct jingle *) malloc(sizeof(struct jingle));
1604                         memset(member, 0, sizeof(struct jingle));
1605                         ASTOBJ_INIT(member);
1606                         ASTOBJ_WRLOCK(member);
1607                         if (!strcasecmp(cat, "guest")) {
1608                                 ast_copy_string(member->name, "guest", sizeof(member->name));
1609                                 ast_copy_string(member->user, "guest", sizeof(member->user));
1610                                 ast_copy_string(member->context, context, sizeof(member->context));
1611                                 member->allowguest = allowguest;
1612                                 member->prefs = prefs;
1613                                 while (var) {
1614                                         if (!strcasecmp(var->name, "disallow"))
1615                                                 ast_parse_allow_disallow(&member->prefs, &member->capability,
1616                                                                                                  var->value, 0);
1617                                         else if (!strcasecmp(var->name, "allow"))
1618                                                 ast_parse_allow_disallow(&member->prefs, &member->capability,
1619                                                                                                  var->value, 1);
1620                                         else if (!strcasecmp(var->name, "context"))
1621                                                 ast_copy_string(member->context, var->value,
1622                                                                                 sizeof(member->context));
1623 /*  Idea to allow for custom candidates  */
1624 /*
1625                                         else if (!strcasecmp(var->name, "candidate")) {
1626                                                 candidate = jingle_create_candidate(var->value);
1627                                                 if (candidate) {
1628                                                         candidate->next = member->ourcandidates;
1629                                                         member->ourcandidates = candidate;
1630                                                 }
1631                                         }
1632 */
1633                                         var = var->next;
1634                                 }
1635                                 ASTOBJ_UNLOCK(member);
1636                                 clients = ast_aji_get_clients();
1637                                 if (clients) {
1638                                         ASTOBJ_CONTAINER_TRAVERSE(clients, 1, {
1639                                                 ASTOBJ_WRLOCK(iterator);
1640                                                 ASTOBJ_WRLOCK(member);
1641                                                 member->connection = iterator;
1642                                                 iks_filter_add_rule(iterator->f, jingle_parser, member, IKS_RULE_TYPE, IKS_PAK_IQ, IKS_RULE_NS,
1643                                                                                 "http://www.google.com/session", IKS_RULE_DONE);
1644                                                 ASTOBJ_UNLOCK(member);
1645                                                 ASTOBJ_CONTAINER_LINK(&jingles, member);
1646                                                 ASTOBJ_UNLOCK(iterator);
1647                                         });
1648                                 } else {
1649                                         ASTOBJ_UNLOCK(member);
1650                                         ASTOBJ_UNREF(member, jingle_member_destroy);
1651                                 }
1652                         } else {
1653                                 ASTOBJ_UNLOCK(member);
1654                                 if (jingle_create_member(cat, var, allowguest, prefs, context, member))
1655                                         ASTOBJ_CONTAINER_LINK(&jingles, member);
1656                                 ASTOBJ_UNREF(member, jingle_member_destroy);
1657                         }
1658                 }
1659                 cat = ast_category_browse(cfg, cat);
1660         }
1661         jingle_free_candidates(global_candidates);
1662         return 1;
1663 }
1664
1665 /*! \brief Load module into PBX, register channel */
1666 static int load_module(void)
1667 {
1668         ASTOBJ_CONTAINER_INIT(&jingles);
1669         if (!jingle_load_config()) {
1670                 ast_log(LOG_ERROR, "Unable to read config file %s. Not loading module.\n", JINGLE_CONFIG);
1671                 return 0;
1672         }
1673
1674         sched = sched_context_create();
1675         if (!sched) 
1676                 ast_log(LOG_WARNING, "Unable to create schedule context\n");
1677
1678         io = io_context_create();
1679         if (!io) 
1680                 ast_log(LOG_WARNING, "Unable to create I/O context\n");
1681
1682         if (ast_find_ourip(&__ourip, bindaddr)) {
1683                 ast_log(LOG_WARNING, "Unable to get own IP address, Jingle disabled\n");
1684                 return 0;
1685         }
1686
1687         ast_rtp_proto_register(&jingle_rtp);
1688
1689         /* Make sure we can register our channel type */
1690         if (ast_channel_register(&jingle_tech)) {
1691                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
1692                 return -1;
1693         }
1694         return 0;
1695 }
1696
1697 /*! \brief Reload module */
1698 static int reload(void)
1699 {
1700         return 0;
1701 }
1702
1703 /*! \brief Unload the jingle channel from Asterisk */
1704 static int unload_module(void)
1705 {
1706         struct jingle_pvt *privates = NULL;
1707
1708         /* First, take us out of the channel loop */
1709         ast_channel_unregister(&jingle_tech);
1710         ast_rtp_proto_unregister(&jingle_rtp);
1711
1712         if (!ast_mutex_lock(&jinglelock)) {
1713                 /* Hangup all interfaces if they have an owner */
1714                 ASTOBJ_CONTAINER_TRAVERSE(&jingles, 1, {
1715                         ASTOBJ_WRLOCK(iterator);
1716                         privates = iterator->p;
1717                         while(privates) {
1718                             if (privates->owner)
1719                                 ast_softhangup(privates->owner, AST_SOFTHANGUP_APPUNLOAD);
1720                             privates = privates->next;
1721                         }
1722                         iterator->p = NULL;
1723                         ASTOBJ_UNLOCK(iterator);
1724                 });
1725                 ast_mutex_unlock(&jinglelock);
1726         } else {
1727                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
1728                 return -1;
1729         }
1730         ASTOBJ_CONTAINER_DESTROYALL(&jingles, jingle_member_destroy);
1731         ASTOBJ_CONTAINER_DESTROY(&jingles);
1732         return 0;
1733 }
1734
1735 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Jingle Channel Driver",
1736                 .load = load_module,
1737                 .unload = unload_module,
1738                 .reload = reload,
1739                );