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