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