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