Merged revisions 87906 via svnmerge from
[asterisk/asterisk.git] / channels / chan_gtalk.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 Gtalk Channel Driver, until google/libjingle works with jingle spec
24  * 
25  * \ingroup channel_drivers
26  */
27
28 /*** MODULEINFO
29         <depend>iksemel</depend>
30         <depend>res_jabber</depend>
31         <use>gnutls</use>
32  ***/
33
34 #include "asterisk.h"
35
36 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
37
38 #include <stdlib.h>
39 #include <stdio.h>
40 #include <string.h>
41 #include <unistd.h>
42 #include <sys/socket.h>
43 #include <errno.h>
44 #include <stdlib.h>
45 #include <fcntl.h>
46 #include <netdb.h>
47 #include <netinet/in.h>
48 #include <arpa/inet.h>
49 #include <sys/signal.h>
50 #include <iksemel.h>
51 #include <pthread.h>
52
53 #ifdef HAVE_GNUTLS
54 #include <gcrypt.h>
55 GCRY_THREAD_OPTION_PTHREAD_IMPL;
56 #endif /* HAVE_GNUTLS */
57
58 #include "asterisk/lock.h"
59 #include "asterisk/channel.h"
60 #include "asterisk/config.h"
61 #include "asterisk/logger.h"
62 #include "asterisk/module.h"
63 #include "asterisk/pbx.h"
64 #include "asterisk/options.h"
65 #include "asterisk/lock.h"
66 #include "asterisk/sched.h"
67 #include "asterisk/io.h"
68 #include "asterisk/rtp.h"
69 #include "asterisk/acl.h"
70 #include "asterisk/callerid.h"
71 #include "asterisk/file.h"
72 #include "asterisk/cli.h"
73 #include "asterisk/app.h"
74 #include "asterisk/musiconhold.h"
75 #include "asterisk/manager.h"
76 #include "asterisk/stringfields.h"
77 #include "asterisk/utils.h"
78 #include "asterisk/causes.h"
79 #include "asterisk/astobj.h"
80 #include "asterisk/abstract_jb.h"
81 #include "asterisk/jabber.h"
82
83 #define GOOGLE_CONFIG "gtalk.conf"
84
85 #define GOOGLE_NS "http://www.google.com/session"
86
87
88 /*! Global jitterbuffer configuration - by default, jb is disabled */
89 static struct ast_jb_conf default_jbconf =
90 {
91         .flags = 0,
92         .max_size = -1,
93         .resync_threshold = -1,
94         .impl = ""
95 };
96 static struct ast_jb_conf global_jbconf;
97
98 enum gtalk_protocol {
99         AJI_PROTOCOL_UDP = 1,
100         AJI_PROTOCOL_SSLTCP = 2,
101 };
102
103 enum gtalk_connect_type {
104         AJI_CONNECT_STUN = 1,
105         AJI_CONNECT_LOCAL = 2,
106         AJI_CONNECT_RELAY = 3,
107 };
108
109 struct gtalk_pvt {
110         ast_mutex_t lock;                /*!< Channel private lock */
111         time_t laststun;
112         struct gtalk *parent;            /*!< Parent client */
113         char sid[100];
114         char us[AJI_MAX_JIDLEN];
115         char them[AJI_MAX_JIDLEN];
116         char ring[10];                   /*!< Message ID of ring */
117         iksrule *ringrule;               /*!< Rule for matching RING request */
118         int initiator;                   /*!< If we're the initiator */
119         int alreadygone;
120         int capability;
121         struct ast_codec_pref prefs;
122         struct gtalk_candidate *theircandidates;
123         struct gtalk_candidate *ourcandidates;
124         char cid_num[80];                /*!< Caller ID num */
125         char cid_name[80];               /*!< Caller ID name */
126         char exten[80];                  /*!< Called extension */
127         struct ast_channel *owner;       /*!< Master Channel */
128         struct ast_rtp *rtp;             /*!< RTP audio session */
129         struct ast_rtp *vrtp;            /*!< RTP video session */
130         int jointcapability;             /*!< Supported capability at both ends (codecs ) */
131         int peercapability;
132         struct gtalk_pvt *next; /* Next entity */
133 };
134
135 struct gtalk_candidate {
136         char name[100];
137         enum gtalk_protocol protocol;
138         double preference;
139         char username[100];
140         char password[100];
141         enum gtalk_connect_type type;
142         char network[6];
143         int generation;
144         char ip[16];
145         int port;
146         int receipt;
147         struct gtalk_candidate *next;
148 };
149
150 struct gtalk {
151         ASTOBJ_COMPONENTS(struct gtalk);
152         struct aji_client *connection;
153         struct aji_buddy *buddy;
154         struct gtalk_pvt *p;
155         struct ast_codec_pref prefs;
156         int amaflags;                   /*!< AMA Flags */
157         char user[AJI_MAX_JIDLEN];
158         char context[AST_MAX_CONTEXT];
159         char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */
160         int capability;
161         ast_group_t callgroup;  /*!< Call group */
162         ast_group_t pickupgroup;        /*!< Pickup group */
163         int callingpres;                /*!< Calling presentation */
164         int allowguest;
165         char language[MAX_LANGUAGE];    /*!<  Default language for prompts */
166         char musicclass[MAX_MUSICCLASS];        /*!<  Music on Hold class */
167 };
168
169 struct gtalk_container {
170         ASTOBJ_CONTAINER_COMPONENTS(struct gtalk);
171 };
172
173 static const char desc[] = "Gtalk Channel";
174
175 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
176
177 AST_MUTEX_DEFINE_STATIC(gtalklock); /*!< Protect the interface list (of gtalk_pvt's) */
178
179 /* Forward declarations */
180 static struct ast_channel *gtalk_request(const char *type, int format, void *data, int *cause);
181 static int gtalk_digit(struct ast_channel *ast, char digit, unsigned int duration);
182 static int gtalk_digit_begin(struct ast_channel *ast, char digit);
183 static int gtalk_digit_end(struct ast_channel *ast, char digit, unsigned int duration);
184 static int gtalk_call(struct ast_channel *ast, char *dest, int timeout);
185 static int gtalk_hangup(struct ast_channel *ast);
186 static int gtalk_answer(struct ast_channel *ast);
187 static int gtalk_newcall(struct gtalk *client, ikspak *pak);
188 static struct ast_frame *gtalk_read(struct ast_channel *ast);
189 static int gtalk_write(struct ast_channel *ast, struct ast_frame *f);
190 static int gtalk_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
191 static int gtalk_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
192 static int gtalk_sendhtml(struct ast_channel *ast, int subclass, const char *data, int datalen);
193 static struct gtalk_pvt *gtalk_alloc(struct gtalk *client, const char *us, const char *them, const char *sid);
194 static char *gtalk_do_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
195 static char *gtalk_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
196 /*----- RTP interface functions */
197 static int gtalk_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp,
198                                                            struct ast_rtp *vrtp, struct ast_rtp *trtp, int codecs, int nat_active);
199 static enum ast_rtp_get_result gtalk_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
200 static int gtalk_get_codec(struct ast_channel *chan);
201
202 /*! \brief PBX interface structure for channel registration */
203 static const struct ast_channel_tech gtalk_tech = {
204         .type = "Gtalk",
205         .description = "Gtalk Channel Driver",
206         .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
207         .requester = gtalk_request,
208         .send_digit_begin = gtalk_digit_begin,
209         .send_digit_end = gtalk_digit_end,
210         .bridge = ast_rtp_bridge,
211         .call = gtalk_call,
212         .hangup = gtalk_hangup,
213         .answer = gtalk_answer,
214         .read = gtalk_read,
215         .write = gtalk_write,
216         .exception = gtalk_read,
217         .indicate = gtalk_indicate,
218         .fixup = gtalk_fixup,
219         .send_html = gtalk_sendhtml,
220         .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER
221 };
222
223 static struct sockaddr_in bindaddr = { 0, };    /*!< The address we bind to */
224
225 static struct sched_context *sched;     /*!< The scheduling context */
226 static struct io_context *io;   /*!< The IO context */
227 static struct in_addr __ourip;
228
229 /*! \brief RTP driver interface */
230 static struct ast_rtp_protocol gtalk_rtp = {
231         type: "Gtalk",
232         get_rtp_info: gtalk_get_rtp_peer,
233         set_rtp_peer: gtalk_set_rtp_peer,
234         get_codec: gtalk_get_codec,
235 };
236
237 static struct ast_cli_entry gtalk_cli[] = {
238         AST_CLI_DEFINE(gtalk_do_reload, "Reload GoogleTalk configuration"),
239         AST_CLI_DEFINE(gtalk_show_channels, "Show GoogleTalk channels"),
240 };
241
242 static char externip[16];
243
244 static struct gtalk_container gtalk_list;
245
246 static void gtalk_member_destroy(struct gtalk *obj)
247 {
248         ast_free(obj);
249 }
250
251 static struct gtalk *find_gtalk(char *name, char *connection)
252 {
253         struct gtalk *gtalk = NULL;
254         char *domain = NULL , *s = NULL;
255
256         if (strchr(connection, '@')) {
257                 s = ast_strdupa(connection);
258                 domain = strsep(&s, "@");
259                 ast_verbose("OOOOH domain = %s\n", domain);
260         }
261         gtalk = ASTOBJ_CONTAINER_FIND(&gtalk_list, name);
262         if (!gtalk && strchr(name, '@'))
263                 gtalk = ASTOBJ_CONTAINER_FIND_FULL(&gtalk_list, name, user,,, strcasecmp);
264
265         if (!gtalk) {                           /* guest call */
266                 ASTOBJ_CONTAINER_TRAVERSE(&gtalk_list, 1, {
267                         ASTOBJ_RDLOCK(iterator);
268                         if (!strcasecmp(iterator->name, "guest")) {
269                                 if (!strcasecmp(iterator->connection->jid->partial, connection)) {
270                                         gtalk = iterator;
271                                 } else if (!strcasecmp(iterator->connection->name, connection)) {
272                                         gtalk = iterator;
273                                 } else if (iterator->connection->component && !strcasecmp(iterator->connection->user,domain)) {
274                                         gtalk = iterator;
275                                 }
276                         }
277                         ASTOBJ_UNLOCK(iterator);
278
279                         if (gtalk)
280                                 break;
281                 });
282
283         }
284         return gtalk;
285 }
286
287
288 static int add_codec_to_answer(const struct gtalk_pvt *p, int codec, iks *dcodecs)
289 {
290         char *format = ast_getformatname(codec);
291
292         if (!strcasecmp("ulaw", format)) {
293                 iks *payload_eg711u, *payload_pcmu;
294                 payload_pcmu = iks_new("payload-type");
295                 payload_eg711u = iks_new("payload-type");
296         
297                 if(!payload_eg711u || !payload_pcmu) {
298                         if(payload_pcmu)
299                                 iks_delete(payload_pcmu);
300                         if(payload_eg711u)
301                                 iks_delete(payload_eg711u);
302                         ast_log(LOG_WARNING,"Failed to allocate iks node");
303                         return -1;
304                 }
305                 iks_insert_attrib(payload_pcmu, "id", "0");
306                 iks_insert_attrib(payload_pcmu, "name", "PCMU");
307                 iks_insert_attrib(payload_pcmu, "clockrate","8000");
308                 iks_insert_attrib(payload_pcmu, "bitrate","64000");
309                 iks_insert_attrib(payload_eg711u, "id", "100");
310                 iks_insert_attrib(payload_eg711u, "name", "EG711U");
311                 iks_insert_attrib(payload_eg711u, "clockrate","8000");
312                 iks_insert_attrib(payload_eg711u, "bitrate","64000");
313                 iks_insert_node(dcodecs, payload_pcmu);
314                 iks_insert_node(dcodecs, payload_eg711u);
315         }
316         if (!strcasecmp("alaw", format)) {
317                 iks *payload_eg711a, *payload_pcma;
318                 payload_pcma = iks_new("payload-type");
319                 payload_eg711a = iks_new("payload-type");
320                 if(!payload_eg711a || !payload_pcma) {
321                         if(payload_eg711a)
322                                 iks_delete(payload_eg711a);
323                         if(payload_pcma)
324                                 iks_delete(payload_pcma);
325                         ast_log(LOG_WARNING,"Failed to allocate iks node");
326                         return -1;
327                 }
328                 iks_insert_attrib(payload_pcma, "id", "8");
329                 iks_insert_attrib(payload_pcma, "name", "PCMA");
330                 iks_insert_attrib(payload_pcma, "clockrate","8000");
331                 iks_insert_attrib(payload_pcma, "bitrate","64000");
332                 payload_eg711a = iks_new("payload-type");
333                 iks_insert_attrib(payload_eg711a, "id", "101");
334                 iks_insert_attrib(payload_eg711a, "name", "EG711A");
335                 iks_insert_attrib(payload_eg711a, "clockrate","8000");
336                 iks_insert_attrib(payload_eg711a, "bitrate","64000");
337                 iks_insert_node(dcodecs, payload_pcma);
338                 iks_insert_node(dcodecs, payload_eg711a);
339         }
340         if (!strcasecmp("ilbc", format)) {
341                 iks *payload_ilbc = iks_new("payload-type");
342                 if(!payload_ilbc) {
343                         ast_log(LOG_WARNING,"Failed to allocate iks node");
344                         return -1;
345                 }
346                 iks_insert_attrib(payload_ilbc, "id", "97");
347                 iks_insert_attrib(payload_ilbc, "name", "iLBC");
348                 iks_insert_attrib(payload_ilbc, "clockrate","8000");
349                 iks_insert_attrib(payload_ilbc, "bitrate","13300");
350                 iks_insert_node(dcodecs, payload_ilbc);
351         }
352         if (!strcasecmp("g723", format)) {
353                 iks *payload_g723 = iks_new("payload-type");
354                 if(!payload_g723) {
355                         ast_log(LOG_WARNING,"Failed to allocate iks node");
356                         return -1;
357                 }
358                 iks_insert_attrib(payload_g723, "id", "4");
359                 iks_insert_attrib(payload_g723, "name", "G723");
360                 iks_insert_attrib(payload_g723, "clockrate","8000");
361                 iks_insert_attrib(payload_g723, "bitrate","6300");
362                 iks_insert_node(dcodecs, payload_g723);
363         }
364         if (!strcasecmp("speex", format)) {
365                 iks *payload_speex = iks_new("payload-type");
366                 if(!payload_speex) {
367                         ast_log(LOG_WARNING,"Failed to allocate iks node");
368                         return -1;
369                 }
370                 iks_insert_attrib(payload_speex, "id", "110");
371                 iks_insert_attrib(payload_speex, "name", "speex");
372                 iks_insert_attrib(payload_speex, "clockrate","8000");
373                 iks_insert_attrib(payload_speex, "bitrate","11000");
374                 iks_insert_node(dcodecs, payload_speex);
375         }
376         ast_rtp_lookup_code(p->rtp, 1, codec);
377         return 0;
378 }
379
380 static int gtalk_invite(struct gtalk_pvt *p, char *to, char *from, char *sid, int initiator)
381 {
382         struct gtalk *client = p->parent;
383         iks *iq, *gtalk, *dcodecs, *payload_telephone, *transport;
384         int x;
385         int pref_codec = 0;
386         int alreadysent = 0;
387
388
389         iq = iks_new("iq");
390         gtalk = iks_new("session");
391         dcodecs = iks_new("description");
392         transport = iks_new("transport");
393         payload_telephone = iks_new("payload-type");
394         if (!(iq && gtalk && dcodecs && transport && payload_telephone)){
395                 if(iq)
396                         iks_delete(iq);
397                 if(gtalk)
398                         iks_delete(gtalk);
399                 if(dcodecs)
400                         iks_delete(dcodecs);
401                 if(transport)
402                         iks_delete(transport);
403                 if(payload_telephone)
404                         iks_delete(payload_telephone);
405
406                 ast_log(LOG_ERROR, "Could not allocate iksemel nodes\n");
407                 return 0;
408         }
409         iks_insert_attrib(dcodecs, "xmlns", "http://www.google.com/session/phone");
410         iks_insert_attrib(dcodecs, "xml:lang", "en");
411
412         for (x = 0; x < 32; x++) {
413                 if (!(pref_codec = ast_codec_pref_index(&client->prefs, x)))
414                         break;
415                 if (!(client->capability & pref_codec))
416                         continue;
417                 if (alreadysent & pref_codec)
418                         continue;
419                 add_codec_to_answer(p, pref_codec, dcodecs);
420                 alreadysent |= pref_codec;
421         }
422         
423         iks_insert_attrib(payload_telephone, "id", "106");
424         iks_insert_attrib(payload_telephone, "name", "telephone-event");
425         iks_insert_attrib(payload_telephone, "clockrate", "8000");
426         
427         iks_insert_attrib(transport,"xmlns","http://www.google.com/transport/p2p");
428         
429         iks_insert_attrib(iq, "type", "set");
430         iks_insert_attrib(iq, "to", to);
431         iks_insert_attrib(iq, "from", from);
432         iks_insert_attrib(iq, "id", client->connection->mid);
433         ast_aji_increment_mid(client->connection->mid);
434
435         iks_insert_attrib(gtalk, "xmlns", "http://www.google.com/session");
436         iks_insert_attrib(gtalk, "type",initiator ? "initiate": "accept");
437         iks_insert_attrib(gtalk, "initiator", initiator ? from : to);
438         iks_insert_attrib(gtalk, "id", sid);
439         iks_insert_node(iq, gtalk);
440         iks_insert_node(gtalk, dcodecs);
441         iks_insert_node(gtalk, transport);
442         iks_insert_node(dcodecs, payload_telephone);
443
444         iks_send(client->connection->p, iq);
445         iks_delete(payload_telephone);
446         iks_delete(transport);
447         iks_delete(dcodecs);
448         iks_delete(gtalk);
449         iks_delete(iq);
450         return 1;
451 }
452
453 static int gtalk_invite_response(struct gtalk_pvt *p, char *to , char *from, char *sid, int initiator)
454 {
455         iks *iq, *session, *transport;
456         iq = iks_new("iq");
457         session = iks_new("session");
458         transport = iks_new("transport");
459         if(!(iq && session && transport)) {
460                 if(iq)
461                         iks_delete(iq);
462                 if(session)
463                         iks_delete(session);
464                 if(transport)
465                         iks_delete(transport);
466                 ast_log(LOG_ERROR, " Unable to allocate IKS node\n");
467                 return -1;
468         }
469         iks_insert_attrib(iq, "from", from);
470         iks_insert_attrib(iq, "to", to);
471         iks_insert_attrib(iq, "type", "set");
472         iks_insert_attrib(iq, "id",p->parent->connection->mid);
473         ast_aji_increment_mid(p->parent->connection->mid);
474         iks_insert_attrib(session, "type", "transport-accept");
475         iks_insert_attrib(session, "id", sid);
476         iks_insert_attrib(session, "initiator", initiator ? from : to);
477         iks_insert_attrib(session, "xmlns", "http://www.google.com/session");
478         iks_insert_attrib(transport, "xmlns", "http://www.google.com/transport/p2p");
479         iks_insert_node(iq,session);
480         iks_insert_node(session,transport);
481         iks_send(p->parent->connection->p, iq);
482         iks_delete(transport);
483         iks_delete(session);
484         iks_delete(iq);
485         return 1;
486
487 }
488
489 static int gtalk_ringing_ack(void *data, ikspak *pak)
490 {
491         struct gtalk_pvt *p = data;
492
493         if (p->ringrule)
494                 iks_filter_remove_rule(p->parent->connection->f, p->ringrule);
495         p->ringrule = NULL;
496         if (p->owner)
497                 ast_queue_control(p->owner, AST_CONTROL_RINGING);
498         return IKS_FILTER_EAT;
499 }
500
501 static int gtalk_answer(struct ast_channel *ast)
502 {
503         struct gtalk_pvt *p = ast->tech_pvt;
504         int res = 0;
505         
506         ast_debug(1, "Answer!\n");
507         ast_mutex_lock(&p->lock);
508         gtalk_invite(p, p->them, p->us,p->sid, 0);
509         ast_mutex_unlock(&p->lock);
510         return res;
511 }
512
513 static enum ast_rtp_get_result gtalk_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
514 {
515         struct gtalk_pvt *p = chan->tech_pvt;
516         enum ast_rtp_get_result res = AST_RTP_GET_FAILED;
517
518         if (!p)
519                 return res;
520
521         ast_mutex_lock(&p->lock);
522         if (p->rtp){
523                 *rtp = p->rtp;
524                 res = AST_RTP_TRY_PARTIAL;
525         }
526         ast_mutex_unlock(&p->lock);
527
528         return res;
529 }
530
531 static int gtalk_get_codec(struct ast_channel *chan)
532 {
533         struct gtalk_pvt *p = chan->tech_pvt;
534         return p->peercapability;
535 }
536
537 static int gtalk_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, struct ast_rtp *trtp, int codecs, int nat_active)
538 {
539         struct gtalk_pvt *p;
540
541         p = chan->tech_pvt;
542         if (!p)
543                 return -1;
544         ast_mutex_lock(&p->lock);
545
546 /*      if (rtp)
547                 ast_rtp_get_peer(rtp, &p->redirip);
548         else
549                 memset(&p->redirip, 0, sizeof(p->redirip));
550         p->redircodecs = codecs; */
551
552         /* Reset lastrtprx timer */
553         ast_mutex_unlock(&p->lock);
554         return 0;
555 }
556
557 static int gtalk_response(struct gtalk *client, char *from, ikspak *pak, const char *reasonstr, const char *reasonstr2)
558 {
559         iks *response = NULL, *error = NULL, *reason = NULL;
560         int res = -1;
561
562         response = iks_new("iq");
563         if (response) {
564                 iks_insert_attrib(response, "type", "result");
565                 iks_insert_attrib(response, "from", from);
566                 iks_insert_attrib(response, "to", iks_find_attrib(pak->x, "from"));
567                 iks_insert_attrib(response, "id", iks_find_attrib(pak->x, "id"));
568                 if (reasonstr) {
569                         error = iks_new("error");
570                         if (error) {
571                                 iks_insert_attrib(error, "type", "cancel");
572                                 reason = iks_new(reasonstr);
573                                 if (reason)
574                                         iks_insert_node(error, reason);
575                                 iks_insert_node(response, error);
576                         }
577                 }
578                 iks_send(client->connection->p, response);
579                 if (reason)
580                         iks_delete(reason);
581                 if (error)
582                         iks_delete(error);
583                 iks_delete(response);
584                 res = 0;
585         }
586         return res;
587 }
588
589 static int gtalk_is_answered(struct gtalk *client, ikspak *pak)
590 {
591         struct gtalk_pvt *tmp;
592         char *from;
593         ast_debug(1, "The client is %s\n", client->name);
594         /* Make sure our new call doesn't exist yet */
595         for (tmp = client->p; tmp; tmp = tmp->next) {
596                 if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid))
597                         break;
598         }
599         
600         from = iks_find_attrib(pak->x, "to");
601         if(!from)
602                 from = client->connection->jid->full;
603
604         if (tmp) {
605                 if (tmp->owner)
606                         ast_queue_control(tmp->owner, AST_CONTROL_ANSWER);
607         } else
608                 ast_log(LOG_NOTICE, "Whoa, didn't find call!\n");
609         gtalk_response(client, from, pak, NULL, NULL);
610         return 1;
611 }
612
613 static int gtalk_is_accepted(struct gtalk *client, ikspak *pak)
614 {
615         struct gtalk_pvt *tmp;
616         char *from;
617
618         ast_log(LOG_DEBUG, "The client is %s\n", client->name);
619         /* find corresponding call */
620         for (tmp = client->p; tmp; tmp = tmp->next) {
621                 if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid))
622                         break;
623         }
624
625         from = iks_find_attrib(pak->x, "to");
626         if(!from)
627                 from = client->connection->jid->full;
628
629         if (!tmp)
630                 ast_log(LOG_NOTICE, "Whoa, didn't find call!\n");
631
632         /* answer 'iq' packet to let the remote peer know that we're alive */
633         gtalk_response(client, from, pak, NULL, NULL);
634         return 1;
635 }
636
637 static int gtalk_handle_dtmf(struct gtalk *client, ikspak *pak)
638 {
639         struct gtalk_pvt *tmp;
640         iks *dtmfnode = NULL, *dtmfchild = NULL;
641         char *dtmf;
642         char *from;
643         /* Make sure our new call doesn't exist yet */
644         for (tmp = client->p; tmp; tmp = tmp->next) {
645                 if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid) || iks_find_with_attrib(pak->x, "gtalk", "sid", tmp->sid))
646                         break;
647         }
648         from = iks_find_attrib(pak->x, "to");
649         if(!from)
650                 from = client->connection->jid->full;
651
652
653         if (tmp) {
654                 if(iks_find_with_attrib(pak->x, "dtmf-method", "method", "rtp")) {
655                         gtalk_response(client, from, pak,
656                                         "feature-not-implemented xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'",
657                                         "unsupported-dtmf-method xmlns='http://jabber.org/protocol/gtalk/info/dtmf#errors'");
658                         return -1;
659                 }
660                 if ((dtmfnode = iks_find(pak->x, "dtmf"))) {
661                         if((dtmf = iks_find_attrib(dtmfnode, "code"))) {
662                                 if(iks_find_with_attrib(pak->x, "dtmf", "action", "button-up")) {
663                                         struct ast_frame f = {AST_FRAME_DTMF_BEGIN, };
664                                         f.subclass = dtmf[0];
665                                         ast_queue_frame(tmp->owner, &f);
666                                         ast_verbose("GOOGLE! DTMF-relay event received: %c\n", f.subclass);
667                                 } else if(iks_find_with_attrib(pak->x, "dtmf", "action", "button-down")) {
668                                         struct ast_frame f = {AST_FRAME_DTMF_END, };
669                                         f.subclass = dtmf[0];
670                                         ast_queue_frame(tmp->owner, &f);
671                                         ast_verbose("GOOGLE! DTMF-relay event received: %c\n", f.subclass);
672                                 } else if(iks_find_attrib(pak->x, "dtmf")) { /* 250 millasecond default */
673                                         struct ast_frame f = {AST_FRAME_DTMF, };
674                                         f.subclass = dtmf[0];
675                                         ast_queue_frame(tmp->owner, &f);
676                                         ast_verbose("GOOGLE! DTMF-relay event received: %c\n", f.subclass);
677                                 }
678                         }
679                 } else if ((dtmfnode = iks_find_with_attrib(pak->x, "gtalk", "action", "session-info"))) {
680                         if((dtmfchild = iks_find(dtmfnode, "dtmf"))) {
681                                 if((dtmf = iks_find_attrib(dtmfchild, "code"))) {
682                                         if(iks_find_with_attrib(dtmfnode, "dtmf", "action", "button-up")) {
683                                                 struct ast_frame f = {AST_FRAME_DTMF_END, };
684                                                 f.subclass = dtmf[0];
685                                                 ast_queue_frame(tmp->owner, &f);
686                                                 ast_verbose("GOOGLE! DTMF-relay event received: %c\n", f.subclass);
687                                         } else if(iks_find_with_attrib(dtmfnode, "dtmf", "action", "button-down")) {
688                                                 struct ast_frame f = {AST_FRAME_DTMF_BEGIN, };
689                                                 f.subclass = dtmf[0];
690                                                 ast_queue_frame(tmp->owner, &f);
691                                                 ast_verbose("GOOGLE! DTMF-relay event received: %c\n", f.subclass);
692                                         }
693                                 }
694                         }
695                 }
696                 gtalk_response(client, from, pak, NULL, NULL);
697                 return 1;
698         } else
699                 ast_log(LOG_NOTICE, "Whoa, didn't find call!\n");
700
701         gtalk_response(client, from, pak, NULL, NULL);
702         return 1;
703 }
704
705 static int gtalk_hangup_farend(struct gtalk *client, ikspak *pak)
706 {
707         struct gtalk_pvt *tmp;
708         char *from;
709
710         ast_debug(1, "The client is %s\n", client->name);
711         /* Make sure our new call doesn't exist yet */
712         for (tmp = client->p; tmp; tmp = tmp->next) {
713                 if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid))
714                         break;
715         }
716         from = iks_find_attrib(pak->x, "to");
717         if(!from)
718                 from = client->connection->jid->full;
719
720         if (tmp) {
721                 tmp->alreadygone = 1;
722                 if (tmp->owner)
723                         ast_queue_hangup(tmp->owner);
724         } else
725                 ast_log(LOG_NOTICE, "Whoa, didn't find call!\n");
726         gtalk_response(client, from, pak, NULL, NULL);
727         return 1;
728 }
729
730 static int gtalk_create_candidates(struct gtalk *client, struct gtalk_pvt *p, char *sid, char *from, char *to)
731 {
732         struct gtalk_candidate *tmp;
733         struct aji_client *c = client->connection;
734         struct gtalk_candidate *ours1 = NULL, *ours2 = NULL;
735         struct sockaddr_in sin;
736         struct sockaddr_in dest;
737         struct in_addr us;
738         iks *iq, *gtalk, *candidate, *transport;
739         char user[17], pass[17], preference[5], port[7];
740
741
742         iq = iks_new("iq");
743         gtalk = iks_new("session");
744         candidate = iks_new("candidate");
745         transport = iks_new("transport");
746         if (!iq || !gtalk || !candidate || !transport) {
747                 ast_log(LOG_ERROR, "Memory allocation error\n");
748                 goto safeout;
749         }
750         ours1 = ast_calloc(1, sizeof(*ours1));
751         ours2 = ast_calloc(1, sizeof(*ours2));
752         if (!ours1 || !ours2)
753                 goto safeout;
754
755         iks_insert_attrib(transport, "xmlns","http://www.google.com/transport/p2p");
756         iks_insert_node(iq, gtalk);
757         iks_insert_node(gtalk,transport);
758         iks_insert_node(transport, candidate);
759
760         for (; p; p = p->next) {
761                 if (!strcasecmp(p->sid, sid))
762                         break;
763         }
764
765         if (!p) {
766                 ast_log(LOG_NOTICE, "No matching gtalk session - SID %s!\n", sid);
767                 goto safeout;
768         }
769
770         ast_rtp_get_us(p->rtp, &sin);
771         ast_find_ourip(&us, bindaddr);
772
773         /* Setup our gtalk candidates */
774         ast_copy_string(ours1->name, "rtp", sizeof(ours1->name));
775         ours1->port = ntohs(sin.sin_port);
776         ours1->preference = 1;
777         snprintf(user, sizeof(user), "%08lx%08lx", ast_random(), ast_random());
778         snprintf(pass, sizeof(pass), "%08lx%08lx", ast_random(), ast_random());
779         ast_copy_string(ours1->username, user, sizeof(ours1->username));
780         ast_copy_string(ours1->password, pass, sizeof(ours1->password));
781         ast_copy_string(ours1->ip, ast_inet_ntoa(us), sizeof(ours1->ip));
782         ours1->protocol = AJI_PROTOCOL_UDP;
783         ours1->type = AJI_CONNECT_LOCAL;
784         ours1->generation = 0;
785         p->ourcandidates = ours1;
786
787         if (!ast_strlen_zero(externip)) {
788                 /* XXX We should really stun for this one not just go with externip XXX */
789                 snprintf(user, sizeof(user), "%08lx%08lx", ast_random(), ast_random());
790                 snprintf(pass, sizeof(pass), "%08lx%08lx", ast_random(), ast_random());
791                 ast_copy_string(ours2->username, user, sizeof(ours2->username));
792                 ast_copy_string(ours2->password, pass, sizeof(ours2->password));
793                 ast_copy_string(ours2->ip, externip, sizeof(ours2->ip));
794                 ast_copy_string(ours2->name, "rtp", sizeof(ours1->name));
795                 ours2->port = ntohs(sin.sin_port);
796                 ours2->preference = 0.9;
797                 ours2->protocol = AJI_PROTOCOL_UDP;
798                 ours2->type = AJI_CONNECT_STUN;
799                 ours2->generation = 0;
800                 ours1->next = ours2;
801                 ours2 = NULL;
802         }
803         ours1 = NULL;
804         dest.sin_addr = __ourip;
805         dest.sin_port = sin.sin_port;
806
807
808         for (tmp = p->ourcandidates; tmp; tmp = tmp->next) {
809                 snprintf(port, sizeof(port), "%d", tmp->port);
810                 snprintf(preference, sizeof(preference), "%.2f", tmp->preference);
811                 iks_insert_attrib(iq, "from", to);
812                 iks_insert_attrib(iq, "to", from);
813                 iks_insert_attrib(iq, "type", "set");
814                 iks_insert_attrib(iq, "id", c->mid);
815                 ast_aji_increment_mid(c->mid);
816                 iks_insert_attrib(gtalk, "type", "transport-info");
817                 iks_insert_attrib(gtalk, "id", sid);
818                 iks_insert_attrib(gtalk, "initiator", (p->initiator) ? to : from);
819                 iks_insert_attrib(gtalk, "xmlns", GOOGLE_NS);
820                 iks_insert_attrib(candidate, "name", tmp->name);
821                 iks_insert_attrib(candidate, "address", tmp->ip);
822                 iks_insert_attrib(candidate, "port", port);
823                 iks_insert_attrib(candidate, "username", tmp->username);
824                 iks_insert_attrib(candidate, "password", tmp->password);
825                 iks_insert_attrib(candidate, "preference", preference);
826                 if (tmp->protocol == AJI_PROTOCOL_UDP)
827                         iks_insert_attrib(candidate, "protocol", "udp");
828                 if (tmp->protocol == AJI_PROTOCOL_SSLTCP)
829                         iks_insert_attrib(candidate, "protocol", "ssltcp");
830                 if (tmp->type == AJI_CONNECT_STUN)
831                         iks_insert_attrib(candidate, "type", "stun");
832                 if (tmp->type == AJI_CONNECT_LOCAL)
833                         iks_insert_attrib(candidate, "type", "local");
834                 if (tmp->type == AJI_CONNECT_RELAY)
835                         iks_insert_attrib(candidate, "type", "relay");
836                 iks_insert_attrib(candidate, "network", "0");
837                 iks_insert_attrib(candidate, "generation", "0");
838                 iks_send(c->p, iq);
839         }
840         p->laststun = 0;
841
842 safeout:
843         if (ours1)
844                 ast_free(ours1);
845         if (ours2)
846                 ast_free(ours2);
847         if (iq)
848                 iks_delete(iq);
849         if (gtalk)
850                 iks_delete(gtalk);
851         if (candidate)
852                 iks_delete(candidate);
853         if(transport)
854                 iks_delete(transport);
855         return 1;
856 }
857
858 static struct gtalk_pvt *gtalk_alloc(struct gtalk *client, const char *us, const char *them, const char *sid)
859 {
860         struct gtalk_pvt *tmp = NULL;
861         struct aji_resource *resources = NULL;
862         struct aji_buddy *buddy;
863         char idroster[200];
864         char *data, *exten = NULL;
865
866         ast_debug(1, "The client is %s for alloc\n", client->name);
867         if (!sid && !strchr(them, '/')) {       /* I started call! */
868                 if (!strcasecmp(client->name, "guest")) {
869                         buddy = ASTOBJ_CONTAINER_FIND(&client->connection->buddies, them);
870                         if (buddy)
871                                 resources = buddy->resources;
872                 } else if (client->buddy)
873                         resources = client->buddy->resources;
874                 while (resources) {
875                         if (resources->cap->jingle) {
876                                 break;
877                         }
878                         resources = resources->next;
879                 }
880                 if (resources)
881                         snprintf(idroster, sizeof(idroster), "%s/%s", them, resources->resource);
882                 else {
883                         ast_log(LOG_ERROR, "no gtalk capable clients to talk to.\n");
884                         return NULL;
885                 }
886         }
887         if (!(tmp = ast_calloc(1, sizeof(*tmp)))) {
888                 return NULL;
889         }
890
891         memcpy(&tmp->prefs, &client->prefs, sizeof(struct ast_codec_pref));
892
893         if (sid) {
894                 ast_copy_string(tmp->sid, sid, sizeof(tmp->sid));
895                 ast_copy_string(tmp->them, them, sizeof(tmp->them));
896                 ast_copy_string(tmp->us, us, sizeof(tmp->us));
897         } else {
898                 snprintf(tmp->sid, sizeof(tmp->sid), "%08lx%08lx", ast_random(), ast_random());
899                 ast_copy_string(tmp->them, idroster, sizeof(tmp->them));
900                 ast_copy_string(tmp->us, us, sizeof(tmp->us));
901                 tmp->initiator = 1;
902         }
903         tmp->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
904         tmp->parent = client;
905         if (!tmp->rtp) {
906                 ast_log(LOG_WARNING, "Out of RTP sessions?\n");
907                 ast_free(tmp);
908                 return NULL;
909         }
910
911         if(strchr(tmp->us, '/')) {
912                 data = ast_strdupa(tmp->us);
913                 exten = strsep(&data, "/");
914         } else
915                 exten = tmp->us;
916         ast_copy_string(tmp->exten,  exten, sizeof(tmp->exten));
917         ast_mutex_init(&tmp->lock);
918         ast_mutex_lock(&gtalklock);
919         tmp->next = client->p;
920         client->p = tmp;
921         ast_mutex_unlock(&gtalklock);
922         return tmp;
923 }
924
925 /*! \brief Start new gtalk channel */
926 static struct ast_channel *gtalk_new(struct gtalk *client, struct gtalk_pvt *i, int state, const char *title)
927 {
928         struct ast_channel *tmp;
929         int fmt;
930         int what;
931         const char *n2;
932         char *data = NULL, *cid = NULL;
933
934         if (title)
935                 n2 = title;
936         else
937                 n2 = i->us;
938         tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, client->accountcode, i->exten, client->context, client->amaflags, "Gtalk/%s-%04lx", n2, ast_random() & 0xffff);
939         if (!tmp) {
940                 ast_log(LOG_WARNING, "Unable to allocate Gtalk channel structure!\n");
941                 return NULL;
942         }
943         tmp->tech = &gtalk_tech;
944
945         /* Select our native format based on codec preference until we receive
946            something from another device to the contrary. */
947 /*      ast_verbose("XXXXXXXXXXXXX\nXXX i->jointcapability = %X\nXXX i->capability = %X\nXXX global_capability %X\n XXXXXXXXXXXX\n",i->jointcapability,i->capability,global_capability); */
948         if (i->jointcapability)
949                 what = i->jointcapability;
950         else if (i->capability)
951                 what = i->capability;
952         else
953                 what = global_capability;
954
955         /* Set Frame packetization */
956         if (i->rtp)
957                 ast_rtp_codec_setpref(i->rtp, &i->prefs);
958
959         tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | (i->jointcapability & AST_FORMAT_VIDEO_MASK);
960         fmt = ast_best_codec(tmp->nativeformats);
961
962         if (i->rtp) {
963                 ast_rtp_setstun(i->rtp, 1);
964                 ast_channel_set_fd(tmp, 0, ast_rtp_fd(i->rtp));
965                 ast_channel_set_fd(tmp, 1, ast_rtcp_fd(i->rtp));
966         }
967         if (i->vrtp) {
968                 ast_rtp_setstun(i->rtp, 1);
969                 ast_channel_set_fd(tmp, 2, ast_rtp_fd(i->vrtp));
970                 ast_channel_set_fd(tmp, 3, ast_rtcp_fd(i->vrtp));
971         }
972         if (state == AST_STATE_RING)
973                 tmp->rings = 1;
974         tmp->adsicpe = AST_ADSI_UNAVAILABLE;
975         tmp->writeformat = fmt;
976         tmp->rawwriteformat = fmt;
977         tmp->readformat = fmt;
978         tmp->rawreadformat = fmt;
979         tmp->tech_pvt = i;
980
981         tmp->callgroup = client->callgroup;
982         tmp->pickupgroup = client->pickupgroup;
983         tmp->cid.cid_pres = client->callingpres;
984         if (!ast_strlen_zero(client->accountcode))
985                 ast_string_field_set(tmp, accountcode, client->accountcode);
986         if (client->amaflags)
987                 tmp->amaflags = client->amaflags;
988         if (!ast_strlen_zero(client->language))
989                 ast_string_field_set(tmp, language, client->language);
990         if (!ast_strlen_zero(client->musicclass))
991                 ast_string_field_set(tmp, musicclass, client->musicclass);
992         i->owner = tmp;
993         ast_module_ref(ast_module_info->self);
994         ast_copy_string(tmp->context, client->context, sizeof(tmp->context));
995         ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
996         /* Don't use ast_set_callerid() here because it will
997          * generate a needless NewCallerID event */
998         if (!strcasecmp(client->name, "guest")) {
999                 data = ast_strdupa(i->them);
1000                 if (strchr(data, '/')) {
1001                         cid = strsep(&data, "/");
1002                 } else
1003                         cid = data;
1004         } else {
1005                 data =  ast_strdupa(client->user);
1006                 cid = data;
1007         }
1008         cid = strsep(&cid, "@");
1009         tmp->cid.cid_ani = ast_strdup(cid);
1010         if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
1011                 tmp->cid.cid_dnid = ast_strdup(i->exten);
1012         tmp->priority = 1;
1013         if (i->rtp)
1014                 ast_jb_configure(tmp, &global_jbconf);
1015         if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
1016                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
1017                 tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
1018                 ast_hangup(tmp);
1019                 tmp = NULL;
1020         }
1021
1022         return tmp;
1023 }
1024
1025 static int gtalk_action(struct gtalk *client, struct gtalk_pvt *p, const char *action)
1026 {
1027         iks *request, *session = NULL;
1028         int res = -1;
1029
1030         request = iks_new("iq");
1031         if (request) {
1032                 iks_insert_attrib(request, "type", "set");
1033                 iks_insert_attrib(request, "from", p->us);
1034                 iks_insert_attrib(request, "to", p->them);
1035                 iks_insert_attrib(request, "id", client->connection->mid);
1036                 ast_aji_increment_mid(client->connection->mid);
1037                 session = iks_new("session");
1038                 if (session) {
1039                         iks_insert_attrib(session, "type", action);
1040                         iks_insert_attrib(session, "id", p->sid);
1041                         iks_insert_attrib(session, "initiator", p->initiator ? p->us : p->them);
1042                         iks_insert_attrib(session, "xmlns", "http://www.google.com/session");
1043                         iks_insert_node(request, session);
1044                         iks_send(client->connection->p, request);
1045                         iks_delete(session);
1046                         res = 0;
1047                 }
1048                 iks_delete(request);
1049         }
1050         return res;
1051 }
1052
1053 static void gtalk_free_candidates(struct gtalk_candidate *candidate)
1054 {
1055         struct gtalk_candidate *last;
1056         while (candidate) {
1057                 last = candidate;
1058                 candidate = candidate->next;
1059                 ast_free(last);
1060         }
1061 }
1062
1063 static void gtalk_free_pvt(struct gtalk *client, struct gtalk_pvt *p)
1064 {
1065         struct gtalk_pvt *cur, *prev = NULL;
1066         cur = client->p;
1067         while (cur) {
1068                 if (cur == p) {
1069                         if (prev)
1070                                 prev->next = p->next;
1071                         else
1072                                 client->p = p->next;
1073                         break;
1074                 }
1075                 prev = cur;
1076                 cur = cur->next;
1077         }
1078         if (p->ringrule)
1079                 iks_filter_remove_rule(p->parent->connection->f, p->ringrule);
1080         if (p->owner)
1081                 ast_log(LOG_WARNING, "Uh oh, there's an owner, this is going to be messy.\n");
1082         if (p->rtp)
1083                 ast_rtp_destroy(p->rtp);
1084         if (p->vrtp)
1085                 ast_rtp_destroy(p->vrtp);
1086         gtalk_free_candidates(p->theircandidates);
1087         ast_free(p);
1088 }
1089
1090
1091 static int gtalk_newcall(struct gtalk *client, ikspak *pak)
1092 {
1093         struct gtalk_pvt *p, *tmp = client->p;
1094         struct ast_channel *chan;
1095         int res;
1096         iks *codec;
1097         char *from = NULL;
1098         /* Make sure our new call doesn't exist yet */
1099         from = iks_find_attrib(pak->x,"to");
1100         if(!from)
1101                 from = client->connection->jid->full;
1102         
1103         while (tmp) {
1104                 if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid)) {
1105                         ast_log(LOG_NOTICE, "Ignoring duplicate call setup on SID %s\n", tmp->sid);
1106                         gtalk_response(client, from, pak, "out-of-order", NULL);
1107                         return -1;
1108                 }
1109                 tmp = tmp->next;
1110         }
1111
1112         p = gtalk_alloc(client, from, pak->from->full, iks_find_attrib(pak->query, "id"));
1113         if (!p) {
1114                 ast_log(LOG_WARNING, "Unable to allocate gtalk structure!\n");
1115                 return -1;
1116         }
1117         chan = gtalk_new(client, p, AST_STATE_DOWN, pak->from->user);
1118         if (chan) {
1119                 ast_mutex_lock(&p->lock);
1120                 ast_copy_string(p->them, pak->from->full, sizeof(p->them));
1121                 if (iks_find_attrib(pak->query, "id")) {
1122                         ast_copy_string(p->sid, iks_find_attrib(pak->query, "id"),
1123                                                         sizeof(p->sid));
1124                 }
1125
1126                 codec = iks_child(iks_child(iks_child(pak->x)));
1127                 while (codec) {
1128                         ast_rtp_set_m_type(p->rtp, atoi(iks_find_attrib(codec, "id")));
1129                         ast_rtp_set_rtpmap_type(p->rtp, atoi(iks_find_attrib(codec, "id")), "audio",
1130                                                 iks_find_attrib(codec, "name"), 0);
1131                         codec = iks_next(codec);
1132                 }
1133                 
1134                 ast_mutex_unlock(&p->lock);
1135                 ast_setstate(chan, AST_STATE_RING);
1136                 res = ast_pbx_start(chan);
1137
1138                 switch (res) {
1139                 case AST_PBX_FAILED:
1140                         ast_log(LOG_WARNING, "Failed to start PBX :(\n");
1141                         gtalk_response(client, from, pak, "service-unavailable", NULL);
1142                         break;
1143                 case AST_PBX_CALL_LIMIT:
1144                         ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
1145                         gtalk_response(client, from, pak, "service-unavailable", NULL);
1146                         break;
1147                 case AST_PBX_SUCCESS:
1148                         gtalk_response(client, from, pak, NULL, NULL);
1149                         gtalk_invite_response(p, p->them, p->us,p->sid, 0);
1150                         gtalk_create_candidates(client, p, p->sid, p->them, p->us);
1151                         /* nothing to do */
1152                         break;
1153                 }
1154         } else {
1155                 gtalk_free_pvt(client, p);
1156         }
1157         return 1;
1158 }
1159
1160 static int gtalk_update_stun(struct gtalk *client, struct gtalk_pvt *p)
1161 {
1162         struct gtalk_candidate *tmp;
1163         struct hostent *hp;
1164         struct ast_hostent ahp;
1165         struct sockaddr_in sin;
1166         struct sockaddr_in aux;
1167
1168         if (time(NULL) == p->laststun)
1169                 return 0;
1170
1171         tmp = p->theircandidates;
1172         p->laststun = time(NULL);
1173         while (tmp) {
1174                 char username[256];
1175
1176                 /* Find the IP address of the host */
1177                 hp = ast_gethostbyname(tmp->ip, &ahp);
1178                 sin.sin_family = AF_INET;
1179                 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
1180                 sin.sin_port = htons(tmp->port);
1181                 snprintf(username, sizeof(username), "%s%s", tmp->username,
1182                          p->ourcandidates->username);
1183                 
1184                 /* Find out the result of the STUN */
1185                 ast_rtp_get_peer(p->rtp, &aux);
1186
1187                 /* If the STUN result is different from the IP of the hostname,
1188                         lock on the stun IP of the hostname advertised by the
1189                         remote client */
1190                 if (aux.sin_addr.s_addr && 
1191                     aux.sin_addr.s_addr != sin.sin_addr.s_addr)
1192                         ast_rtp_stun_request(p->rtp, &aux, username);
1193                 else 
1194                         ast_rtp_stun_request(p->rtp, &sin, username);
1195                 
1196                 if (aux.sin_addr.s_addr) {
1197                         ast_debug(4, "Receiving RTP traffic from IP %s, matches with remote candidate's IP %s\n", ast_inet_ntoa(aux.sin_addr), tmp->ip);
1198                         ast_debug(4, "Sending STUN request to %s\n", tmp->ip);
1199                 }
1200
1201                 tmp = tmp->next;
1202         }
1203         return 1;
1204 }
1205
1206 static int gtalk_add_candidate(struct gtalk *client, ikspak *pak)
1207 {
1208         struct gtalk_pvt *p = NULL, *tmp = NULL;
1209         struct aji_client *c = client->connection;
1210         struct gtalk_candidate *newcandidate = NULL;
1211         iks *traversenodes = NULL, *receipt = NULL;
1212         char *from;
1213
1214         from = iks_find_attrib(pak->x,"to");
1215         if(!from)
1216                 from = c->jid->full;
1217
1218         for (tmp = client->p; tmp; tmp = tmp->next) {
1219                 if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid)) {
1220                         p = tmp;
1221                         break;
1222                 }
1223         }
1224
1225         if (!p)
1226                 return -1;
1227
1228         traversenodes = pak->query;
1229         while(traversenodes) {
1230                 if(!strcasecmp(iks_name(traversenodes), "session")) {
1231                         traversenodes = iks_child(traversenodes);
1232                         continue;
1233                 }
1234                 if(!strcasecmp(iks_name(traversenodes), "transport")) {
1235                         traversenodes = iks_child(traversenodes);
1236                         continue;
1237                 }
1238                 if(!strcasecmp(iks_name(traversenodes), "candidate")) {
1239                         newcandidate = ast_calloc(1, sizeof(*newcandidate));
1240                         if (!newcandidate)
1241                                 return 0;
1242                         ast_copy_string(newcandidate->name, iks_find_attrib(traversenodes, "name"),
1243                                                         sizeof(newcandidate->name));
1244                         ast_copy_string(newcandidate->ip, iks_find_attrib(traversenodes, "address"),
1245                                                         sizeof(newcandidate->ip));
1246                         newcandidate->port = atoi(iks_find_attrib(traversenodes, "port"));
1247                         ast_copy_string(newcandidate->username, iks_find_attrib(traversenodes, "username"),
1248                                                         sizeof(newcandidate->username));
1249                         ast_copy_string(newcandidate->password, iks_find_attrib(traversenodes, "password"),
1250                                                         sizeof(newcandidate->password));
1251                         newcandidate->preference = atof(iks_find_attrib(traversenodes, "preference"));
1252                         if (!strcasecmp(iks_find_attrib(traversenodes, "protocol"), "udp"))
1253                                 newcandidate->protocol = AJI_PROTOCOL_UDP;
1254                         if (!strcasecmp(iks_find_attrib(traversenodes, "protocol"), "ssltcp"))
1255                                 newcandidate->protocol = AJI_PROTOCOL_SSLTCP;
1256                 
1257                         if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "stun"))
1258                                 newcandidate->type = AJI_CONNECT_STUN;
1259                         if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "local"))
1260                                 newcandidate->type = AJI_CONNECT_LOCAL;
1261                         if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "relay"))
1262                                 newcandidate->type = AJI_CONNECT_RELAY;
1263                         ast_copy_string(newcandidate->network, iks_find_attrib(traversenodes, "network"),
1264                                                         sizeof(newcandidate->network));
1265                         newcandidate->generation = atoi(iks_find_attrib(traversenodes, "generation"));
1266                         newcandidate->next = NULL;
1267                 
1268                         newcandidate->next = p->theircandidates;
1269                         p->theircandidates = newcandidate;
1270                         p->laststun = 0;
1271                         gtalk_update_stun(p->parent, p);
1272                         newcandidate = NULL;
1273                 }
1274                 traversenodes = iks_next(traversenodes);
1275         }
1276         
1277         receipt = iks_new("iq");
1278         iks_insert_attrib(receipt, "type", "result");
1279         iks_insert_attrib(receipt, "from", from);
1280         iks_insert_attrib(receipt, "to", iks_find_attrib(pak->x, "from"));
1281         iks_insert_attrib(receipt, "id", iks_find_attrib(pak->x, "id"));
1282         iks_send(c->p, receipt);
1283         iks_delete(receipt);
1284
1285         return 1;
1286 }
1287
1288 static struct ast_frame *gtalk_rtp_read(struct ast_channel *ast, struct gtalk_pvt *p)
1289 {
1290         struct ast_frame *f;
1291
1292         if (!p->rtp)
1293                 return &ast_null_frame;
1294         f = ast_rtp_read(p->rtp);
1295         gtalk_update_stun(p->parent, p);
1296         if (p->owner) {
1297                 /* We already hold the channel lock */
1298                 if (f->frametype == AST_FRAME_VOICE) {
1299                         if (f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
1300                                 ast_debug(1, "Oooh, format changed to %d\n", f->subclass);
1301                                 p->owner->nativeformats =
1302                                         (p->owner->nativeformats & AST_FORMAT_VIDEO_MASK) | f->subclass;
1303                                 ast_set_read_format(p->owner, p->owner->readformat);
1304                                 ast_set_write_format(p->owner, p->owner->writeformat);
1305                         }
1306 /*                      if ((ast_test_flag(p, SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
1307                                 f = ast_dsp_process(p->owner, p->vad, f);
1308                                 if (option_debug && f && (f->frametype == AST_FRAME_DTMF))
1309                                         ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass);
1310                         } */
1311                 }
1312         }
1313         return f;
1314 }
1315
1316 static struct ast_frame *gtalk_read(struct ast_channel *ast)
1317 {
1318         struct ast_frame *fr;
1319         struct gtalk_pvt *p = ast->tech_pvt;
1320
1321         ast_mutex_lock(&p->lock);
1322         fr = gtalk_rtp_read(ast, p);
1323         ast_mutex_unlock(&p->lock);
1324         return fr;
1325 }
1326
1327 /*! \brief Send frame to media channel (rtp) */
1328 static int gtalk_write(struct ast_channel *ast, struct ast_frame *frame)
1329 {
1330         struct gtalk_pvt *p = ast->tech_pvt;
1331         int res = 0;
1332
1333         switch (frame->frametype) {
1334         case AST_FRAME_VOICE:
1335                 if (!(frame->subclass & ast->nativeformats)) {
1336                         ast_log(LOG_WARNING,
1337                                         "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
1338                                         frame->subclass, ast->nativeformats, ast->readformat,
1339                                         ast->writeformat);
1340                         return 0;
1341                 }
1342                 if (p) {
1343                         ast_mutex_lock(&p->lock);
1344                         if (p->rtp) {
1345                                 res = ast_rtp_write(p->rtp, frame);
1346                         }
1347                         ast_mutex_unlock(&p->lock);
1348                 }
1349                 break;
1350         case AST_FRAME_VIDEO:
1351                 if (p) {
1352                         ast_mutex_lock(&p->lock);
1353                         if (p->vrtp) {
1354                                 res = ast_rtp_write(p->vrtp, frame);
1355                         }
1356                         ast_mutex_unlock(&p->lock);
1357                 }
1358                 break;
1359         case AST_FRAME_IMAGE:
1360                 return 0;
1361                 break;
1362         default:
1363                 ast_log(LOG_WARNING, "Can't send %d type frames with Gtalk write\n",
1364                                 frame->frametype);
1365                 return 0;
1366         }
1367
1368         return res;
1369 }
1370
1371 static int gtalk_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1372 {
1373         struct gtalk_pvt *p = newchan->tech_pvt;
1374         ast_mutex_lock(&p->lock);
1375
1376         if ((p->owner != oldchan)) {
1377                 ast_mutex_unlock(&p->lock);
1378                 return -1;
1379         }
1380         if (p->owner == oldchan)
1381                 p->owner = newchan;
1382         ast_mutex_unlock(&p->lock);
1383         return 0;
1384 }
1385
1386 static int gtalk_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
1387 {
1388         int res = 0;
1389
1390         switch (condition) {
1391         case AST_CONTROL_HOLD:
1392                 ast_moh_start(ast, data, NULL);
1393                 break;
1394         case AST_CONTROL_UNHOLD:
1395                 ast_moh_stop(ast);
1396                 break;
1397         default:
1398                 ast_log(LOG_NOTICE, "Don't know how to indicate condition '%d'\n", condition);
1399                 res = -1;
1400         }
1401
1402         return res;
1403 }
1404
1405 static int gtalk_digit_begin(struct ast_channel *chan, char digit)
1406 {
1407         return gtalk_digit(chan, digit, 0);
1408 }
1409
1410 static int gtalk_digit_end(struct ast_channel *chan, char digit, unsigned int duration)
1411 {
1412         return gtalk_digit(chan, digit, duration);
1413 }
1414
1415 static int gtalk_digit(struct ast_channel *ast, char digit, unsigned int duration)
1416 {
1417         struct gtalk_pvt *p = ast->tech_pvt;
1418         struct gtalk *client = p->parent;
1419         iks *iq, *gtalk, *dtmf;
1420         char buffer[2] = {digit, '\0'};
1421         iq = iks_new("iq");
1422         gtalk = iks_new("gtalk");
1423         dtmf = iks_new("dtmf");
1424         if(!iq || !gtalk || !dtmf) {
1425                 if(iq)
1426                         iks_delete(iq);
1427                 if(gtalk)
1428                         iks_delete(gtalk);
1429                 if(dtmf)
1430                         iks_delete(dtmf);
1431                 ast_log(LOG_ERROR, "Did not send dtmf do to memory issue\n");
1432                 return -1;
1433         }
1434
1435         iks_insert_attrib(iq, "type", "set");
1436         iks_insert_attrib(iq, "to", p->them);
1437         iks_insert_attrib(iq, "from", p->us);
1438         iks_insert_attrib(iq, "id", client->connection->mid);
1439         ast_aji_increment_mid(client->connection->mid);
1440         iks_insert_attrib(gtalk, "xmlns", "http://jabber.org/protocol/gtalk");
1441         iks_insert_attrib(gtalk, "action", "session-info");
1442         iks_insert_attrib(gtalk, "initiator", p->initiator ? p->us: p->them);
1443         iks_insert_attrib(gtalk, "sid", p->sid);
1444         iks_insert_attrib(dtmf, "xmlns", "http://jabber.org/protocol/gtalk/info/dtmf");
1445         iks_insert_attrib(dtmf, "code", buffer);
1446         iks_insert_node(iq, gtalk);
1447         iks_insert_node(gtalk, dtmf);
1448
1449         ast_mutex_lock(&p->lock);
1450         if (ast->dtmff.frametype == AST_FRAME_DTMF_BEGIN || duration == 0) {
1451                 iks_insert_attrib(dtmf, "action", "button-down");
1452         } else if (ast->dtmff.frametype == AST_FRAME_DTMF_END || duration != 0) {
1453                 iks_insert_attrib(dtmf, "action", "button-up");
1454         }
1455         iks_send(client->connection->p, iq);
1456         iks_delete(iq);
1457         iks_delete(gtalk);
1458         iks_delete(dtmf);
1459         ast_mutex_unlock(&p->lock);
1460         return 0;
1461 }
1462
1463 static int gtalk_sendhtml(struct ast_channel *ast, int subclass, const char *data, int datalen)
1464 {
1465         ast_log(LOG_NOTICE, "XXX Implement gtalk sendhtml XXX\n");
1466
1467         return -1;
1468 }
1469
1470 /* Not in use right now.
1471 static int gtalk_auto_congest(void *nothing)
1472 {
1473         struct gtalk_pvt *p = nothing;
1474
1475         ast_mutex_lock(&p->lock);
1476         if (p->owner) {
1477                 if (!ast_channel_trylock(p->owner)) {
1478                         ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
1479                         ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
1480                         ast_channel_unlock(p->owner);
1481                 }
1482         }
1483         ast_mutex_unlock(&p->lock);
1484         return 0;
1485 }
1486 */
1487
1488 /*! \brief Initiate new call, part of PBX interface 
1489  *      dest is the dial string */
1490 static int gtalk_call(struct ast_channel *ast, char *dest, int timeout)
1491 {
1492         struct gtalk_pvt *p = ast->tech_pvt;
1493
1494         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
1495                 ast_log(LOG_WARNING, "gtalk_call called on %s, neither down nor reserved\n", ast->name);
1496                 return -1;
1497         }
1498
1499         ast_setstate(ast, AST_STATE_RING);
1500         p->jointcapability = p->capability;
1501         if (!p->ringrule) {
1502                 ast_copy_string(p->ring, p->parent->connection->mid, sizeof(p->ring));
1503                 p->ringrule = iks_filter_add_rule(p->parent->connection->f, gtalk_ringing_ack, p,
1504                                                         IKS_RULE_ID, p->ring, IKS_RULE_DONE);
1505         } else
1506                 ast_log(LOG_WARNING, "Whoa, already have a ring rule!\n");
1507
1508         gtalk_invite(p, p->them, p->us, p->sid, 1);
1509         gtalk_create_candidates(p->parent, p, p->sid, p->them, p->us);
1510
1511         return 0;
1512 }
1513
1514 /*! \brief Hangup a call through the gtalk proxy channel */
1515 static int gtalk_hangup(struct ast_channel *ast)
1516 {
1517         struct gtalk_pvt *p = ast->tech_pvt;
1518         struct gtalk *client;
1519
1520         ast_mutex_lock(&p->lock);
1521         client = p->parent;
1522         p->owner = NULL;
1523         ast->tech_pvt = NULL;
1524         if (!p->alreadygone)
1525                 gtalk_action(client, p, "terminate");
1526         ast_mutex_unlock(&p->lock);
1527
1528         gtalk_free_pvt(client, p);
1529         ast_module_unref(ast_module_info->self);
1530
1531         return 0;
1532 }
1533
1534 /*! \brief Part of PBX interface */
1535 static struct ast_channel *gtalk_request(const char *type, int format, void *data, int *cause)
1536 {
1537         struct gtalk_pvt *p = NULL;
1538         struct gtalk *client = NULL;
1539         char *sender = NULL, *to = NULL, *s = NULL;
1540         struct ast_channel *chan = NULL;
1541
1542         if (data) {
1543                 s = ast_strdupa(data);
1544                 if (s) {
1545                         sender = strsep(&s, "/");
1546                         if (sender && (sender[0] != '\0'))
1547                                 to = strsep(&s, "/");
1548                         if (!to) {
1549                                 ast_log(LOG_ERROR, "Bad arguments in Gtalk Dialstring: %s\n", (char*) data);
1550                                 return NULL;
1551                         }
1552                 }
1553         }
1554         client = find_gtalk(to, sender);
1555         if (!client) {
1556                 ast_log(LOG_WARNING, "Could not find recipient.\n");
1557                 return NULL;
1558         }
1559         ASTOBJ_WRLOCK(client);
1560         p = gtalk_alloc(client, strchr(sender, '@') ? sender : client->connection->jid->full, strchr(to, '@') ? to : client->user, NULL);
1561         if (p)
1562                 chan = gtalk_new(client, p, AST_STATE_DOWN, to);
1563
1564         ASTOBJ_UNLOCK(client);
1565         return chan;
1566 }
1567
1568 /*! \brief CLI command "gtalk show channels" */
1569 static char *gtalk_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1570 {
1571 #define FORMAT  "%-30.30s  %-30.30s  %-15.15s  %-5.5s %-5.5s \n"
1572         struct gtalk_pvt *p;
1573         struct ast_channel *chan;
1574         int numchans = 0;
1575         char them[AJI_MAX_JIDLEN];
1576         char *jid = NULL;
1577         char *resource = NULL;
1578
1579         switch (cmd) {
1580         case CLI_INIT:
1581                 e->command = "gtalk show channels";
1582                 e->usage =
1583                         "Usage: gtalk show channels\n"
1584                         "       Shows current state of the Gtalk channels.\n";
1585                 return NULL;
1586         case CLI_GENERATE:
1587                 return NULL;
1588         }
1589
1590         if (a->argc != 3)
1591                 return CLI_SHOWUSAGE;
1592
1593         ast_mutex_lock(&gtalklock);
1594         ast_cli(a->fd, FORMAT, "Channel", "Jabber ID", "Resource", "Read", "Write");
1595         ASTOBJ_CONTAINER_TRAVERSE(&gtalk_list, 1, {
1596                 ASTOBJ_WRLOCK(iterator);
1597                 p = iterator->p;
1598                 while(p) {
1599                         chan = p->owner;
1600                         ast_copy_string(them, p->them, sizeof(them));
1601                         jid = them;
1602                         resource = strchr(them, '/');
1603                         if (!resource)
1604                                 resource = "None";
1605                         else {
1606                                 *resource = '\0';
1607                                 resource ++;
1608                         }
1609                         if (chan)
1610                                 ast_cli(a->fd, FORMAT, 
1611                                         chan->name,
1612                                         jid,
1613                                         resource,
1614                                         ast_getformatname(chan->readformat),
1615                                         ast_getformatname(chan->writeformat)                                    
1616                                         );
1617                         else 
1618                                 ast_log(LOG_WARNING, "No available channel\n");
1619                         numchans ++;
1620                         p = p->next;
1621                 }
1622                 ASTOBJ_UNLOCK(iterator);
1623         });
1624
1625         ast_mutex_unlock(&gtalklock);
1626
1627         ast_cli(a->fd, "%d active gtalk channel%s\n", numchans, (numchans != 1) ? "s" : "");
1628         return CLI_SUCCESS;
1629 #undef FORMAT
1630 }
1631
1632 /*! \brief CLI command "gtalk reload" */
1633 static char *gtalk_do_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1634 {
1635         switch (cmd) {
1636         case CLI_INIT:
1637                 e->command = "gtalk reload";
1638                 e->usage =
1639                         "Usage: gtalk reload\n"
1640                         "       Reload gtalk channel driver.\n";
1641                 return NULL;
1642         case CLI_GENERATE:
1643                 return NULL;
1644         }       
1645         
1646         ast_verbose("IT DOES WORK!\n");
1647         return CLI_SUCCESS;
1648 }
1649
1650 static int gtalk_parser(void *data, ikspak *pak)
1651 {
1652         struct gtalk *client = ASTOBJ_REF((struct gtalk *) data);
1653
1654         if (iks_find_with_attrib(pak->x, "session", "type", "initiate")) {
1655                 /* New call */
1656                 gtalk_newcall(client, pak);
1657         } else if (iks_find_with_attrib(pak->x, "session", "type", "candidates") || iks_find_with_attrib(pak->x, "session", "type", "transport-info")) {
1658                 ast_debug(3, "About to add candidate!\n");
1659                 gtalk_add_candidate(client, pak);
1660                 ast_debug(3, "Candidate Added!\n");
1661         } else if (iks_find_with_attrib(pak->x, "session", "type", "accept")) {
1662                 gtalk_is_answered(client, pak);
1663         } else if (iks_find_with_attrib(pak->x, "session", "type", "transport-accept")) {
1664                 gtalk_is_accepted(client, pak);
1665         } else if (iks_find_with_attrib(pak->x, "session", "type", "content-info") || iks_find_with_attrib(pak->x, "gtalk", "action", "session-info")) {
1666                 gtalk_handle_dtmf(client, pak);
1667         } else if (iks_find_with_attrib(pak->x, "session", "type", "terminate")) {
1668                 gtalk_hangup_farend(client, pak);
1669         } else if (iks_find_with_attrib(pak->x, "session", "type", "reject")) {
1670                 gtalk_hangup_farend(client, pak);
1671         }
1672         ASTOBJ_UNREF(client, gtalk_member_destroy);
1673         return IKS_FILTER_EAT;
1674 }
1675
1676 /* Not using this anymore probably take out soon 
1677 static struct gtalk_candidate *gtalk_create_candidate(char *args)
1678 {
1679         char *name, *type, *preference, *protocol;
1680         struct gtalk_candidate *res;
1681         res = ast_calloc(1, sizeof(*res));
1682         if (args)
1683                 name = args;
1684         if ((args = strchr(args, ','))) {
1685                 *args = '\0';
1686                 args++;
1687                 preference = args;
1688         }
1689         if ((args = strchr(args, ','))) {
1690                 *args = '\0';
1691                 args++;
1692                 protocol = args;
1693         }
1694         if ((args = strchr(args, ','))) {
1695                 *args = '\0';
1696                 args++;
1697                 type = args;
1698         }
1699         if (name)
1700                 ast_copy_string(res->name, name, sizeof(res->name));
1701         if (preference) {
1702                 res->preference = atof(preference);
1703         }
1704         if (protocol) {
1705                 if (!strcasecmp("udp", protocol))
1706                         res->protocol = AJI_PROTOCOL_UDP;
1707                 if (!strcasecmp("ssltcp", protocol))
1708                         res->protocol = AJI_PROTOCOL_SSLTCP;
1709         }
1710         if (type) {
1711                 if (!strcasecmp("stun", type))
1712                         res->type = AJI_CONNECT_STUN;
1713                 if (!strcasecmp("local", type))
1714                         res->type = AJI_CONNECT_LOCAL;
1715                 if (!strcasecmp("relay", type))
1716                         res->type = AJI_CONNECT_RELAY;
1717         }
1718
1719         return res;
1720 }
1721 */
1722
1723 static int gtalk_create_member(char *label, struct ast_variable *var, int allowguest,
1724                                                                 struct ast_codec_pref prefs, char *context,
1725                                                                 struct gtalk *member)
1726 {
1727         struct aji_client *client;
1728
1729         if (!member)
1730                 ast_log(LOG_WARNING, "Out of memory.\n");
1731
1732         ast_copy_string(member->name, label, sizeof(member->name));
1733         ast_copy_string(member->user, label, sizeof(member->user));
1734         ast_copy_string(member->context, context, sizeof(member->context));
1735         member->allowguest = allowguest;
1736         member->prefs = prefs;
1737         while (var) {
1738 #if 0
1739                 struct gtalk_candidate *candidate = NULL;
1740 #endif
1741                 if (!strcasecmp(var->name, "username"))
1742                         ast_copy_string(member->user, var->value, sizeof(member->user));
1743                 else if (!strcasecmp(var->name, "disallow"))
1744                         ast_parse_allow_disallow(&member->prefs, &member->capability, var->value, 0);
1745                 else if (!strcasecmp(var->name, "allow"))
1746                         ast_parse_allow_disallow(&member->prefs, &member->capability, var->value, 1);
1747                 else if (!strcasecmp(var->name, "context"))
1748                         ast_copy_string(member->context, var->value, sizeof(member->context));
1749 #if 0
1750                 else if (!strcasecmp(var->name, "candidate")) {
1751                         candidate = gtalk_create_candidate(var->value);
1752                         if (candidate) {
1753                                 candidate->next = member->ourcandidates;
1754                                 member->ourcandidates = candidate;
1755                         }
1756                 }
1757 #endif
1758                 else if (!strcasecmp(var->name, "connection")) {
1759                         if ((client = ast_aji_get_client(var->value))) {
1760                                 member->connection = client;
1761                                 iks_filter_add_rule(client->f, gtalk_parser, member, 
1762                                                     IKS_RULE_TYPE, IKS_PAK_IQ, 
1763                                                     IKS_RULE_FROM_PARTIAL, member->user,
1764                                                     IKS_RULE_NS, "http://www.google.com/session",
1765                                                     IKS_RULE_DONE);
1766
1767                         } else {
1768                                 ast_log(LOG_ERROR, "connection referenced not found!\n");
1769                                 return 0;
1770                         }
1771                 }
1772                 var = var->next;
1773         }
1774         if (member->connection && member->user)
1775                 member->buddy = ASTOBJ_CONTAINER_FIND(&member->connection->buddies, member->user);
1776         else {
1777                 ast_log(LOG_ERROR, "No Connection or Username!\n");
1778         }
1779         return 1;
1780 }
1781
1782 static int gtalk_load_config(void)
1783 {
1784         char *cat = NULL;
1785         struct ast_config *cfg = NULL;
1786         char context[AST_MAX_CONTEXT];
1787         int allowguest = 1;
1788         struct ast_variable *var;
1789         struct gtalk *member;
1790         struct ast_codec_pref prefs;
1791         struct aji_client_container *clients;
1792         struct gtalk_candidate *global_candidates = NULL;
1793         struct hostent *hp;
1794         struct ast_hostent ahp;
1795         struct ast_flags config_flags = { 0 };
1796
1797         cfg = ast_config_load(GOOGLE_CONFIG, config_flags);
1798         if (!cfg)
1799                 return 0;
1800
1801         /* Copy the default jb config over global_jbconf */
1802         memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
1803
1804         cat = ast_category_browse(cfg, NULL);
1805         for (var = ast_variable_browse(cfg, "general"); var; var = var->next) {
1806                 /* handle jb conf */
1807                 if (!ast_jb_read_conf(&global_jbconf, var->name, var->value))
1808                         continue;
1809
1810                 if (!strcasecmp(var->name, "allowguest"))
1811                         allowguest =
1812                                 (ast_true(ast_variable_retrieve(cfg, "general", "allowguest"))) ? 1 : 0;
1813                 else if (!strcasecmp(var->name, "disallow"))
1814                         ast_parse_allow_disallow(&prefs, &global_capability, var->value, 0);
1815                 else if (!strcasecmp(var->name, "allow"))
1816                         ast_parse_allow_disallow(&prefs, &global_capability, var->value, 1);
1817                 else if (!strcasecmp(var->name, "context"))
1818                         ast_copy_string(context, var->value, sizeof(context));
1819                 else if (!strcasecmp(var->name, "bindaddr")) {
1820                         if (!(hp = ast_gethostbyname(var->value, &ahp))) {
1821                                 ast_log(LOG_WARNING, "Invalid address: %s\n", var->value);
1822                         } else {
1823                                 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
1824                         }
1825                 }
1826 /*  Idea to allow for custom candidates  */
1827 /*
1828                 else if (!strcasecmp(var->name, "candidate")) {
1829                         candidate = gtalk_create_candidate(var->value);
1830                         if (candidate) {
1831                                 candidate->next = global_candidates;
1832                                 global_candidates = candidate;
1833                         }
1834                 }
1835 */
1836         }
1837         while (cat) {
1838                 if (strcasecmp(cat, "general")) {
1839                         var = ast_variable_browse(cfg, cat);
1840                         member = ast_calloc(1, sizeof(*member));
1841                         ASTOBJ_INIT(member);
1842                         ASTOBJ_WRLOCK(member);
1843                         if (!strcasecmp(cat, "guest")) {
1844                                 ast_copy_string(member->name, "guest", sizeof(member->name));
1845                                 ast_copy_string(member->user, "guest", sizeof(member->user));
1846                                 ast_copy_string(member->context, context, sizeof(member->context));
1847                                 member->allowguest = allowguest;
1848                                 member->prefs = prefs;
1849                                 while (var) {
1850                                         if (!strcasecmp(var->name, "disallow"))
1851                                                 ast_parse_allow_disallow(&member->prefs, &member->capability,
1852                                                                                                  var->value, 0);
1853                                         else if (!strcasecmp(var->name, "allow"))
1854                                                 ast_parse_allow_disallow(&member->prefs, &member->capability,
1855                                                                                                  var->value, 1);
1856                                         else if (!strcasecmp(var->name, "context"))
1857                                                 ast_copy_string(member->context, var->value,
1858                                                                                 sizeof(member->context));
1859 /*  Idea to allow for custom candidates  */
1860 /*
1861                                         else if (!strcasecmp(var->name, "candidate")) {
1862                                                 candidate = gtalk_create_candidate(var->value);
1863                                                 if (candidate) {
1864                                                         candidate->next = member->ourcandidates;
1865                                                         member->ourcandidates = candidate;
1866                                                 }
1867                                         }
1868 */
1869                                         var = var->next;
1870                                 }
1871                                 ASTOBJ_UNLOCK(member);
1872                                 clients = ast_aji_get_clients();
1873                                 if (clients) {
1874                                         ASTOBJ_CONTAINER_TRAVERSE(clients, 1, {
1875                                                 ASTOBJ_WRLOCK(iterator);
1876                                                 ASTOBJ_WRLOCK(member);
1877                                                 member->connection = iterator;
1878                                                 iks_filter_add_rule(iterator->f, gtalk_parser, member, IKS_RULE_TYPE, IKS_PAK_IQ, IKS_RULE_NS, "http://www.google.com/session", IKS_RULE_DONE);
1879                                                 iks_filter_add_rule(iterator->f, gtalk_parser, member, IKS_RULE_TYPE, IKS_PAK_IQ, IKS_RULE_NS, "http://jabber.org/protocol/gtalk", IKS_RULE_DONE);
1880                                                 ASTOBJ_UNLOCK(member);
1881                                                 ASTOBJ_CONTAINER_LINK(&gtalk_list, member);
1882                                                 ASTOBJ_UNLOCK(iterator);
1883                                         });
1884                                 } else {
1885                                         ASTOBJ_UNLOCK(member);
1886                                         ASTOBJ_UNREF(member, gtalk_member_destroy);
1887                                 }
1888                         } else {
1889                                 ASTOBJ_UNLOCK(member);
1890                                 if (gtalk_create_member(cat, var, allowguest, prefs, context, member))
1891                                         ASTOBJ_CONTAINER_LINK(&gtalk_list, member);
1892                                 ASTOBJ_UNREF(member, gtalk_member_destroy);
1893                         }
1894                 }
1895                 cat = ast_category_browse(cfg, cat);
1896         }
1897         gtalk_free_candidates(global_candidates);
1898         return 1;
1899 }
1900
1901 /*! \brief Load module into PBX, register channel */
1902 static int load_module(void)
1903 {
1904 #ifdef HAVE_GNUTLS      
1905         gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
1906 #endif /* HAVE_GNUTLS */
1907
1908         ASTOBJ_CONTAINER_INIT(&gtalk_list);
1909         if (!gtalk_load_config()) {
1910                 ast_log(LOG_ERROR, "Unable to read config file %s. Not loading module.\n", GOOGLE_CONFIG);
1911                 return 0;
1912         }
1913
1914         sched = sched_context_create();
1915         if (!sched) 
1916                 ast_log(LOG_WARNING, "Unable to create schedule context\n");
1917
1918         io = io_context_create();
1919         if (!io) 
1920                 ast_log(LOG_WARNING, "Unable to create I/O context\n");
1921
1922         if (ast_find_ourip(&__ourip, bindaddr)) {
1923                 ast_log(LOG_WARNING, "Unable to get own IP address, Gtalk disabled\n");
1924                 return 0;
1925         }
1926
1927         ast_rtp_proto_register(&gtalk_rtp);
1928         ast_cli_register_multiple(gtalk_cli, sizeof(gtalk_cli) / sizeof(gtalk_cli[0]));
1929
1930         /* Make sure we can register our channel type */
1931         if (ast_channel_register(&gtalk_tech)) {
1932                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", gtalk_tech.type);
1933                 return -1;
1934         }
1935         return 0;
1936 }
1937
1938 /*! \brief Reload module */
1939 static int reload(void)
1940 {
1941         return 0;
1942 }
1943
1944 /*! \brief Unload the gtalk channel from Asterisk */
1945 static int unload_module(void)
1946 {
1947         struct gtalk_pvt *privates = NULL;
1948         ast_cli_unregister_multiple(gtalk_cli, sizeof(gtalk_cli) / sizeof(gtalk_cli[0]));
1949         /* First, take us out of the channel loop */
1950         ast_channel_unregister(&gtalk_tech);
1951         ast_rtp_proto_unregister(&gtalk_rtp);
1952
1953         if (!ast_mutex_lock(&gtalklock)) {
1954                 /* Hangup all interfaces if they have an owner */
1955                 ASTOBJ_CONTAINER_TRAVERSE(&gtalk_list, 1, {
1956                         ASTOBJ_WRLOCK(iterator);
1957                         privates = iterator->p;
1958                         while(privates) {
1959                                 if (privates->owner)
1960                                         ast_softhangup(privates->owner, AST_SOFTHANGUP_APPUNLOAD);
1961                                 privates = privates->next;
1962                         }
1963                         iterator->p = NULL;
1964                         ASTOBJ_UNLOCK(iterator);
1965                 });
1966                 ast_mutex_unlock(&gtalklock);
1967         } else {
1968                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
1969                 return -1;
1970         }
1971         ASTOBJ_CONTAINER_DESTROYALL(&gtalk_list, gtalk_member_destroy);
1972         ASTOBJ_CONTAINER_DESTROY(&gtalk_list);
1973         return 0;
1974 }
1975
1976 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Gtalk Channel Driver",
1977                 .load = load_module,
1978                 .unload = unload_module,
1979                 .reload = reload,
1980                );