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