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