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