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