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