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