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