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