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