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