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