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