Merged revisions 60989 via svnmerge from
[asterisk/asterisk.git] / channels / chan_gtalk.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2005, Digium, Inc.
5  *
6  * Matt O'Gorman <mogorman@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \author Matt O'Gorman <mogorman@digium.com>
22  *
23  * \brief Gtalk Channel Driver, until google/libjingle works with jingle spec
24  * 
25  * \ingroup channel_drivers
26  */
27
28 /*** MODULEINFO
29         <depend>iksemel</depend>
30         <depend>res_jabber</depend>
31  ***/
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
261         if(strchr(connection, '@')) {
262                 s = ast_strdupa(connection);
263                 domain = strsep(&s, "@");
264                 ast_verbose("OOOOH domain = %s\n", domain);
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_RDLOCK(iterator);
273                         if (!strcasecmp(iterator->name, "guest")) {
274                                 if (!strcasecmp(iterator->connection->jid->partial, connection)) {
275                                         gtalk = iterator;
276                                 } else if (!strcasecmp(iterator->connection->name, connection)) {
277                                         gtalk = iterator;
278                                 } else if (iterator->connection->component && !strcasecmp(iterator->connection->user,domain)) {
279                                         gtalk = iterator;
280                                 }
281                         }
282                         ASTOBJ_UNLOCK(iterator);
283
284                         if (gtalk)
285                                 break;
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 if (client->buddy)
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
861         memcpy(&tmp->prefs, &client->prefs, sizeof(struct ast_codec_pref));
862
863         if (sid) {
864                 ast_copy_string(tmp->sid, sid, sizeof(tmp->sid));
865                 ast_copy_string(tmp->them, them, sizeof(tmp->them));
866                 ast_copy_string(tmp->us, us, sizeof(tmp->us));
867         } else {
868                 snprintf(tmp->sid, sizeof(tmp->sid), "%08lx%08lx", ast_random(), ast_random());
869                 ast_copy_string(tmp->them, idroster, sizeof(tmp->them));
870                 ast_copy_string(tmp->us, us, sizeof(tmp->us));
871                 tmp->initiator = 1;
872         }
873         tmp->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
874         tmp->parent = client;
875         if (!tmp->rtp) {
876                 ast_log(LOG_WARNING, "Out of RTP sessions?\n");
877                 free(tmp);
878                 return NULL;
879         }
880
881         if(strchr(tmp->us, '/')) {
882                 data = ast_strdupa(tmp->us);
883                 exten = strsep(&data, "/");
884         } else
885                 exten = tmp->us;
886         ast_copy_string(tmp->exten,  exten, sizeof(tmp->exten));
887         ast_mutex_init(&tmp->lock);
888         ast_mutex_lock(&gtalklock);
889         tmp->next = client->p;
890         client->p = tmp;
891         ast_mutex_unlock(&gtalklock);
892         return tmp;
893 }
894
895 /*! \brief Start new gtalk channel */
896 static struct ast_channel *gtalk_new(struct gtalk *client, struct gtalk_pvt *i, int state, const char *title)
897 {
898         struct ast_channel *tmp;
899         int fmt;
900         int what;
901         const char *n2;
902
903         if (title)
904                 n2 = title;
905         else
906                 n2 = i->us;
907         tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, client->accountcode, i->exten, client->context, client->amaflags, "Gtalk/%s-%04lx", n2, ast_random() & 0xffff);
908         if (!tmp) {
909                 ast_log(LOG_WARNING, "Unable to allocate Gtalk channel structure!\n");
910                 return NULL;
911         }
912         tmp->tech = &gtalk_tech;
913
914         /* Select our native format based on codec preference until we receive
915            something from another device to the contrary. */
916 /*      ast_verbose("XXXXXXXXXXXXX\nXXX i->jointcapability = %X\nXXX i->capability = %X\nXXX global_capability %X\n XXXXXXXXXXXX\n",i->jointcapability,i->capability,global_capability); */
917         if (i->jointcapability)
918                 what = i->jointcapability;
919         else if (i->capability)
920                 what = i->capability;
921         else
922                 what = global_capability;
923
924         /* Set Frame packetization */
925         if (i->rtp)
926                 ast_rtp_codec_setpref(i->rtp, &i->prefs);
927
928         tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | (i->jointcapability & AST_FORMAT_VIDEO_MASK);
929         fmt = ast_best_codec(tmp->nativeformats);
930
931         if (i->rtp) {
932                 ast_rtp_setstun(i->rtp, 1);
933                 tmp->fds[0] = ast_rtp_fd(i->rtp);
934                 tmp->fds[1] = ast_rtcp_fd(i->rtp);
935         }
936         if (i->vrtp) {
937                 ast_rtp_setstun(i->rtp, 1);
938                 tmp->fds[2] = ast_rtp_fd(i->vrtp);
939                 tmp->fds[3] = ast_rtcp_fd(i->vrtp);
940         }
941         if (state == AST_STATE_RING)
942                 tmp->rings = 1;
943         tmp->adsicpe = AST_ADSI_UNAVAILABLE;
944         tmp->writeformat = fmt;
945         tmp->rawwriteformat = fmt;
946         tmp->readformat = fmt;
947         tmp->rawreadformat = fmt;
948         tmp->tech_pvt = i;
949
950         tmp->callgroup = client->callgroup;
951         tmp->pickupgroup = client->pickupgroup;
952         tmp->cid.cid_pres = client->callingpres;
953         if (!ast_strlen_zero(client->accountcode))
954                 ast_string_field_set(tmp, accountcode, client->accountcode);
955         if (client->amaflags)
956                 tmp->amaflags = client->amaflags;
957         if (!ast_strlen_zero(client->language))
958                 ast_string_field_set(tmp, language, client->language);
959         if (!ast_strlen_zero(client->musicclass))
960                 ast_string_field_set(tmp, musicclass, client->musicclass);
961         i->owner = tmp;
962         ast_module_ref(ast_module_info->self);
963         ast_copy_string(tmp->context, client->context, sizeof(tmp->context));
964         ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
965         /* Don't use ast_set_callerid() here because it will
966          * generate a needless NewCallerID event */
967         tmp->cid.cid_num = ast_strdup(i->cid_num);
968         tmp->cid.cid_ani = ast_strdup(i->cid_num);
969         tmp->cid.cid_name = ast_strdup(i->cid_name);
970         if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
971                 tmp->cid.cid_dnid = ast_strdup(i->exten);
972         tmp->priority = 1;
973         if (i->rtp)
974                 ast_jb_configure(tmp, &global_jbconf);
975         if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
976                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
977                 tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
978                 ast_hangup(tmp);
979                 tmp = NULL;
980         }
981
982         return tmp;
983 }
984
985 static int gtalk_action(struct gtalk *client, struct gtalk_pvt *p, const char *action)
986 {
987         iks *request, *session = NULL;
988         int res = -1;
989
990         request = iks_new("iq");
991         if (request) {
992                 iks_insert_attrib(request, "type", "set");
993                 iks_insert_attrib(request, "from", p->us);
994                 iks_insert_attrib(request, "to", p->them);
995                 iks_insert_attrib(request, "id", client->connection->mid);
996                 ast_aji_increment_mid(client->connection->mid);
997                 session = iks_new("session");
998                 if (session) {
999                         iks_insert_attrib(session, "type", action);
1000                         iks_insert_attrib(session, "id", p->sid);
1001                         iks_insert_attrib(session, "initiator", p->initiator ? p->us : p->them);
1002                         iks_insert_attrib(session, "xmlns", "http://www.google.com/session");
1003                         iks_insert_node(request, session);
1004                         iks_send(client->connection->p, request);
1005                         iks_delete(session);
1006                         res = 0;
1007                 }
1008                 iks_delete(request);
1009         }
1010         return res;
1011 }
1012
1013 static void gtalk_free_candidates(struct gtalk_candidate *candidate)
1014 {
1015         struct gtalk_candidate *last;
1016         while (candidate) {
1017                 last = candidate;
1018                 candidate = candidate->next;
1019                 free(last);
1020         }
1021 }
1022
1023 static void gtalk_free_pvt(struct gtalk *client, struct gtalk_pvt *p)
1024 {
1025         struct gtalk_pvt *cur, *prev = NULL;
1026         cur = client->p;
1027         while (cur) {
1028                 if (cur == p) {
1029                         if (prev)
1030                                 prev->next = p->next;
1031                         else
1032                                 client->p = p->next;
1033                         break;
1034                 }
1035                 prev = cur;
1036                 cur = cur->next;
1037         }
1038         if (p->ringrule)
1039                 iks_filter_remove_rule(p->parent->connection->f, p->ringrule);
1040         if (p->owner)
1041                 ast_log(LOG_WARNING, "Uh oh, there's an owner, this is going to be messy.\n");
1042         if (p->rtp)
1043                 ast_rtp_destroy(p->rtp);
1044         if (p->vrtp)
1045                 ast_rtp_destroy(p->vrtp);
1046         gtalk_free_candidates(p->theircandidates);
1047         free(p);
1048 }
1049
1050
1051 static int gtalk_newcall(struct gtalk *client, ikspak *pak)
1052 {
1053         struct gtalk_pvt *p, *tmp = client->p;
1054         struct ast_channel *chan;
1055         int res;
1056         iks *codec;
1057         char *from = NULL;
1058         /* Make sure our new call doesn't exist yet */
1059         from = iks_find_attrib(pak->x,"to");
1060         if(!from)
1061                 from = client->connection->jid->full;
1062         
1063         while (tmp) {
1064                 if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid)) {
1065                         ast_log(LOG_NOTICE, "Ignoring duplicate call setup on SID %s\n", tmp->sid);
1066                         gtalk_response(client, from, pak, "out-of-order", NULL);
1067                         return -1;
1068                 }
1069                 tmp = tmp->next;
1070         }
1071
1072         p = gtalk_alloc(client, from, pak->from->full, iks_find_attrib(pak->query, "id"));
1073         if (!p) {
1074                 ast_log(LOG_WARNING, "Unable to allocate gtalk structure!\n");
1075                 return -1;
1076         }
1077         chan = gtalk_new(client, p, AST_STATE_DOWN, pak->from->user);
1078         if (chan) {
1079                 ast_mutex_lock(&p->lock);
1080                 ast_copy_string(p->them, pak->from->full, sizeof(p->them));
1081                 if (iks_find_attrib(pak->query, "id")) {
1082                         ast_copy_string(p->sid, iks_find_attrib(pak->query, "id"),
1083                                                         sizeof(p->sid));
1084                 }
1085
1086                 codec = iks_child(iks_child(iks_child(pak->x)));
1087                 while (codec) {
1088                         ast_rtp_set_m_type(p->rtp, atoi(iks_find_attrib(codec, "id")));
1089                         ast_rtp_set_rtpmap_type(p->rtp, atoi(iks_find_attrib(codec, "id")), "audio",
1090                                                 iks_find_attrib(codec, "name"), 0);
1091                         codec = iks_next(codec);
1092                 }
1093                 
1094                 ast_mutex_unlock(&p->lock);
1095                 ast_setstate(chan, AST_STATE_RING);
1096                 res = ast_pbx_start(chan);
1097
1098                 switch (res) {
1099                 case AST_PBX_FAILED:
1100                         ast_log(LOG_WARNING, "Failed to start PBX :(\n");
1101                         gtalk_response(client, from, pak, "service-unavailable", NULL);
1102                         break;
1103                 case AST_PBX_CALL_LIMIT:
1104                         ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
1105                         gtalk_response(client, from, pak, "service-unavailable", NULL);
1106                         break;
1107                 case AST_PBX_SUCCESS:
1108                         gtalk_response(client, from, pak, NULL, NULL);
1109                         gtalk_invite_response(p, p->them, p->us,p->sid, 0);
1110                         gtalk_create_candidates(client, p, p->sid, p->them, p->us);
1111                         /* nothing to do */
1112                         break;
1113                 }
1114         } else {
1115                 gtalk_free_pvt(client, p);
1116         }
1117         return 1;
1118 }
1119
1120 static int gtalk_update_stun(struct gtalk *client, struct gtalk_pvt *p)
1121 {
1122         struct gtalk_candidate *tmp;
1123         struct hostent *hp;
1124         struct ast_hostent ahp;
1125         struct sockaddr_in sin;
1126
1127         if (time(NULL) == p->laststun)
1128                 return 0;
1129
1130         tmp = p->theircandidates;
1131         p->laststun = time(NULL);
1132         while (tmp) {
1133                 char username[256];
1134                 hp = ast_gethostbyname(tmp->ip, &ahp);
1135                 sin.sin_family = AF_INET;
1136                 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
1137                 sin.sin_port = htons(tmp->port);
1138                 snprintf(username, sizeof(username), "%s%s", tmp->username,
1139                                  p->ourcandidates->username);
1140
1141                 ast_rtp_stun_request(p->rtp, &sin, username);
1142                 tmp = tmp->next;
1143         }
1144         return 1;
1145 }
1146
1147 static int gtalk_add_candidate(struct gtalk *client, ikspak *pak)
1148 {
1149         struct gtalk_pvt *p = NULL, *tmp = NULL;
1150         struct aji_client *c = client->connection;
1151         struct gtalk_candidate *newcandidate = NULL;
1152         iks *traversenodes = NULL, *receipt = NULL;
1153         char *from;
1154
1155         from = iks_find_attrib(pak->x,"to");
1156         if(!from)
1157                 from = c->jid->full;
1158
1159         newcandidate = ast_calloc(1, sizeof(*newcandidate));
1160         if (!newcandidate)
1161                 return 0;
1162         for (tmp = client->p; tmp; tmp = tmp->next) {
1163                 if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid)) {
1164                         p = tmp;
1165                         break;
1166                 }
1167         }
1168
1169         if (!p)
1170                 return -1;
1171
1172         traversenodes = pak->query;
1173         while(traversenodes) {
1174                 if(!strcasecmp(iks_name(traversenodes), "session")) {
1175                         traversenodes = iks_child(traversenodes);
1176                         continue;
1177                 }
1178                 if(!strcasecmp(iks_name(traversenodes), "transport")) {
1179                         traversenodes = iks_child(traversenodes);
1180                         continue;
1181                 }
1182                 if(!strcasecmp(iks_name(traversenodes), "candidate")) {
1183                         newcandidate = ast_calloc(1, sizeof(*newcandidate));
1184                         if (!newcandidate)
1185                                 return 0;
1186                         ast_copy_string(newcandidate->name, iks_find_attrib(traversenodes, "name"),
1187                                                         sizeof(newcandidate->name));
1188                         ast_copy_string(newcandidate->ip, iks_find_attrib(traversenodes, "address"),
1189                                                         sizeof(newcandidate->ip));
1190                         newcandidate->port = atoi(iks_find_attrib(traversenodes, "port"));
1191                         ast_copy_string(newcandidate->username, iks_find_attrib(traversenodes, "username"),
1192                                                         sizeof(newcandidate->username));
1193                         ast_copy_string(newcandidate->password, iks_find_attrib(traversenodes, "password"),
1194                                                         sizeof(newcandidate->password));
1195                         newcandidate->preference = atof(iks_find_attrib(traversenodes, "preference"));
1196                         if (!strcasecmp(iks_find_attrib(traversenodes, "protocol"), "udp"))
1197                                 newcandidate->protocol = AJI_PROTOCOL_UDP;
1198                         if (!strcasecmp(iks_find_attrib(traversenodes, "protocol"), "ssltcp"))
1199                                 newcandidate->protocol = AJI_PROTOCOL_SSLTCP;
1200                 
1201                         if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "stun"))
1202                                 newcandidate->type = AJI_CONNECT_STUN;
1203                         if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "local"))
1204                                 newcandidate->type = AJI_CONNECT_LOCAL;
1205                         if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "relay"))
1206                                 newcandidate->type = AJI_CONNECT_RELAY;
1207                         ast_copy_string(newcandidate->network, iks_find_attrib(traversenodes, "network"),
1208                                                         sizeof(newcandidate->network));
1209                         newcandidate->generation = atoi(iks_find_attrib(traversenodes, "generation"));
1210                         newcandidate->next = NULL;
1211                 
1212                         newcandidate->next = p->theircandidates;
1213                         p->theircandidates = newcandidate;
1214                         p->laststun = 0;
1215                         gtalk_update_stun(p->parent, p);
1216                         newcandidate = NULL;
1217                 }
1218                 traversenodes = iks_next(traversenodes);
1219         }
1220         
1221         receipt = iks_new("iq");
1222         iks_insert_attrib(receipt, "type", "result");
1223         iks_insert_attrib(receipt, "from", from);
1224         iks_insert_attrib(receipt, "to", iks_find_attrib(pak->x, "from"));
1225         iks_insert_attrib(receipt, "id", iks_find_attrib(pak->x, "id"));
1226         iks_send(c->p, receipt);
1227         iks_delete(receipt);
1228
1229         return 1;
1230 }
1231
1232 static struct ast_frame *gtalk_rtp_read(struct ast_channel *ast, struct gtalk_pvt *p)
1233 {
1234         struct ast_frame *f;
1235
1236         if (!p->rtp)
1237                 return &ast_null_frame;
1238         f = ast_rtp_read(p->rtp);
1239         gtalk_update_stun(p->parent, p);
1240         if (p->owner) {
1241                 /* We already hold the channel lock */
1242                 if (f->frametype == AST_FRAME_VOICE) {
1243                         if (f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
1244                                 if (option_debug)
1245                                         ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
1246                                 p->owner->nativeformats =
1247                                         (p->owner->nativeformats & AST_FORMAT_VIDEO_MASK) | f->subclass;
1248                                 ast_set_read_format(p->owner, p->owner->readformat);
1249                                 ast_set_write_format(p->owner, p->owner->writeformat);
1250                         }
1251 /*                      if ((ast_test_flag(p, SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
1252                                 f = ast_dsp_process(p->owner, p->vad, f);
1253                                 if (option_debug && f && (f->frametype == AST_FRAME_DTMF))
1254                                         if (option_debug)
1255                                                 ast_log(LOG_DEBUG, "* Detected inband DTMF '%c'\n", f->subclass);
1256                         } */
1257                 }
1258         }
1259         return f;
1260 }
1261
1262 static struct ast_frame *gtalk_read(struct ast_channel *ast)
1263 {
1264         struct ast_frame *fr;
1265         struct gtalk_pvt *p = ast->tech_pvt;
1266
1267         ast_mutex_lock(&p->lock);
1268         fr = gtalk_rtp_read(ast, p);
1269         ast_mutex_unlock(&p->lock);
1270         return fr;
1271 }
1272
1273 /*! \brief Send frame to media channel (rtp) */
1274 static int gtalk_write(struct ast_channel *ast, struct ast_frame *frame)
1275 {
1276         struct gtalk_pvt *p = ast->tech_pvt;
1277         int res = 0;
1278
1279         switch (frame->frametype) {
1280         case AST_FRAME_VOICE:
1281                 if (!(frame->subclass & ast->nativeformats)) {
1282                         ast_log(LOG_WARNING,
1283                                         "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
1284                                         frame->subclass, ast->nativeformats, ast->readformat,
1285                                         ast->writeformat);
1286                         return 0;
1287                 }
1288                 if (p) {
1289                         ast_mutex_lock(&p->lock);
1290                         if (p->rtp) {
1291                                 res = ast_rtp_write(p->rtp, frame);
1292                         }
1293                         ast_mutex_unlock(&p->lock);
1294                 }
1295                 break;
1296         case AST_FRAME_VIDEO:
1297                 if (p) {
1298                         ast_mutex_lock(&p->lock);
1299                         if (p->vrtp) {
1300                                 res = ast_rtp_write(p->vrtp, frame);
1301                         }
1302                         ast_mutex_unlock(&p->lock);
1303                 }
1304                 break;
1305         case AST_FRAME_IMAGE:
1306                 return 0;
1307                 break;
1308         default:
1309                 ast_log(LOG_WARNING, "Can't send %d type frames with Gtalk write\n",
1310                                 frame->frametype);
1311                 return 0;
1312         }
1313
1314         return res;
1315 }
1316
1317 static int gtalk_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1318 {
1319         struct gtalk_pvt *p = newchan->tech_pvt;
1320         ast_mutex_lock(&p->lock);
1321
1322         if ((p->owner != oldchan)) {
1323                 ast_mutex_unlock(&p->lock);
1324                 return -1;
1325         }
1326         if (p->owner == oldchan)
1327                 p->owner = newchan;
1328         ast_mutex_unlock(&p->lock);
1329         return 0;
1330 }
1331
1332 static int gtalk_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
1333 {
1334         int res = 0;
1335
1336         switch (condition) {
1337         case AST_CONTROL_HOLD:
1338                 ast_moh_start(ast, data, NULL);
1339                 break;
1340         case AST_CONTROL_UNHOLD:
1341                 ast_moh_stop(ast);
1342                 break;
1343         default:
1344                 ast_log(LOG_NOTICE, "Don't know how to indicate condition '%d'\n", condition);
1345                 res = -1;
1346         }
1347
1348         return res;
1349 }
1350
1351 static int gtalk_digit_begin(struct ast_channel *chan, char digit)
1352 {
1353         return gtalk_digit(chan, digit, 0);
1354 }
1355
1356 static int gtalk_digit_end(struct ast_channel *chan, char digit, unsigned int duration)
1357 {
1358         return gtalk_digit(chan, digit, duration);
1359 }
1360
1361 static int gtalk_digit(struct ast_channel *ast, char digit, unsigned int duration)
1362 {
1363         struct gtalk_pvt *p = ast->tech_pvt;
1364         struct gtalk *client = p->parent;
1365         iks *iq, *gtalk, *dtmf;
1366         char buffer[2] = {digit, '\0'};
1367         iq = iks_new("iq");
1368         gtalk = iks_new("gtalk");
1369         dtmf = iks_new("dtmf");
1370         if(!iq || !gtalk || !dtmf) {
1371                 if(iq)
1372                         iks_delete(iq);
1373                 if(gtalk)
1374                         iks_delete(gtalk);
1375                 if(dtmf)
1376                         iks_delete(dtmf);
1377                 ast_log(LOG_ERROR, "Did not send dtmf do to memory issue\n");
1378                 return -1;
1379         }
1380
1381         iks_insert_attrib(iq, "type", "set");
1382         iks_insert_attrib(iq, "to", p->them);
1383         iks_insert_attrib(iq, "from", p->us);
1384         iks_insert_attrib(iq, "id", client->connection->mid);
1385         ast_aji_increment_mid(client->connection->mid);
1386         iks_insert_attrib(gtalk, "xmlns", "http://jabber.org/protocol/gtalk");
1387         iks_insert_attrib(gtalk, "action", "content-info");
1388         iks_insert_attrib(gtalk, "initiator", p->initiator ? p->us: p->them);
1389         iks_insert_attrib(gtalk, "sid", p->sid);
1390         iks_insert_attrib(dtmf, "xmlns", "http://jabber.org/protocol/gtalk/info/dtmf");
1391         iks_insert_attrib(dtmf, "code", buffer);
1392         iks_insert_node(iq, gtalk);
1393         iks_insert_node(gtalk, dtmf);
1394
1395         ast_mutex_lock(&p->lock);
1396         if (ast->dtmff.frametype == AST_FRAME_DTMF_BEGIN) {
1397                 iks_insert_attrib(dtmf, "action", "button-down");
1398         } else if (ast->dtmff.frametype == AST_FRAME_DTMF_END) {
1399                 iks_insert_attrib(dtmf, "action", "button-up");
1400         }
1401         iks_send(client->connection->p, iq);
1402         iks_delete(iq);
1403         iks_delete(gtalk);
1404         iks_delete(dtmf);
1405         ast_mutex_unlock(&p->lock);
1406         return 0;
1407 }
1408
1409 static int gtalk_sendhtml(struct ast_channel *ast, int subclass, const char *data, int datalen)
1410 {
1411         ast_log(LOG_NOTICE, "XXX Implement gtalk sendhtml XXX\n");
1412
1413         return -1;
1414 }
1415
1416 /* Not in use right now.
1417 static int gtalk_auto_congest(void *nothing)
1418 {
1419         struct gtalk_pvt *p = nothing;
1420
1421         ast_mutex_lock(&p->lock);
1422         if (p->owner) {
1423                 if (!ast_channel_trylock(p->owner)) {
1424                         ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
1425                         ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
1426                         ast_channel_unlock(p->owner);
1427                 }
1428         }
1429         ast_mutex_unlock(&p->lock);
1430         return 0;
1431 }
1432 */
1433
1434 /*! \brief Initiate new call, part of PBX interface 
1435  *      dest is the dial string */
1436 static int gtalk_call(struct ast_channel *ast, char *dest, int timeout)
1437 {
1438         struct gtalk_pvt *p = ast->tech_pvt;
1439
1440         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
1441                 ast_log(LOG_WARNING, "gtalk_call called on %s, neither down nor reserved\n", ast->name);
1442                 return -1;
1443         }
1444
1445         ast_setstate(ast, AST_STATE_RING);
1446         p->jointcapability = p->capability;
1447         if (!p->ringrule) {
1448                 ast_copy_string(p->ring, p->parent->connection->mid, sizeof(p->ring));
1449                 p->ringrule = iks_filter_add_rule(p->parent->connection->f, gtalk_ringing_ack, p,
1450                                                         IKS_RULE_ID, p->ring, IKS_RULE_DONE);
1451         } else
1452                 ast_log(LOG_WARNING, "Whoa, already have a ring rule!\n");
1453
1454         gtalk_invite(p, p->them, p->us, p->sid, 1);
1455         gtalk_create_candidates(p->parent, p, p->sid, p->them, p->us);
1456
1457         return 0;
1458 }
1459
1460 /*! \brief Hangup a call through the gtalk proxy channel */
1461 static int gtalk_hangup(struct ast_channel *ast)
1462 {
1463         struct gtalk_pvt *p = ast->tech_pvt;
1464         struct gtalk *client;
1465
1466         ast_mutex_lock(&p->lock);
1467         client = p->parent;
1468         p->owner = NULL;
1469         ast->tech_pvt = NULL;
1470         if (!p->alreadygone)
1471                 gtalk_action(client, p, "terminate");
1472         ast_mutex_unlock(&p->lock);
1473
1474         gtalk_free_pvt(client, p);
1475         ast_module_unref(ast_module_info->self);
1476
1477         return 0;
1478 }
1479
1480 /*! \brief Part of PBX interface */
1481 static struct ast_channel *gtalk_request(const char *type, int format, void *data, int *cause)
1482 {
1483         struct gtalk_pvt *p = NULL;
1484         struct gtalk *client = NULL;
1485         char *sender = NULL, *to = NULL, *s = NULL;
1486         struct ast_channel *chan = NULL;
1487
1488         if (data) {
1489                 s = ast_strdupa(data);
1490                 if (s) {
1491                         sender = strsep(&s, "/");
1492                         if (sender && (sender[0] != '\0'))
1493                                 to = strsep(&s, "/");
1494                         if (!to) {
1495                                 ast_log(LOG_ERROR, "Bad arguments in Gtalk Dialstring: %s\n", (char*) data);
1496                                 return NULL;
1497                         }
1498                 }
1499         }
1500         client = find_gtalk(to, sender);
1501         if (!client) {
1502                 ast_log(LOG_WARNING, "Could not find recipient.\n");
1503                 return NULL;
1504         }
1505         ASTOBJ_WRLOCK(client);
1506         p = gtalk_alloc(client, strchr(sender, '@') ? sender : client->connection->jid->full, strchr(to, '@') ? to : client->user, NULL);
1507         if (p)
1508                 chan = gtalk_new(client, p, AST_STATE_DOWN, to);
1509
1510         ASTOBJ_UNLOCK(client);
1511         return chan;
1512 }
1513
1514 /*! \brief CLI command "gtalk show channels" */
1515 static int gtalk_show_channels(int fd, int argc, char **argv)
1516 {
1517         if (argc != 3)
1518                 return RESULT_SHOWUSAGE;
1519         ast_mutex_lock(&gtalklock);
1520 //      if (!gtalk_list->p)
1521                 ast_cli(fd, "No gtalk channels in use\n");
1522         ast_mutex_unlock(&gtalklock);
1523         return RESULT_SUCCESS;
1524 }
1525
1526 /*! \brief CLI command "gtalk show channels" */
1527 static int gtalk_do_reload(int fd, int argc, char **argv)
1528 {
1529         ast_verbose("IT DOES WORK!\n");
1530         return RESULT_SUCCESS;
1531 }
1532
1533 static int gtalk_parser(void *data, ikspak *pak)
1534 {
1535         struct gtalk *client = ASTOBJ_REF((struct gtalk *) data);
1536
1537         if (iks_find_with_attrib(pak->x, "session", "type", "initiate")) {
1538                 /* New call */
1539                 gtalk_newcall(client, pak);
1540         } else if (iks_find_with_attrib(pak->x, "session", "type", "candidates") || iks_find_with_attrib(pak->x, "session", "type", "transport-info")) {
1541                 if (option_debug > 2)
1542                         ast_log(LOG_DEBUG, "About to add candidate!\n");
1543                 gtalk_add_candidate(client, pak);
1544                 if (option_debug > 2)
1545                         ast_log(LOG_DEBUG, "Candidate Added!\n");
1546         } else if (iks_find_with_attrib(pak->x, "session", "type", "accept") || iks_find_with_attrib(pak->x, "session", "type", "transport-accept")) {
1547                 gtalk_is_answered(client, pak);
1548         } else if (iks_find_with_attrib(pak->x, "session", "type", "content-info")) {
1549                 gtalk_handle_dtmf(client, pak);
1550         } else if (iks_find_with_attrib(pak->x, "session", "type", "terminate")) {
1551                 gtalk_hangup_farend(client, pak);
1552         } else if (iks_find_with_attrib(pak->x, "session", "type", "reject")) {
1553                 gtalk_hangup_farend(client, pak);
1554         }
1555         ASTOBJ_UNREF(client, gtalk_member_destroy);
1556         return IKS_FILTER_EAT;
1557 }
1558
1559 /* Not using this anymore probably take out soon 
1560 static struct gtalk_candidate *gtalk_create_candidate(char *args)
1561 {
1562         char *name, *type, *preference, *protocol;
1563         struct gtalk_candidate *res;
1564         res = malloc(sizeof(struct gtalk_candidate));
1565         memset(res, 0, sizeof(struct gtalk_candidate));
1566         if (args)
1567                 name = args;
1568         if ((args = strchr(args, ','))) {
1569                 *args = '\0';
1570                 args++;
1571                 preference = args;
1572         }
1573         if ((args = strchr(args, ','))) {
1574                 *args = '\0';
1575                 args++;
1576                 protocol = args;
1577         }
1578         if ((args = strchr(args, ','))) {
1579                 *args = '\0';
1580                 args++;
1581                 type = args;
1582         }
1583         if (name)
1584                 ast_copy_string(res->name, name, sizeof(res->name));
1585         if (preference) {
1586                 res->preference = atof(preference);
1587         }
1588         if (protocol) {
1589                 if (!strcasecmp("udp", protocol))
1590                         res->protocol = AJI_PROTOCOL_UDP;
1591                 if (!strcasecmp("ssltcp", protocol))
1592                         res->protocol = AJI_PROTOCOL_SSLTCP;
1593         }
1594         if (type) {
1595                 if (!strcasecmp("stun", type))
1596                         res->type = AJI_CONNECT_STUN;
1597                 if (!strcasecmp("local", type))
1598                         res->type = AJI_CONNECT_LOCAL;
1599                 if (!strcasecmp("relay", type))
1600                         res->type = AJI_CONNECT_RELAY;
1601         }
1602
1603         return res;
1604 }
1605 */
1606
1607 static int gtalk_create_member(char *label, struct ast_variable *var, int allowguest,
1608                                                                 struct ast_codec_pref prefs, char *context,
1609                                                                 struct gtalk *member)
1610 {
1611         struct aji_client *client;
1612
1613         if (!member)
1614                 ast_log(LOG_WARNING, "Out of memory.\n");
1615
1616         ast_copy_string(member->name, label, sizeof(member->name));
1617         ast_copy_string(member->user, label, sizeof(member->user));
1618         ast_copy_string(member->context, context, sizeof(member->context));
1619         member->allowguest = allowguest;
1620         member->prefs = prefs;
1621         while (var) {
1622 #if 0
1623                 struct gtalk_candidate *candidate = NULL;
1624 #endif
1625                 if (!strcasecmp(var->name, "username"))
1626                         ast_copy_string(member->user, var->value, sizeof(member->user));
1627                 else if (!strcasecmp(var->name, "disallow"))
1628                         ast_parse_allow_disallow(&member->prefs, &member->capability, var->value, 0);
1629                 else if (!strcasecmp(var->name, "allow"))
1630                         ast_parse_allow_disallow(&member->prefs, &member->capability, var->value, 1);
1631                 else if (!strcasecmp(var->name, "context"))
1632                         ast_copy_string(member->context, var->value, sizeof(member->context));
1633 #if 0
1634                 else if (!strcasecmp(var->name, "candidate")) {
1635                         candidate = gtalk_create_candidate(var->value);
1636                         if (candidate) {
1637                                 candidate->next = member->ourcandidates;
1638                                 member->ourcandidates = candidate;
1639                         }
1640                 }
1641 #endif
1642                 else if (!strcasecmp(var->name, "connection")) {
1643                         if ((client = ast_aji_get_client(var->value))) {
1644                                 member->connection = client;
1645                                 iks_filter_add_rule(client->f, gtalk_parser, member, IKS_RULE_TYPE,
1646                                                                         IKS_PAK_IQ, IKS_RULE_FROM_PARTIAL, member->user,
1647                                                                         IKS_RULE_NS, "http://www.google.com/session",
1648                                                                         IKS_RULE_DONE);
1649
1650                         } else {
1651                                 ast_log(LOG_ERROR, "connection referenced not found!\n");
1652                                 return 0;
1653                         }
1654                 }
1655                 var = var->next;
1656         }
1657         if (member->connection && member->user)
1658                 member->buddy = ASTOBJ_CONTAINER_FIND(&member->connection->buddies, member->user);
1659         else {
1660                 ast_log(LOG_ERROR, "No Connection or Username!\n");
1661         }
1662         return 1;
1663 }
1664
1665 static int gtalk_load_config(void)
1666 {
1667         char *cat = NULL;
1668         struct ast_config *cfg = NULL;
1669         char context[100];
1670         int allowguest = 1;
1671         struct ast_variable *var;
1672         struct gtalk *member;
1673         struct ast_codec_pref prefs;
1674         struct aji_client_container *clients;
1675         struct gtalk_candidate *global_candidates = NULL;
1676         struct hostent *hp;
1677         struct ast_hostent ahp;
1678
1679         cfg = ast_config_load(GOOGLE_CONFIG);
1680         if (!cfg)
1681                 return 0;
1682
1683         /* Copy the default jb config over global_jbconf */
1684         memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
1685
1686         cat = ast_category_browse(cfg, NULL);
1687         for (var = ast_variable_browse(cfg, "general"); var; var = var->next) {
1688                 /* handle jb conf */
1689                 if (!ast_jb_read_conf(&global_jbconf, var->name, var->value))
1690                         continue;
1691
1692                 if (!strcasecmp(var->name, "allowguest"))
1693                         allowguest =
1694                                 (ast_true(ast_variable_retrieve(cfg, "general", "allowguest"))) ? 1 : 0;
1695                 else if (!strcasecmp(var->name, "disallow"))
1696                         ast_parse_allow_disallow(&prefs, &global_capability, var->value, 0);
1697                 else if (!strcasecmp(var->name, "allow"))
1698                         ast_parse_allow_disallow(&prefs, &global_capability, var->value, 1);
1699                 else if (!strcasecmp(var->name, "context"))
1700                         ast_copy_string(context, var->value, sizeof(context));
1701                 else if (!strcasecmp(var->name, "bindaddr")) {
1702                         if (!(hp = ast_gethostbyname(var->value, &ahp))) {
1703                                 ast_log(LOG_WARNING, "Invalid address: %s\n", var->value);
1704                         } else {
1705                                 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
1706                         }
1707                 }
1708 /*  Idea to allow for custom candidates  */
1709 /*
1710                 else if (!strcasecmp(var->name, "candidate")) {
1711                         candidate = gtalk_create_candidate(var->value);
1712                         if (candidate) {
1713                                 candidate->next = global_candidates;
1714                                 global_candidates = candidate;
1715                         }
1716                 }
1717 */
1718         }
1719         while (cat) {
1720                 if (strcasecmp(cat, "general")) {
1721                         var = ast_variable_browse(cfg, cat);
1722                         member = (struct gtalk *) malloc(sizeof(struct gtalk));
1723                         memset(member, 0, sizeof(struct gtalk));
1724                         ASTOBJ_INIT(member);
1725                         ASTOBJ_WRLOCK(member);
1726                         if (!strcasecmp(cat, "guest")) {
1727                                 ast_copy_string(member->name, "guest", sizeof(member->name));
1728                                 ast_copy_string(member->user, "guest", sizeof(member->user));
1729                                 ast_copy_string(member->context, context, sizeof(member->context));
1730                                 member->allowguest = allowguest;
1731                                 member->prefs = prefs;
1732                                 while (var) {
1733                                         if (!strcasecmp(var->name, "disallow"))
1734                                                 ast_parse_allow_disallow(&member->prefs, &member->capability,
1735                                                                                                  var->value, 0);
1736                                         else if (!strcasecmp(var->name, "allow"))
1737                                                 ast_parse_allow_disallow(&member->prefs, &member->capability,
1738                                                                                                  var->value, 1);
1739                                         else if (!strcasecmp(var->name, "context"))
1740                                                 ast_copy_string(member->context, var->value,
1741                                                                                 sizeof(member->context));
1742 /*  Idea to allow for custom candidates  */
1743 /*
1744                                         else if (!strcasecmp(var->name, "candidate")) {
1745                                                 candidate = gtalk_create_candidate(var->value);
1746                                                 if (candidate) {
1747                                                         candidate->next = member->ourcandidates;
1748                                                         member->ourcandidates = candidate;
1749                                                 }
1750                                         }
1751 */
1752                                         var = var->next;
1753                                 }
1754                                 ASTOBJ_UNLOCK(member);
1755                                 clients = ast_aji_get_clients();
1756                                 if (clients) {
1757                                         ASTOBJ_CONTAINER_TRAVERSE(clients, 1, {
1758                                                 ASTOBJ_WRLOCK(iterator);
1759                                                 ASTOBJ_WRLOCK(member);
1760                                                 member->connection = iterator;
1761                                                 iks_filter_add_rule(iterator->f, gtalk_parser, member, IKS_RULE_TYPE, IKS_PAK_IQ, IKS_RULE_NS,
1762                                                                                 "http://www.google.com/session", IKS_RULE_DONE);
1763                                                 ASTOBJ_UNLOCK(member);
1764                                                 ASTOBJ_CONTAINER_LINK(&gtalk_list, member);
1765                                                 ASTOBJ_UNLOCK(iterator);
1766                                         });
1767                                 } else {
1768                                         ASTOBJ_UNLOCK(member);
1769                                         ASTOBJ_UNREF(member, gtalk_member_destroy);
1770                                 }
1771                         } else {
1772                                 ASTOBJ_UNLOCK(member);
1773                                 if (gtalk_create_member(cat, var, allowguest, prefs, context, member))
1774                                         ASTOBJ_CONTAINER_LINK(&gtalk_list, member);
1775                                 ASTOBJ_UNREF(member, gtalk_member_destroy);
1776                         }
1777                 }
1778                 cat = ast_category_browse(cfg, cat);
1779         }
1780         gtalk_free_candidates(global_candidates);
1781         return 1;
1782 }
1783
1784 /*! \brief Load module into PBX, register channel */
1785 static int load_module(void)
1786 {
1787         ASTOBJ_CONTAINER_INIT(&gtalk_list);
1788         if (!gtalk_load_config()) {
1789                 ast_log(LOG_ERROR, "Unable to read config file %s. Not loading module.\n", GOOGLE_CONFIG);
1790                 return 0;
1791         }
1792
1793         sched = sched_context_create();
1794         if (!sched) 
1795                 ast_log(LOG_WARNING, "Unable to create schedule context\n");
1796
1797         io = io_context_create();
1798         if (!io) 
1799                 ast_log(LOG_WARNING, "Unable to create I/O context\n");
1800
1801         if (ast_find_ourip(&__ourip, bindaddr)) {
1802                 ast_log(LOG_WARNING, "Unable to get own IP address, Gtalk disabled\n");
1803                 return 0;
1804         }
1805
1806         ast_rtp_proto_register(&gtalk_rtp);
1807         ast_cli_register_multiple(gtalk_cli, sizeof(gtalk_cli) / sizeof(gtalk_cli[0]));
1808
1809         /* Make sure we can register our channel type */
1810         if (ast_channel_register(&gtalk_tech)) {
1811                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", gtalk_tech.type);
1812                 return -1;
1813         }
1814         return 0;
1815 }
1816
1817 /*! \brief Reload module */
1818 static int reload(void)
1819 {
1820         return 0;
1821 }
1822
1823 /*! \brief Unload the gtalk channel from Asterisk */
1824 static int unload_module(void)
1825 {
1826         struct gtalk_pvt *privates = NULL;
1827         ast_cli_unregister_multiple(gtalk_cli, sizeof(gtalk_cli) / sizeof(gtalk_cli[0]));
1828         /* First, take us out of the channel loop */
1829         ast_channel_unregister(&gtalk_tech);
1830         ast_rtp_proto_unregister(&gtalk_rtp);
1831
1832         if (!ast_mutex_lock(&gtalklock)) {
1833                 /* Hangup all interfaces if they have an owner */
1834                 ASTOBJ_CONTAINER_TRAVERSE(&gtalk_list, 1, {
1835                         ASTOBJ_WRLOCK(iterator);
1836                         privates = iterator->p;
1837                         while(privates) {
1838                                 if (privates->owner)
1839                                         ast_softhangup(privates->owner, AST_SOFTHANGUP_APPUNLOAD);
1840                                 privates = privates->next;
1841                         }
1842                         iterator->p = NULL;
1843                         ASTOBJ_UNLOCK(iterator);
1844                 });
1845                 ast_mutex_unlock(&gtalklock);
1846         } else {
1847                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
1848                 return -1;
1849         }
1850         ASTOBJ_CONTAINER_DESTROYALL(&gtalk_list, gtalk_member_destroy);
1851         ASTOBJ_CONTAINER_DESTROY(&gtalk_list);
1852         return 0;
1853 }
1854
1855 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Gtalk Channel Driver",
1856                 .load = load_module,
1857                 .unload = unload_module,
1858                 .reload = reload,
1859                );