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