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