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