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