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