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