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