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