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