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