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