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