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