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