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