Merge in the RTP engine API.
[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, 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;
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         tmp->rtp = ast_rtp_instance_new(NULL, sched, &bindaddr, NULL);
951         ast_rtp_instance_set_prop(tmp->rtp, AST_RTP_PROPERTY_RTCP, 1);
952         ast_rtp_codecs_payloads_clear(ast_rtp_instance_get_codecs(tmp->rtp), tmp->rtp);
953
954         /* add user configured codec capabilites */
955         if (client->capability)
956                 tmp->capability = client->capability;
957         else if (global_capability)
958                 tmp->capability = global_capability;
959
960         tmp->parent = client;
961         if (!tmp->rtp) {
962                 ast_log(LOG_WARNING, "Out of RTP sessions?\n");
963                 ast_free(tmp);
964                 return NULL;
965         }
966
967         /* Set CALLERID(name) to the full JID of the remote peer */
968         ast_copy_string(tmp->cid_name, tmp->them, sizeof(tmp->cid_name));
969
970         if(strchr(tmp->us, '/')) {
971                 data = ast_strdupa(tmp->us);
972                 exten = strsep(&data, "/");
973         } else
974                 exten = tmp->us;
975         ast_copy_string(tmp->exten,  exten, sizeof(tmp->exten));
976         ast_mutex_init(&tmp->lock);
977         ast_mutex_lock(&gtalklock);
978         tmp->next = client->p;
979         client->p = tmp;
980         ast_mutex_unlock(&gtalklock);
981         return tmp;
982 }
983
984 /*! \brief Start new gtalk channel */
985 static struct ast_channel *gtalk_new(struct gtalk *client, struct gtalk_pvt *i, int state, const char *title)
986 {
987         struct ast_channel *tmp;
988         int fmt;
989         int what;
990         const char *n2;
991
992         if (title)
993                 n2 = title;
994         else
995                 n2 = i->us;
996         tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, client->accountcode, i->exten, client->context, client->amaflags, "Gtalk/%s-%04lx", n2, ast_random() & 0xffff);
997         if (!tmp) {
998                 ast_log(LOG_WARNING, "Unable to allocate Gtalk channel structure!\n");
999                 return NULL;
1000         }
1001         tmp->tech = &gtalk_tech;
1002
1003         /* Select our native format based on codec preference until we receive
1004            something from another device to the contrary. */
1005         if (i->jointcapability)
1006                 what = i->jointcapability;
1007         else if (i->capability)
1008                 what = i->capability;
1009         else
1010                 what = global_capability;
1011
1012         /* Set Frame packetization */
1013         if (i->rtp)
1014                 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(i->rtp), i->rtp, &i->prefs);
1015
1016         tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | (i->jointcapability & AST_FORMAT_VIDEO_MASK);
1017         fmt = ast_best_codec(tmp->nativeformats);
1018
1019         if (i->rtp) {
1020                 ast_rtp_instance_set_prop(i->rtp, AST_RTP_PROPERTY_STUN, 1);
1021                 ast_channel_set_fd(tmp, 0, ast_rtp_instance_fd(i->rtp, 0));
1022                 ast_channel_set_fd(tmp, 1, ast_rtp_instance_fd(i->rtp, 1));
1023         }
1024         if (i->vrtp) {
1025                 ast_rtp_instance_set_prop(i->vrtp, AST_RTP_PROPERTY_STUN, 1);
1026                 ast_channel_set_fd(tmp, 2, ast_rtp_instance_fd(i->vrtp, 0));
1027                 ast_channel_set_fd(tmp, 3, ast_rtp_instance_fd(i->vrtp, 1));
1028         }
1029         if (state == AST_STATE_RING)
1030                 tmp->rings = 1;
1031         tmp->adsicpe = AST_ADSI_UNAVAILABLE;
1032         tmp->writeformat = fmt;
1033         tmp->rawwriteformat = fmt;
1034         tmp->readformat = fmt;
1035         tmp->rawreadformat = fmt;
1036         tmp->tech_pvt = i;
1037
1038         tmp->callgroup = client->callgroup;
1039         tmp->pickupgroup = client->pickupgroup;
1040         tmp->cid.cid_pres = client->callingpres;
1041         if (!ast_strlen_zero(client->accountcode))
1042                 ast_string_field_set(tmp, accountcode, client->accountcode);
1043         if (client->amaflags)
1044                 tmp->amaflags = client->amaflags;
1045         if (!ast_strlen_zero(client->language))
1046                 ast_string_field_set(tmp, language, client->language);
1047         if (!ast_strlen_zero(client->musicclass))
1048                 ast_string_field_set(tmp, musicclass, client->musicclass);
1049         if (!ast_strlen_zero(client->parkinglot))
1050                 ast_string_field_set(tmp, parkinglot, client->parkinglot);
1051         i->owner = tmp;
1052         ast_module_ref(ast_module_info->self);
1053         ast_copy_string(tmp->context, client->context, sizeof(tmp->context));
1054         ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
1055
1056         if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
1057                 tmp->cid.cid_dnid = ast_strdup(i->exten);
1058         tmp->priority = 1;
1059         if (i->rtp)
1060                 ast_jb_configure(tmp, &global_jbconf);
1061         if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
1062                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
1063                 tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
1064                 ast_hangup(tmp);
1065                 tmp = NULL;
1066         } else {
1067                 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
1068                         "Channel: %s\r\nChanneltype: %s\r\nGtalk-SID: %s\r\n",
1069                         i->owner ? i->owner->name : "", "Gtalk", i->sid);
1070         }
1071         return tmp;
1072 }
1073
1074 static int gtalk_action(struct gtalk *client, struct gtalk_pvt *p, const char *action)
1075 {
1076         iks *request, *session = NULL;
1077         int res = -1;
1078         char *lowerthem = NULL;
1079
1080         request = iks_new("iq");
1081         if (request) {
1082                 iks_insert_attrib(request, "type", "set");
1083                 iks_insert_attrib(request, "from", p->us);
1084                 iks_insert_attrib(request, "to", p->them);
1085                 iks_insert_attrib(request, "id", client->connection->mid);
1086                 ast_aji_increment_mid(client->connection->mid);
1087                 session = iks_new("session");
1088                 if (session) {
1089                         iks_insert_attrib(session, "type", action);
1090                         iks_insert_attrib(session, "id", p->sid);
1091                         /* put the initiator attribute to lower case if we receive the call 
1092                          * otherwise GoogleTalk won't establish the session */
1093                         if (!p->initiator) {
1094                                 char c;
1095                                 char *t = lowerthem = ast_strdupa(p->them);
1096                                 while (((c = *t) != '/') && (*t++ = tolower(c)));
1097                         }
1098                         iks_insert_attrib(session, "initiator", p->initiator ? p->us : lowerthem);
1099                         iks_insert_attrib(session, "xmlns", "http://www.google.com/session");
1100                         iks_insert_node(request, session);
1101                         ast_aji_send(client->connection, request);
1102                         res = 0;
1103                 }
1104         }
1105
1106         iks_delete(session);
1107         iks_delete(request);
1108
1109         return res;
1110 }
1111
1112 static void gtalk_free_candidates(struct gtalk_candidate *candidate)
1113 {
1114         struct gtalk_candidate *last;
1115         while (candidate) {
1116                 last = candidate;
1117                 candidate = candidate->next;
1118                 ast_free(last);
1119         }
1120 }
1121
1122 static void gtalk_free_pvt(struct gtalk *client, struct gtalk_pvt *p)
1123 {
1124         struct gtalk_pvt *cur, *prev = NULL;
1125         cur = client->p;
1126         while (cur) {
1127                 if (cur == p) {
1128                         if (prev)
1129                                 prev->next = p->next;
1130                         else
1131                                 client->p = p->next;
1132                         break;
1133                 }
1134                 prev = cur;
1135                 cur = cur->next;
1136         }
1137         if (p->ringrule)
1138                 iks_filter_remove_rule(p->parent->connection->f, p->ringrule);
1139         if (p->owner)
1140                 ast_log(LOG_WARNING, "Uh oh, there's an owner, this is going to be messy.\n");
1141         if (p->rtp)
1142                 ast_rtp_instance_destroy(p->rtp);
1143         if (p->vrtp)
1144                 ast_rtp_instance_destroy(p->vrtp);
1145         gtalk_free_candidates(p->theircandidates);
1146         ast_free(p);
1147 }
1148
1149
1150 static int gtalk_newcall(struct gtalk *client, ikspak *pak)
1151 {
1152         struct gtalk_pvt *p, *tmp = client->p;
1153         struct ast_channel *chan;
1154         int res;
1155         iks *codec;
1156         char *from = NULL;
1157         char s1[BUFSIZ], s2[BUFSIZ], s3[BUFSIZ];
1158         int peernoncodeccapability;
1159
1160         /* Make sure our new call doesn't exist yet */
1161         from = iks_find_attrib(pak->x,"to");
1162         if(!from)
1163                 from = client->connection->jid->full;
1164         
1165         while (tmp) {
1166                 if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid)) {
1167                         ast_log(LOG_NOTICE, "Ignoring duplicate call setup on SID %s\n", tmp->sid);
1168                         gtalk_response(client, from, pak, "out-of-order", NULL);
1169                         return -1;
1170                 }
1171                 tmp = tmp->next;
1172         }
1173
1174         if (!strcasecmp(client->name, "guest")){
1175                 /* the guest account is not tied to any configured XMPP client,
1176                    let's set it now */
1177                 client->connection = ast_aji_get_client(from);
1178                 if (!client->connection) {
1179                         ast_log(LOG_ERROR, "No XMPP client to talk to, us (partial JID) : %s\n", from);
1180                         return -1;
1181                 }
1182         }
1183
1184         p = gtalk_alloc(client, from, pak->from->full, iks_find_attrib(pak->query, "id"));
1185         if (!p) {
1186                 ast_log(LOG_WARNING, "Unable to allocate gtalk structure!\n");
1187                 return -1;
1188         }
1189
1190         chan = gtalk_new(client, p, AST_STATE_DOWN, pak->from->user);
1191         if (!chan) {
1192                 gtalk_free_pvt(client, p);
1193                 return -1;
1194         }
1195
1196         ast_mutex_lock(&p->lock);
1197         ast_copy_string(p->them, pak->from->full, sizeof(p->them));
1198         if (iks_find_attrib(pak->query, "id")) {
1199                 ast_copy_string(p->sid, iks_find_attrib(pak->query, "id"),
1200                                 sizeof(p->sid));
1201         }
1202
1203         /* codec points to the first <payload-type/> tag */     
1204         codec = iks_first_tag(iks_first_tag(iks_first_tag(pak->x)));
1205         
1206         while (codec) {
1207                 ast_rtp_codecs_payloads_set_m_type(ast_rtp_instance_get_codecs(p->rtp), p->rtp, atoi(iks_find_attrib(codec, "id")));
1208                 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);
1209                 codec = iks_next_tag(codec);
1210         }
1211         
1212         /* Now gather all of the codecs that we are asked for */
1213         ast_rtp_codecs_payload_formats(ast_rtp_instance_get_codecs(p->rtp), &p->peercapability, &peernoncodeccapability);
1214         p->jointcapability = p->capability & p->peercapability;
1215         ast_mutex_unlock(&p->lock);
1216                 
1217         ast_setstate(chan, AST_STATE_RING);
1218         if (!p->jointcapability) {
1219                 ast_log(LOG_WARNING, "Capabilities don't match : us - %s, peer - %s, combined - %s \n", ast_getformatname_multiple(s1, BUFSIZ, p->capability),
1220                         ast_getformatname_multiple(s2, BUFSIZ, p->peercapability),
1221                         ast_getformatname_multiple(s3, BUFSIZ, p->jointcapability));
1222                 /* close session if capabilities don't match */
1223                 gtalk_action(client, p, "reject");
1224                 p->alreadygone = 1;
1225                 gtalk_hangup(chan);
1226                 ast_channel_free(chan);
1227                 return -1;
1228         }       
1229
1230         res = ast_pbx_start(chan);
1231         
1232         switch (res) {
1233         case AST_PBX_FAILED:
1234                 ast_log(LOG_WARNING, "Failed to start PBX :(\n");
1235                 gtalk_response(client, from, pak, "service-unavailable", NULL);
1236                 break;
1237         case AST_PBX_CALL_LIMIT:
1238                 ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
1239                 gtalk_response(client, from, pak, "service-unavailable", NULL);
1240                 break;
1241         case AST_PBX_SUCCESS:
1242                 gtalk_response(client, from, pak, NULL, NULL);
1243                 gtalk_invite_response(p, p->them, p->us,p->sid, 0);
1244                 gtalk_create_candidates(client, p, p->sid, p->them, p->us);
1245                 /* nothing to do */
1246                 break;
1247         }
1248
1249         return 1;
1250 }
1251
1252 static int gtalk_update_stun(struct gtalk *client, struct gtalk_pvt *p)
1253 {
1254         struct gtalk_candidate *tmp;
1255         struct hostent *hp;
1256         struct ast_hostent ahp;
1257         struct sockaddr_in sin;
1258         struct sockaddr_in aux;
1259
1260         if (time(NULL) == p->laststun)
1261                 return 0;
1262
1263         tmp = p->theircandidates;
1264         p->laststun = time(NULL);
1265         while (tmp) {
1266                 char username[256];
1267
1268                 /* Find the IP address of the host */
1269                 hp = ast_gethostbyname(tmp->ip, &ahp);
1270                 sin.sin_family = AF_INET;
1271                 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
1272                 sin.sin_port = htons(tmp->port);
1273                 snprintf(username, sizeof(username), "%s%s", tmp->username,
1274                          p->ourcandidates->username);
1275                 
1276                 /* Find out the result of the STUN */
1277                 ast_rtp_instance_get_remote_address(p->rtp, &aux);
1278
1279                 /* If the STUN result is different from the IP of the hostname,
1280                         lock on the stun IP of the hostname advertised by the
1281                         remote client */
1282                 if (aux.sin_addr.s_addr && 
1283                     aux.sin_addr.s_addr != sin.sin_addr.s_addr)
1284                         ast_rtp_instance_stun_request(p->rtp, &aux, username);
1285                 else 
1286                         ast_rtp_instance_stun_request(p->rtp, &sin, username);
1287                 
1288                 if (aux.sin_addr.s_addr) {
1289                         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);
1290                         ast_debug(4, "Sending STUN request to %s\n", tmp->ip);
1291                 }
1292
1293                 tmp = tmp->next;
1294         }
1295         return 1;
1296 }
1297
1298 static int gtalk_add_candidate(struct gtalk *client, ikspak *pak)
1299 {
1300         struct gtalk_pvt *p = NULL, *tmp = NULL;
1301         struct aji_client *c = client->connection;
1302         struct gtalk_candidate *newcandidate = NULL;
1303         iks *traversenodes = NULL, *receipt = NULL;
1304         char *from;
1305
1306         from = iks_find_attrib(pak->x,"to");
1307         if(!from)
1308                 from = c->jid->full;
1309
1310         for (tmp = client->p; tmp; tmp = tmp->next) {
1311                 if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid)) {
1312                         p = tmp;
1313                         break;
1314                 }
1315         }
1316
1317         if (!p)
1318                 return -1;
1319
1320         traversenodes = pak->query;
1321         while(traversenodes) {
1322                 if(!strcasecmp(iks_name(traversenodes), "session")) {
1323                         traversenodes = iks_first_tag(traversenodes);
1324                         continue;
1325                 }
1326                 if(!strcasecmp(iks_name(traversenodes), "transport")) {
1327                         traversenodes = iks_first_tag(traversenodes);
1328                         continue;
1329                 }
1330                 if(!strcasecmp(iks_name(traversenodes), "candidate")) {
1331                         newcandidate = ast_calloc(1, sizeof(*newcandidate));
1332                         if (!newcandidate)
1333                                 return 0;
1334                         ast_copy_string(newcandidate->name, iks_find_attrib(traversenodes, "name"),
1335                                                         sizeof(newcandidate->name));
1336                         ast_copy_string(newcandidate->ip, iks_find_attrib(traversenodes, "address"),
1337                                                         sizeof(newcandidate->ip));
1338                         newcandidate->port = atoi(iks_find_attrib(traversenodes, "port"));
1339                         ast_copy_string(newcandidate->username, iks_find_attrib(traversenodes, "username"),
1340                                                         sizeof(newcandidate->username));
1341                         ast_copy_string(newcandidate->password, iks_find_attrib(traversenodes, "password"),
1342                                                         sizeof(newcandidate->password));
1343                         newcandidate->preference = atof(iks_find_attrib(traversenodes, "preference"));
1344                         if (!strcasecmp(iks_find_attrib(traversenodes, "protocol"), "udp"))
1345                                 newcandidate->protocol = AJI_PROTOCOL_UDP;
1346                         if (!strcasecmp(iks_find_attrib(traversenodes, "protocol"), "ssltcp"))
1347                                 newcandidate->protocol = AJI_PROTOCOL_SSLTCP;
1348                 
1349                         if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "stun"))
1350                                 newcandidate->type = AJI_CONNECT_STUN;
1351                         if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "local"))
1352                                 newcandidate->type = AJI_CONNECT_LOCAL;
1353                         if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "relay"))
1354                                 newcandidate->type = AJI_CONNECT_RELAY;
1355                         ast_copy_string(newcandidate->network, iks_find_attrib(traversenodes, "network"),
1356                                                         sizeof(newcandidate->network));
1357                         newcandidate->generation = atoi(iks_find_attrib(traversenodes, "generation"));
1358                         newcandidate->next = NULL;
1359                 
1360                         newcandidate->next = p->theircandidates;
1361                         p->theircandidates = newcandidate;
1362                         p->laststun = 0;
1363                         gtalk_update_stun(p->parent, p);
1364                         newcandidate = NULL;
1365                 }
1366                 traversenodes = iks_next_tag(traversenodes);
1367         }
1368         
1369         receipt = iks_new("iq");
1370         iks_insert_attrib(receipt, "type", "result");
1371         iks_insert_attrib(receipt, "from", from);
1372         iks_insert_attrib(receipt, "to", iks_find_attrib(pak->x, "from"));
1373         iks_insert_attrib(receipt, "id", iks_find_attrib(pak->x, "id"));
1374         ast_aji_send(c, receipt);
1375
1376         iks_delete(receipt);
1377
1378         return 1;
1379 }
1380
1381 static struct ast_frame *gtalk_rtp_read(struct ast_channel *ast, struct gtalk_pvt *p)
1382 {
1383         struct ast_frame *f;
1384
1385         if (!p->rtp)
1386                 return &ast_null_frame;
1387         f = ast_rtp_instance_read(p->rtp, 0);
1388         gtalk_update_stun(p->parent, p);
1389         if (p->owner) {
1390                 /* We already hold the channel lock */
1391                 if (f->frametype == AST_FRAME_VOICE) {
1392                         if (f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
1393                                 ast_debug(1, "Oooh, format changed to %d\n", f->subclass);
1394                                 p->owner->nativeformats =
1395                                         (p->owner->nativeformats & AST_FORMAT_VIDEO_MASK) | f->subclass;
1396                                 ast_set_read_format(p->owner, p->owner->readformat);
1397                                 ast_set_write_format(p->owner, p->owner->writeformat);
1398                         }
1399 /*                      if ((ast_test_flag(p, SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
1400                                 f = ast_dsp_process(p->owner, p->vad, f);
1401                                 if (option_debug && f && (f->frametype == AST_FRAME_DTMF))
1402                                         ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass);
1403                         } */
1404                 }
1405         }
1406         return f;
1407 }
1408
1409 static struct ast_frame *gtalk_read(struct ast_channel *ast)
1410 {
1411         struct ast_frame *fr;
1412         struct gtalk_pvt *p = ast->tech_pvt;
1413
1414         ast_mutex_lock(&p->lock);
1415         fr = gtalk_rtp_read(ast, p);
1416         ast_mutex_unlock(&p->lock);
1417         return fr;
1418 }
1419
1420 /*! \brief Send frame to media channel (rtp) */
1421 static int gtalk_write(struct ast_channel *ast, struct ast_frame *frame)
1422 {
1423         struct gtalk_pvt *p = ast->tech_pvt;
1424         int res = 0;
1425
1426         switch (frame->frametype) {
1427         case AST_FRAME_VOICE:
1428                 if (!(frame->subclass & ast->nativeformats)) {
1429                         ast_log(LOG_WARNING,
1430                                         "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
1431                                         frame->subclass, ast->nativeformats, ast->readformat,
1432                                         ast->writeformat);
1433                         return 0;
1434                 }
1435                 if (p) {
1436                         ast_mutex_lock(&p->lock);
1437                         if (p->rtp) {
1438                                 res = ast_rtp_instance_write(p->rtp, frame);
1439                         }
1440                         ast_mutex_unlock(&p->lock);
1441                 }
1442                 break;
1443         case AST_FRAME_VIDEO:
1444                 if (p) {
1445                         ast_mutex_lock(&p->lock);
1446                         if (p->vrtp) {
1447                                 res = ast_rtp_instance_write(p->vrtp, frame);
1448                         }
1449                         ast_mutex_unlock(&p->lock);
1450                 }
1451                 break;
1452         case AST_FRAME_IMAGE:
1453                 return 0;
1454                 break;
1455         default:
1456                 ast_log(LOG_WARNING, "Can't send %d type frames with Gtalk write\n",
1457                                 frame->frametype);
1458                 return 0;
1459         }
1460
1461         return res;
1462 }
1463
1464 static int gtalk_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1465 {
1466         struct gtalk_pvt *p = newchan->tech_pvt;
1467         ast_mutex_lock(&p->lock);
1468
1469         if ((p->owner != oldchan)) {
1470                 ast_mutex_unlock(&p->lock);
1471                 return -1;
1472         }
1473         if (p->owner == oldchan)
1474                 p->owner = newchan;
1475         ast_mutex_unlock(&p->lock);
1476         return 0;
1477 }
1478
1479 static int gtalk_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
1480 {
1481         int res = 0;
1482
1483         switch (condition) {
1484         case AST_CONTROL_HOLD:
1485                 ast_moh_start(ast, data, NULL);
1486                 break;
1487         case AST_CONTROL_UNHOLD:
1488                 ast_moh_stop(ast);
1489                 break;
1490         default:
1491                 ast_log(LOG_NOTICE, "Don't know how to indicate condition '%d'\n", condition);
1492                 res = -1;
1493         }
1494
1495         return res;
1496 }
1497
1498 static int gtalk_digit_begin(struct ast_channel *chan, char digit)
1499 {
1500         return gtalk_digit(chan, digit, 0);
1501 }
1502
1503 static int gtalk_digit_end(struct ast_channel *chan, char digit, unsigned int duration)
1504 {
1505         return gtalk_digit(chan, digit, duration);
1506 }
1507
1508 static int gtalk_digit(struct ast_channel *ast, char digit, unsigned int duration)
1509 {
1510         struct gtalk_pvt *p = ast->tech_pvt;
1511         struct gtalk *client = p->parent;
1512         iks *iq, *gtalk, *dtmf;
1513         char buffer[2] = {digit, '\0'};
1514         char *lowerthem = NULL;
1515         iq = iks_new("iq");
1516         gtalk = iks_new("gtalk");
1517         dtmf = iks_new("dtmf");
1518         if(!iq || !gtalk || !dtmf) {
1519                 iks_delete(iq);
1520                 iks_delete(gtalk);
1521                 iks_delete(dtmf);
1522                 ast_log(LOG_ERROR, "Did not send dtmf do to memory issue\n");
1523                 return -1;
1524         }
1525
1526         iks_insert_attrib(iq, "type", "set");
1527         iks_insert_attrib(iq, "to", p->them);
1528         iks_insert_attrib(iq, "from", p->us);
1529         iks_insert_attrib(iq, "id", client->connection->mid);
1530         ast_aji_increment_mid(client->connection->mid);
1531         iks_insert_attrib(gtalk, "xmlns", "http://jabber.org/protocol/gtalk");
1532         iks_insert_attrib(gtalk, "action", "session-info");
1533         /* put the initiator attribute to lower case if we receive the call 
1534          * otherwise GoogleTalk won't establish the session */
1535         if (!p->initiator) {
1536                 char c;
1537                 char *t = lowerthem = ast_strdupa(p->them);
1538                 while (((c = *t) != '/') && (*t++ = tolower(c)));
1539         }
1540         iks_insert_attrib(gtalk, "initiator", p->initiator ? p->us: lowerthem);
1541         iks_insert_attrib(gtalk, "sid", p->sid);
1542         iks_insert_attrib(dtmf, "xmlns", "http://jabber.org/protocol/gtalk/info/dtmf");
1543         iks_insert_attrib(dtmf, "code", buffer);
1544         iks_insert_node(iq, gtalk);
1545         iks_insert_node(gtalk, dtmf);
1546
1547         ast_mutex_lock(&p->lock);
1548         if (ast->dtmff.frametype == AST_FRAME_DTMF_BEGIN || duration == 0) {
1549                 iks_insert_attrib(dtmf, "action", "button-down");
1550         } else if (ast->dtmff.frametype == AST_FRAME_DTMF_END || duration != 0) {
1551                 iks_insert_attrib(dtmf, "action", "button-up");
1552         }
1553         ast_aji_send(client->connection, iq);
1554
1555         iks_delete(iq);
1556         iks_delete(gtalk);
1557         iks_delete(dtmf);
1558         ast_mutex_unlock(&p->lock);
1559         return 0;
1560 }
1561
1562 static int gtalk_sendhtml(struct ast_channel *ast, int subclass, const char *data, int datalen)
1563 {
1564         ast_log(LOG_NOTICE, "XXX Implement gtalk sendhtml XXX\n");
1565
1566         return -1;
1567 }
1568
1569 /* Not in use right now.
1570 static int gtalk_auto_congest(void *nothing)
1571 {
1572         struct gtalk_pvt *p = nothing;
1573
1574         ast_mutex_lock(&p->lock);
1575         if (p->owner) {
1576                 if (!ast_channel_trylock(p->owner)) {
1577                         ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
1578                         ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
1579                         ast_channel_unlock(p->owner);
1580                 }
1581         }
1582         ast_mutex_unlock(&p->lock);
1583         return 0;
1584 }
1585 */
1586
1587 /*! \brief Initiate new call, part of PBX interface 
1588  *      dest is the dial string */
1589 static int gtalk_call(struct ast_channel *ast, char *dest, int timeout)
1590 {
1591         struct gtalk_pvt *p = ast->tech_pvt;
1592
1593         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
1594                 ast_log(LOG_WARNING, "gtalk_call called on %s, neither down nor reserved\n", ast->name);
1595                 return -1;
1596         }
1597
1598         ast_setstate(ast, AST_STATE_RING);
1599         if (!p->ringrule) {
1600                 ast_copy_string(p->ring, p->parent->connection->mid, sizeof(p->ring));
1601                 p->ringrule = iks_filter_add_rule(p->parent->connection->f, gtalk_ringing_ack, p,
1602                                                         IKS_RULE_ID, p->ring, IKS_RULE_DONE);
1603         } else
1604                 ast_log(LOG_WARNING, "Whoa, already have a ring rule!\n");
1605
1606         gtalk_invite(p, p->them, p->us, p->sid, 1);
1607         gtalk_create_candidates(p->parent, p, p->sid, p->them, p->us);
1608
1609         return 0;
1610 }
1611
1612 /*! \brief Hangup a call through the gtalk proxy channel */
1613 static int gtalk_hangup(struct ast_channel *ast)
1614 {
1615         struct gtalk_pvt *p = ast->tech_pvt;
1616         struct gtalk *client;
1617
1618         ast_mutex_lock(&p->lock);
1619         client = p->parent;
1620         p->owner = NULL;
1621         ast->tech_pvt = NULL;
1622         if (!p->alreadygone)
1623                 gtalk_action(client, p, "terminate");
1624         ast_mutex_unlock(&p->lock);
1625
1626         gtalk_free_pvt(client, p);
1627         ast_module_unref(ast_module_info->self);
1628
1629         return 0;
1630 }
1631
1632 /*! \brief Part of PBX interface */
1633 static struct ast_channel *gtalk_request(const char *type, int format, void *data, int *cause)
1634 {
1635         struct gtalk_pvt *p = NULL;
1636         struct gtalk *client = NULL;
1637         char *sender = NULL, *to = NULL, *s = NULL;
1638         struct ast_channel *chan = NULL;
1639
1640         if (data) {
1641                 s = ast_strdupa(data);
1642                 if (s) {
1643                         sender = strsep(&s, "/");
1644                         if (sender && (sender[0] != '\0'))
1645                                 to = strsep(&s, "/");
1646                         if (!to) {
1647                                 ast_log(LOG_ERROR, "Bad arguments in Gtalk Dialstring: %s\n", (char*) data);
1648                                 return NULL;
1649                         }
1650                 }
1651         }
1652
1653         client = find_gtalk(to, sender);
1654         if (!client) {
1655                 ast_log(LOG_WARNING, "Could not find recipient.\n");
1656                 return NULL;
1657         }
1658         if (!strcasecmp(client->name, "guest")){
1659                 /* the guest account is not tied to any configured XMPP client,
1660                    let's set it now */
1661                 client->connection = ast_aji_get_client(sender);
1662                 if (!client->connection) {
1663                         ast_log(LOG_ERROR, "No XMPP client to talk to, us (partial JID) : %s\n", sender);
1664                         ASTOBJ_UNREF(client, gtalk_member_destroy);
1665                         return NULL;
1666                 }
1667         }
1668        
1669         ASTOBJ_WRLOCK(client);
1670         p = gtalk_alloc(client, strchr(sender, '@') ? sender : client->connection->jid->full, strchr(to, '@') ? to : client->user, NULL);
1671         if (p)
1672                 chan = gtalk_new(client, p, AST_STATE_DOWN, to);
1673
1674         ASTOBJ_UNLOCK(client);
1675         return chan;
1676 }
1677
1678 /*! \brief CLI command "gtalk show channels" */
1679 static char *gtalk_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1680 {
1681 #define FORMAT  "%-30.30s  %-30.30s  %-15.15s  %-5.5s %-5.5s \n"
1682         struct gtalk_pvt *p;
1683         struct ast_channel *chan;
1684         int numchans = 0;
1685         char them[AJI_MAX_JIDLEN];
1686         char *jid = NULL;
1687         char *resource = NULL;
1688
1689         switch (cmd) {
1690         case CLI_INIT:
1691                 e->command = "gtalk show channels";
1692                 e->usage =
1693                         "Usage: gtalk show channels\n"
1694                         "       Shows current state of the Gtalk channels.\n";
1695                 return NULL;
1696         case CLI_GENERATE:
1697                 return NULL;
1698         }
1699
1700         if (a->argc != 3)
1701                 return CLI_SHOWUSAGE;
1702
1703         ast_mutex_lock(&gtalklock);
1704         ast_cli(a->fd, FORMAT, "Channel", "Jabber ID", "Resource", "Read", "Write");
1705         ASTOBJ_CONTAINER_TRAVERSE(&gtalk_list, 1, {
1706                 ASTOBJ_WRLOCK(iterator);
1707                 p = iterator->p;
1708                 while(p) {
1709                         chan = p->owner;
1710                         ast_copy_string(them, p->them, sizeof(them));
1711                         jid = them;
1712                         resource = strchr(them, '/');
1713                         if (!resource)
1714                                 resource = "None";
1715                         else {
1716                                 *resource = '\0';
1717                                 resource ++;
1718                         }
1719                         if (chan)
1720                                 ast_cli(a->fd, FORMAT, 
1721                                         chan->name,
1722                                         jid,
1723                                         resource,
1724                                         ast_getformatname(chan->readformat),
1725                                         ast_getformatname(chan->writeformat)                                    
1726                                         );
1727                         else 
1728                                 ast_log(LOG_WARNING, "No available channel\n");
1729                         numchans ++;
1730                         p = p->next;
1731                 }
1732                 ASTOBJ_UNLOCK(iterator);
1733         });
1734
1735         ast_mutex_unlock(&gtalklock);
1736
1737         ast_cli(a->fd, "%d active gtalk channel%s\n", numchans, (numchans != 1) ? "s" : "");
1738         return CLI_SUCCESS;
1739 #undef FORMAT
1740 }
1741
1742 /*! \brief CLI command "gtalk reload" */
1743 static char *gtalk_do_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1744 {
1745         switch (cmd) {
1746         case CLI_INIT:
1747                 e->command = "gtalk reload";
1748                 e->usage =
1749                         "Usage: gtalk reload\n"
1750                         "       Reload gtalk channel driver.\n";
1751                 return NULL;
1752         case CLI_GENERATE:
1753                 return NULL;
1754         }       
1755         
1756         ast_verbose("IT DOES WORK!\n");
1757         return CLI_SUCCESS;
1758 }
1759
1760 static int gtalk_parser(void *data, ikspak *pak)
1761 {
1762         struct gtalk *client = ASTOBJ_REF((struct gtalk *) data);
1763
1764         if (iks_find_attrib(pak->x, "type") && !strcmp(iks_find_attrib (pak->x, "type"),"error")) {
1765                 ast_log(LOG_NOTICE, "Remote peer reported an error, trying to establish the call anyway\n");
1766         }
1767         else if (iks_find_with_attrib(pak->x, "session", "type", "initiate")) {
1768                 /* New call */
1769                 gtalk_newcall(client, pak);
1770         } else if (iks_find_with_attrib(pak->x, "session", "type", "candidates") || iks_find_with_attrib(pak->x, "session", "type", "transport-info")) {
1771                 ast_debug(3, "About to add candidate!\n");
1772                 gtalk_add_candidate(client, pak);
1773                 ast_debug(3, "Candidate Added!\n");
1774         } else if (iks_find_with_attrib(pak->x, "session", "type", "accept")) {
1775                 gtalk_is_answered(client, pak);
1776         } else if (iks_find_with_attrib(pak->x, "session", "type", "transport-accept")) {
1777                 gtalk_is_accepted(client, pak);
1778         } else if (iks_find_with_attrib(pak->x, "session", "type", "content-info") || iks_find_with_attrib(pak->x, "gtalk", "action", "session-info")) {
1779                 gtalk_handle_dtmf(client, pak);
1780         } else if (iks_find_with_attrib(pak->x, "session", "type", "terminate")) {
1781                 gtalk_hangup_farend(client, pak);
1782         } else if (iks_find_with_attrib(pak->x, "session", "type", "reject")) {
1783                 gtalk_hangup_farend(client, pak);
1784         }
1785         ASTOBJ_UNREF(client, gtalk_member_destroy);
1786         return IKS_FILTER_EAT;
1787 }
1788
1789 /* Not using this anymore probably take out soon 
1790 static struct gtalk_candidate *gtalk_create_candidate(char *args)
1791 {
1792         char *name, *type, *preference, *protocol;
1793         struct gtalk_candidate *res;
1794         res = ast_calloc(1, sizeof(*res));
1795         if (args)
1796                 name = args;
1797         if ((args = strchr(args, ','))) {
1798                 *args = '\0';
1799                 args++;
1800                 preference = args;
1801         }
1802         if ((args = strchr(args, ','))) {
1803                 *args = '\0';
1804                 args++;
1805                 protocol = args;
1806         }
1807         if ((args = strchr(args, ','))) {
1808                 *args = '\0';
1809                 args++;
1810                 type = args;
1811         }
1812         if (name)
1813                 ast_copy_string(res->name, name, sizeof(res->name));
1814         if (preference) {
1815                 res->preference = atof(preference);
1816         }
1817         if (protocol) {
1818                 if (!strcasecmp("udp", protocol))
1819                         res->protocol = AJI_PROTOCOL_UDP;
1820                 if (!strcasecmp("ssltcp", protocol))
1821                         res->protocol = AJI_PROTOCOL_SSLTCP;
1822         }
1823         if (type) {
1824                 if (!strcasecmp("stun", type))
1825                         res->type = AJI_CONNECT_STUN;
1826                 if (!strcasecmp("local", type))
1827                         res->type = AJI_CONNECT_LOCAL;
1828                 if (!strcasecmp("relay", type))
1829                         res->type = AJI_CONNECT_RELAY;
1830         }
1831
1832         return res;
1833 }
1834 */
1835
1836 static int gtalk_create_member(char *label, struct ast_variable *var, int allowguest,
1837                                                                 struct ast_codec_pref prefs, char *context,
1838                                                                 struct gtalk *member)
1839 {
1840         struct aji_client *client;
1841
1842         if (!member)
1843                 ast_log(LOG_WARNING, "Out of memory.\n");
1844
1845         ast_copy_string(member->name, label, sizeof(member->name));
1846         ast_copy_string(member->user, label, sizeof(member->user));
1847         ast_copy_string(member->context, context, sizeof(member->context));
1848         member->allowguest = allowguest;
1849         member->prefs = prefs;
1850         while (var) {
1851 #if 0
1852                 struct gtalk_candidate *candidate = NULL;
1853 #endif
1854                 if (!strcasecmp(var->name, "username"))
1855                         ast_copy_string(member->user, var->value, sizeof(member->user));
1856                 else if (!strcasecmp(var->name, "disallow"))
1857                         ast_parse_allow_disallow(&member->prefs, &member->capability, var->value, 0);
1858                 else if (!strcasecmp(var->name, "allow"))
1859                         ast_parse_allow_disallow(&member->prefs, &member->capability, var->value, 1);
1860                 else if (!strcasecmp(var->name, "context"))
1861                         ast_copy_string(member->context, var->value, sizeof(member->context));
1862                 else if (!strcasecmp(var->name, "parkinglot"))
1863                         ast_copy_string(member->parkinglot, var->value, sizeof(member->parkinglot));
1864 #if 0
1865                 else if (!strcasecmp(var->name, "candidate")) {
1866                         candidate = gtalk_create_candidate(var->value);
1867                         if (candidate) {
1868                                 candidate->next = member->ourcandidates;
1869                                 member->ourcandidates = candidate;
1870                         }
1871                 }
1872 #endif
1873                 else if (!strcasecmp(var->name, "connection")) {
1874                         if ((client = ast_aji_get_client(var->value))) {
1875                                 member->connection = client;
1876                                 iks_filter_add_rule(client->f, gtalk_parser, member, 
1877                                                     IKS_RULE_TYPE, IKS_PAK_IQ, 
1878                                                     IKS_RULE_FROM_PARTIAL, member->user,
1879                                                     IKS_RULE_NS, "http://www.google.com/session",
1880                                                     IKS_RULE_DONE);
1881
1882                         } else {
1883                                 ast_log(LOG_ERROR, "connection referenced not found!\n");
1884                                 return 0;
1885                         }
1886                 }
1887                 var = var->next;
1888         }
1889         if (member->connection && member->user)
1890                 member->buddy = ASTOBJ_CONTAINER_FIND(&member->connection->buddies, member->user);
1891         else {
1892                 ast_log(LOG_ERROR, "No Connection or Username!\n");
1893         }
1894         return 1;
1895 }
1896
1897 static int gtalk_load_config(void)
1898 {
1899         char *cat = NULL;
1900         struct ast_config *cfg = NULL;
1901         char context[AST_MAX_CONTEXT];
1902         char parkinglot[AST_MAX_CONTEXT];
1903         int allowguest = 1;
1904         struct ast_variable *var;
1905         struct gtalk *member;
1906         struct ast_codec_pref prefs;
1907         struct aji_client_container *clients;
1908         struct gtalk_candidate *global_candidates = NULL;
1909         struct hostent *hp;
1910         struct ast_hostent ahp;
1911         struct ast_flags config_flags = { 0 };
1912
1913         cfg = ast_config_load(GOOGLE_CONFIG, config_flags);
1914         if (!cfg) {
1915                 return 0;
1916         } else if (cfg == CONFIG_STATUS_FILEINVALID) {
1917                 ast_log(LOG_ERROR, "Config file %s is in an invalid format.  Aborting.\n", GOOGLE_CONFIG);
1918                 return 0;
1919         }
1920
1921         /* Copy the default jb config over global_jbconf */
1922         memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
1923
1924         cat = ast_category_browse(cfg, NULL);
1925         for (var = ast_variable_browse(cfg, "general"); var; var = var->next) {
1926                 /* handle jb conf */
1927                 if (!ast_jb_read_conf(&global_jbconf, var->name, var->value))
1928                         continue;
1929
1930                 if (!strcasecmp(var->name, "allowguest"))
1931                         allowguest =
1932                                 (ast_true(ast_variable_retrieve(cfg, "general", "allowguest"))) ? 1 : 0;
1933                 else if (!strcasecmp(var->name, "disallow"))
1934                         ast_parse_allow_disallow(&prefs, &global_capability, var->value, 0);
1935                 else if (!strcasecmp(var->name, "allow"))
1936                         ast_parse_allow_disallow(&prefs, &global_capability, var->value, 1);
1937                 else if (!strcasecmp(var->name, "context"))
1938                         ast_copy_string(context, var->value, sizeof(context));
1939                 else if (!strcasecmp(var->name, "parkinglot"))
1940                         ast_copy_string(parkinglot, var->value, sizeof(parkinglot));
1941                 else if (!strcasecmp(var->name, "bindaddr")) {
1942                         if (!(hp = ast_gethostbyname(var->value, &ahp))) {
1943                                 ast_log(LOG_WARNING, "Invalid address: %s\n", var->value);
1944                         } else {
1945                                 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
1946                         }
1947                 }
1948 /*  Idea to allow for custom candidates  */
1949 /*
1950                 else if (!strcasecmp(var->name, "candidate")) {
1951                         candidate = gtalk_create_candidate(var->value);
1952                         if (candidate) {
1953                                 candidate->next = global_candidates;
1954                                 global_candidates = candidate;
1955                         }
1956                 }
1957 */
1958         }
1959         while (cat) {
1960                 if (strcasecmp(cat, "general")) {
1961                         var = ast_variable_browse(cfg, cat);
1962                         member = ast_calloc(1, sizeof(*member));
1963                         ASTOBJ_INIT(member);
1964                         ASTOBJ_WRLOCK(member);
1965                         if (!strcasecmp(cat, "guest")) {
1966                                 ast_copy_string(member->name, "guest", sizeof(member->name));
1967                                 ast_copy_string(member->user, "guest", sizeof(member->user));
1968                                 ast_copy_string(member->context, context, sizeof(member->context));
1969                                 ast_copy_string(member->parkinglot, parkinglot, sizeof(member->parkinglot));
1970                                 member->allowguest = allowguest;
1971                                 member->prefs = prefs;
1972                                 while (var) {
1973                                         if (!strcasecmp(var->name, "disallow"))
1974                                                 ast_parse_allow_disallow(&member->prefs, &member->capability,
1975                                                                                                  var->value, 0);
1976                                         else if (!strcasecmp(var->name, "allow"))
1977                                                 ast_parse_allow_disallow(&member->prefs, &member->capability,
1978                                                                                                  var->value, 1);
1979                                         else if (!strcasecmp(var->name, "context"))
1980                                                 ast_copy_string(member->context, var->value,
1981                                                                                 sizeof(member->context));
1982                                         else if (!strcasecmp(var->name, "parkinglot"))
1983                                                 ast_copy_string(member->parkinglot, var->value,
1984                                                                                 sizeof(member->parkinglot));
1985 /*  Idea to allow for custom candidates  */
1986 /*
1987                                         else if (!strcasecmp(var->name, "candidate")) {
1988                                                 candidate = gtalk_create_candidate(var->value);
1989                                                 if (candidate) {
1990                                                         candidate->next = member->ourcandidates;
1991                                                         member->ourcandidates = candidate;
1992                                                 }
1993                                         }
1994 */
1995                                         var = var->next;
1996                                 }
1997                                 ASTOBJ_UNLOCK(member);
1998                                 clients = ast_aji_get_clients();
1999                                 if (clients) {
2000                                         ASTOBJ_CONTAINER_TRAVERSE(clients, 1, {
2001                                                 ASTOBJ_WRLOCK(iterator);
2002                                                 ASTOBJ_WRLOCK(member);
2003                                                 member->connection = NULL;
2004                                                 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);
2005                                                 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);
2006                                                 ASTOBJ_UNLOCK(member);
2007                                                 ASTOBJ_UNLOCK(iterator);
2008                                         });
2009                                         ASTOBJ_CONTAINER_LINK(&gtalk_list, member);
2010                                         ASTOBJ_UNREF(member, gtalk_member_destroy);
2011                                 } else {
2012                                         ASTOBJ_UNLOCK(member);
2013                                         ASTOBJ_UNREF(member, gtalk_member_destroy);
2014                                 }
2015                         } else {
2016                                 ASTOBJ_UNLOCK(member);
2017                                 if (gtalk_create_member(cat, var, allowguest, prefs, context, member))
2018                                         ASTOBJ_CONTAINER_LINK(&gtalk_list, member);
2019                                 ASTOBJ_UNREF(member, gtalk_member_destroy);
2020                         }
2021                 }
2022                 cat = ast_category_browse(cfg, cat);
2023         }
2024         gtalk_free_candidates(global_candidates);
2025         return 1;
2026 }
2027
2028 /*! \brief Load module into PBX, register channel */
2029 static int load_module(void)
2030 {
2031         char *jabber_loaded = ast_module_helper("", "res_jabber.so", 0, 0, 0, 0);
2032         free(jabber_loaded);
2033         if (!jabber_loaded) {
2034                 /* If embedded, check for a different module name */
2035                 jabber_loaded = ast_module_helper("", "res_jabber", 0, 0, 0, 0);
2036                 free(jabber_loaded);
2037                 if (!jabber_loaded) {
2038                         ast_log(LOG_ERROR, "chan_gtalk.so depends upon res_jabber.so\n");
2039                         return AST_MODULE_LOAD_DECLINE;
2040                 }
2041         }
2042
2043         ASTOBJ_CONTAINER_INIT(&gtalk_list);
2044         if (!gtalk_load_config()) {
2045                 ast_log(LOG_ERROR, "Unable to read config file %s. Not loading module.\n", GOOGLE_CONFIG);
2046                 return 0;
2047         }
2048
2049         sched = sched_context_create();
2050         if (!sched) 
2051                 ast_log(LOG_WARNING, "Unable to create schedule context\n");
2052
2053         io = io_context_create();
2054         if (!io) 
2055                 ast_log(LOG_WARNING, "Unable to create I/O context\n");
2056
2057         if (ast_find_ourip(&__ourip, bindaddr)) {
2058                 ast_log(LOG_WARNING, "Unable to get own IP address, Gtalk disabled\n");
2059                 return 0;
2060         }
2061
2062         ast_rtp_glue_register(&gtalk_rtp_glue);
2063         ast_cli_register_multiple(gtalk_cli, ARRAY_LEN(gtalk_cli));
2064
2065         /* Make sure we can register our channel type */
2066         if (ast_channel_register(&gtalk_tech)) {
2067                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", gtalk_tech.type);
2068                 return -1;
2069         }
2070         return 0;
2071 }
2072
2073 /*! \brief Reload module */
2074 static int reload(void)
2075 {
2076         return 0;
2077 }
2078
2079 /*! \brief Unload the gtalk channel from Asterisk */
2080 static int unload_module(void)
2081 {
2082         struct gtalk_pvt *privates = NULL;
2083         ast_cli_unregister_multiple(gtalk_cli, ARRAY_LEN(gtalk_cli));
2084         /* First, take us out of the channel loop */
2085         ast_channel_unregister(&gtalk_tech);
2086         ast_rtp_glue_unregister(&gtalk_rtp_glue);
2087
2088         if (!ast_mutex_lock(&gtalklock)) {
2089                 /* Hangup all interfaces if they have an owner */
2090                 ASTOBJ_CONTAINER_TRAVERSE(&gtalk_list, 1, {
2091                         ASTOBJ_WRLOCK(iterator);
2092                         privates = iterator->p;
2093                         while(privates) {
2094                                 if (privates->owner)
2095                                         ast_softhangup(privates->owner, AST_SOFTHANGUP_APPUNLOAD);
2096                                 privates = privates->next;
2097                         }
2098                         iterator->p = NULL;
2099                         ASTOBJ_UNLOCK(iterator);
2100                 });
2101                 ast_mutex_unlock(&gtalklock);
2102         } else {
2103                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
2104                 return -1;
2105         }
2106         ASTOBJ_CONTAINER_DESTROYALL(&gtalk_list, gtalk_member_destroy);
2107         ASTOBJ_CONTAINER_DESTROY(&gtalk_list);
2108         return 0;
2109 }
2110
2111 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Gtalk Channel Driver",
2112                 .load = load_module,
2113                 .unload = unload_module,
2114                 .reload = reload,
2115                );