Fix refcounting of sip_pvt in test_sip_rtpqos test and unlink it from the list of...
[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_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_nolock();
1067         tmp->jointcap = ast_format_cap_alloc_nolock();
1068         tmp->peercap = ast_format_cap_alloc_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         ast_channel_tech_set(tmp, &gtalk_tech);
1153
1154         /* Select our native format based on codec preference until we receive
1155            something from another device to the contrary. */
1156         if (!(ast_format_cap_is_empty(i->jointcap))) {
1157                 what = i->jointcap;
1158         } else if (i->cap) {
1159                 what = i->cap;
1160         } else {
1161                 what = global_capability;
1162         }
1163
1164         /* Set Frame packetization */
1165         if (i->rtp) {
1166                 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(i->rtp), i->rtp, &i->prefs);
1167         }
1168
1169         ast_codec_choose(&i->prefs, what, 1, &tmpfmt);
1170         ast_format_cap_add(ast_channel_nativeformats(tmp), &tmpfmt);
1171
1172         ast_format_cap_iter_start(i->jointcap);
1173         while (!(ast_format_cap_iter_next(i->jointcap, &tmpfmt))) {
1174                 if (AST_FORMAT_GET_TYPE(tmpfmt.id) == AST_FORMAT_TYPE_VIDEO) {
1175                         ast_format_cap_add(ast_channel_nativeformats(tmp), &tmpfmt);
1176                 }
1177         }
1178         ast_format_cap_iter_end(i->jointcap);
1179
1180         if (i->rtp) {
1181                 ast_channel_set_fd(tmp, 0, ast_rtp_instance_fd(i->rtp, 0));
1182                 ast_channel_set_fd(tmp, 1, ast_rtp_instance_fd(i->rtp, 1));
1183         }
1184         if (i->vrtp) {
1185                 ast_channel_set_fd(tmp, 2, ast_rtp_instance_fd(i->vrtp, 0));
1186                 ast_channel_set_fd(tmp, 3, ast_rtp_instance_fd(i->vrtp, 1));
1187         }
1188         if (state == AST_STATE_RING)
1189                 ast_channel_rings_set(tmp, 1);
1190         ast_channel_adsicpe_set(tmp, AST_ADSI_UNAVAILABLE);
1191
1192         ast_best_codec(ast_channel_nativeformats(tmp), &tmpfmt);
1193         ast_format_copy(ast_channel_writeformat(tmp), &tmpfmt);
1194         ast_format_copy(ast_channel_rawwriteformat(tmp), &tmpfmt);
1195         ast_format_copy(ast_channel_readformat(tmp), &tmpfmt);
1196         ast_format_copy(ast_channel_rawreadformat(tmp), &tmpfmt);
1197         ast_channel_tech_pvt_set(tmp, i);
1198
1199         ast_channel_callgroup_set(tmp, client->callgroup);
1200         ast_channel_pickupgroup_set(tmp, client->pickupgroup);
1201         ast_channel_caller(tmp)->id.name.presentation = client->callingpres;
1202         ast_channel_caller(tmp)->id.number.presentation = client->callingpres;
1203         if (!ast_strlen_zero(client->accountcode))
1204                 ast_channel_accountcode_set(tmp, client->accountcode);
1205         if (client->amaflags)
1206                 ast_channel_amaflags_set(tmp, client->amaflags);
1207         if (!ast_strlen_zero(client->language))
1208                 ast_channel_language_set(tmp, client->language);
1209         if (!ast_strlen_zero(client->musicclass))
1210                 ast_channel_musicclass_set(tmp, client->musicclass);
1211         if (!ast_strlen_zero(client->parkinglot))
1212                 ast_channel_parkinglot_set(tmp, client->parkinglot);
1213         gtalk_set_owner(i, tmp);
1214         ast_module_ref(ast_module_info->self);
1215         ast_channel_context_set(tmp, client->context);
1216         ast_channel_exten_set(tmp, i->exten);
1217
1218         if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s")) {
1219                 ast_channel_dialed(tmp)->number.str = ast_strdup(i->exten);
1220         }
1221         ast_channel_priority_set(tmp, 1);
1222         if (i->rtp)
1223                 ast_jb_configure(tmp, &global_jbconf);
1224         if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
1225                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", ast_channel_name(tmp));
1226                 ast_channel_hangupcause_set(tmp, AST_CAUSE_SWITCH_CONGESTION);
1227                 ast_hangup(tmp);
1228                 tmp = NULL;
1229         }
1230         return tmp;
1231 }
1232
1233 static int gtalk_action(struct gtalk *client, struct gtalk_pvt *p, const char *action)
1234 {
1235         iks *request, *session = NULL;
1236         int res = -1;
1237         char *lowerthem = NULL;
1238
1239         request = iks_new("iq");
1240         if (request) {
1241                 iks_insert_attrib(request, "type", "set");
1242                 iks_insert_attrib(request, "from", p->us);
1243                 iks_insert_attrib(request, "to", p->them);
1244                 iks_insert_attrib(request, "id", client->connection->mid);
1245                 ast_aji_increment_mid(client->connection->mid);
1246                 session = iks_new("session");
1247                 if (session) {
1248                         iks_insert_attrib(session, "type", action);
1249                         iks_insert_attrib(session, "id", p->sid);
1250                         /* put the initiator attribute to lower case if we receive the call
1251                          * otherwise GoogleTalk won't establish the session */
1252                         if (!p->initiator) {
1253                                 char c;
1254                                 char *t = lowerthem = ast_strdupa(p->them);
1255                                 while (((c = *t) != '/') && (*t++ = tolower(c)));
1256                         }
1257                         iks_insert_attrib(session, "initiator", p->initiator ? p->us : lowerthem);
1258                         iks_insert_attrib(session, "xmlns", GOOGLE_NS);
1259                         iks_insert_node(request, session);
1260                         ast_aji_send(client->connection, request);
1261                         res = 0;
1262                 }
1263         }
1264
1265         iks_delete(session);
1266         iks_delete(request);
1267
1268         return res;
1269 }
1270
1271 static void gtalk_free_candidates(struct gtalk_candidate *candidate)
1272 {
1273         struct gtalk_candidate *last;
1274         while (candidate) {
1275                 last = candidate;
1276                 candidate = candidate->next;
1277                 ast_free(last);
1278         }
1279 }
1280
1281 static void gtalk_free_pvt(struct gtalk *client, struct gtalk_pvt *p)
1282 {
1283         struct gtalk_pvt *cur, *prev = NULL;
1284         cur = client->p;
1285         while (cur) {
1286                 if (cur == p) {
1287                         if (prev)
1288                                 prev->next = p->next;
1289                         else
1290                                 client->p = p->next;
1291                         break;
1292                 }
1293                 prev = cur;
1294                 cur = cur->next;
1295         }
1296         if (p->ringrule)
1297                 iks_filter_remove_rule(p->parent->connection->f, p->ringrule);
1298         if (p->owner)
1299                 ast_log(LOG_WARNING, "Uh oh, there's an owner, this is going to be messy.\n");
1300         if (p->rtp)
1301                 ast_rtp_instance_destroy(p->rtp);
1302         if (p->vrtp)
1303                 ast_rtp_instance_destroy(p->vrtp);
1304         gtalk_free_candidates(p->theircandidates);
1305         p->cap = ast_format_cap_destroy(p->cap);
1306         p->jointcap = ast_format_cap_destroy(p->jointcap);
1307         p->peercap = ast_format_cap_destroy(p->peercap);
1308         ast_free(p);
1309 }
1310
1311
1312 static int gtalk_newcall(struct gtalk *client, ikspak *pak)
1313 {
1314         struct gtalk_pvt *p, *tmp = client->p;
1315         struct ast_channel *chan;
1316         int res;
1317         iks *codec;
1318         char *from = NULL;
1319         char s1[BUFSIZ], s2[BUFSIZ], s3[BUFSIZ];
1320         int peernoncodeccapability;
1321         char *sid;
1322
1323         /* Make sure our new call doesn't exist yet */
1324         from = iks_find_attrib(pak->x,"to");
1325         if (!from) {
1326                 from = client->connection->jid->full;
1327         }
1328
1329         while (tmp) {
1330                 if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid) ||
1331                         (iks_find_attrib(pak->query, "id") && !strcmp(iks_find_attrib(pak->query, "id"), tmp->sid))) {
1332                         ast_log(LOG_NOTICE, "Ignoring duplicate call setup on SID %s\n", tmp->sid);
1333                         gtalk_response(client, from, pak, "out-of-order", NULL);
1334                         return -1;
1335                 }
1336                 tmp = tmp->next;
1337         }
1338
1339         if (!strcasecmp(client->name, "guest")){
1340                 /* the guest account is not tied to any configured XMPP client,
1341                    let's set it now */
1342                 if (client->connection) {
1343                         ASTOBJ_UNREF(client->connection, ast_aji_client_destroy);
1344                 }
1345                 client->connection = ast_aji_get_client(from);
1346                 if (!client->connection) {
1347                         ast_log(LOG_ERROR, "No XMPP client to talk to, us (partial JID) : %s\n", from);
1348                         return -1;
1349                 }
1350         }
1351
1352         if (!(sid = iks_find_attrib(pak->query, "id"))) {
1353                 ast_log(LOG_WARNING, "Received Initiate without id attribute. Can not start call.\n");
1354                 return -1;
1355         }
1356
1357         p = gtalk_alloc(client, from, pak->from->full, sid);
1358         if (!p) {
1359                 ast_log(LOG_WARNING, "Unable to allocate gtalk structure!\n");
1360                 return -1;
1361         }
1362
1363         chan = gtalk_new(client, p, AST_STATE_DOWN, pak->from->user, NULL);
1364         if (!chan) {
1365                 gtalk_free_pvt(client, p);
1366                 return -1;
1367         }
1368
1369         ast_mutex_lock(&p->lock);
1370         ast_copy_string(p->them, pak->from->full, sizeof(p->them));
1371         ast_copy_string(p->sid, sid, sizeof(p->sid));
1372
1373         /* codec points to the first <payload-type/> tag */
1374         codec = iks_first_tag(iks_first_tag(pak->query));
1375
1376         while (codec) {
1377                 char *codec_id = iks_find_attrib(codec, "id");
1378                 char *codec_name = iks_find_attrib(codec, "name");
1379                 if (!codec_id || !codec_name) {
1380                         codec = iks_next_tag(codec);
1381                         continue;
1382                 }
1383                 if (!strcmp(S_OR(iks_name(codec), ""), "vid:payload-type") && p->vrtp) {
1384                         ast_rtp_codecs_payloads_set_m_type(
1385                                 ast_rtp_instance_get_codecs(p->vrtp),
1386                                 p->vrtp,
1387                                 atoi(codec_id));
1388                         ast_rtp_codecs_payloads_set_rtpmap_type(
1389                                 ast_rtp_instance_get_codecs(p->vrtp),
1390                                 p->vrtp,
1391                                 atoi(codec_id),
1392                                 "video",
1393                                 codec_name,
1394                                 0);
1395                 } else {
1396                         ast_rtp_codecs_payloads_set_m_type(
1397                                 ast_rtp_instance_get_codecs(p->rtp),
1398                                 p->rtp,
1399                                 atoi(codec_id));
1400                         ast_rtp_codecs_payloads_set_rtpmap_type(
1401                                 ast_rtp_instance_get_codecs(p->rtp),
1402                                 p->rtp,
1403                                 atoi(codec_id),
1404                                 "audio",
1405                                 codec_name,
1406                                 0);
1407                 }
1408                 codec = iks_next_tag(codec);
1409         }
1410
1411         /* Now gather all of the codecs that we are asked for */
1412         ast_rtp_codecs_payload_formats(ast_rtp_instance_get_codecs(p->rtp), p->peercap, &peernoncodeccapability);
1413         ast_format_cap_joint_copy(p->cap, p->peercap, p->jointcap);
1414         ast_mutex_unlock(&p->lock);
1415
1416         ast_setstate(chan, AST_STATE_RING);
1417         if (ast_format_cap_is_empty(p->jointcap)) {
1418                 ast_log(LOG_WARNING, "Capabilities don't match : us - %s, peer - %s, combined - %s \n", ast_getformatname_multiple(s1, BUFSIZ, p->cap),
1419                         ast_getformatname_multiple(s2, BUFSIZ, p->peercap),
1420                         ast_getformatname_multiple(s3, BUFSIZ, p->jointcap));
1421                 /* close session if capabilities don't match */
1422                 gtalk_action(client, p, "reject");
1423                 p->alreadygone = 1;
1424                 gtalk_hangup(chan);
1425                 ast_channel_release(chan);
1426                 return -1;
1427         }
1428
1429         res = ast_pbx_start(chan);
1430
1431         switch (res) {
1432         case AST_PBX_FAILED:
1433                 ast_log(LOG_WARNING, "Failed to start PBX :(\n");
1434                 gtalk_response(client, from, pak, "service-unavailable", NULL);
1435                 break;
1436         case AST_PBX_CALL_LIMIT:
1437                 ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
1438                 gtalk_response(client, from, pak, "service-unavailable", NULL);
1439                 break;
1440         case AST_PBX_SUCCESS:
1441                 gtalk_response(client, from, pak, NULL, NULL);
1442                 gtalk_create_candidates(client, p, p->sid, p->them, p->us);
1443                 /* nothing to do */
1444                 break;
1445         }
1446
1447         return 1;
1448 }
1449
1450 static int gtalk_update_externip(void)
1451 {
1452         int sock;
1453         char *newaddr;
1454         struct sockaddr_in answer = { 0, };
1455         struct sockaddr_in *dst;
1456         struct ast_sockaddr tmp_dst;
1457
1458         if (!stunaddr.sin_addr.s_addr) {
1459                 return -1;
1460         }
1461         dst = &stunaddr;
1462
1463         sock = socket(AF_INET, SOCK_DGRAM, 0);
1464         if (sock < 0) {
1465                 ast_log(LOG_WARNING, "Unable to create STUN socket: %s\n", strerror(errno));
1466                 return -1;
1467         }
1468
1469         ast_sockaddr_from_sin(&tmp_dst, dst);
1470         if (ast_connect(sock, &tmp_dst) != 0) {
1471                 ast_log(LOG_WARNING, "STUN Failed to connect to %s\n", ast_sockaddr_stringify(&tmp_dst));
1472                 close(sock);
1473                 return -1;
1474         }
1475
1476         if ((ast_stun_request(sock, &stunaddr, NULL, &answer))) {
1477                 close(sock);
1478                 return -1;
1479         }
1480
1481         newaddr = ast_strdupa(ast_inet_ntoa(answer.sin_addr));
1482         memcpy(externip, newaddr, sizeof(externip));
1483
1484         close(sock);
1485         return 0;
1486
1487 }
1488
1489 static int gtalk_update_stun(struct gtalk *client, struct gtalk_pvt *p)
1490 {
1491         struct gtalk_candidate *tmp;
1492         struct hostent *hp;
1493         struct ast_hostent ahp;
1494         struct sockaddr_in sin = { 0, };
1495         struct sockaddr_in aux = { 0, };
1496         struct ast_sockaddr sin_tmp;
1497         struct ast_sockaddr aux_tmp;
1498
1499         if (time(NULL) == p->laststun)
1500                 return 0;
1501
1502         tmp = p->theircandidates;
1503         p->laststun = time(NULL);
1504         while (tmp) {
1505                 char username[256];
1506
1507                 /* Find the IP address of the host */
1508                 if (!(hp = ast_gethostbyname(tmp->ip, &ahp))) {
1509                         ast_log(LOG_WARNING, "Could not get host by name for %s\n", tmp->ip);
1510                         tmp = tmp->next;
1511                         continue;
1512                 }
1513                 sin.sin_family = AF_INET;
1514                 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
1515                 sin.sin_port = htons(tmp->port);
1516                 snprintf(username, sizeof(username), "%s%s", tmp->username, p->ourcandidates->username);
1517
1518                 /* Find out the result of the STUN */
1519                 ast_rtp_instance_get_remote_address(p->rtp, &aux_tmp);
1520                 ast_sockaddr_to_sin(&aux_tmp, &aux);
1521
1522                 /* If the STUN result is different from the IP of the hostname,
1523                  * lock on the stun IP of the hostname advertised by the
1524                  * remote client */
1525                 if (aux.sin_addr.s_addr && (aux.sin_addr.s_addr != sin.sin_addr.s_addr)) {
1526                         ast_rtp_instance_stun_request(p->rtp, &aux_tmp, username);
1527                 } else {
1528                         ast_sockaddr_from_sin(&sin_tmp, &sin);
1529                         ast_rtp_instance_stun_request(p->rtp, &sin_tmp, username);
1530                 }
1531                 if (aux.sin_addr.s_addr) {
1532                         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);
1533                         ast_debug(4, "Sending STUN request to %s\n", tmp->ip);
1534                 }
1535
1536                 tmp = tmp->next;
1537         }
1538         return 1;
1539 }
1540
1541 static int gtalk_add_candidate(struct gtalk *client, ikspak *pak)
1542 {
1543         struct gtalk_pvt *p = NULL, *tmp = NULL;
1544         struct aji_client *c = client->connection;
1545         struct gtalk_candidate *newcandidate = NULL;
1546         iks *traversenodes = NULL, *receipt = NULL;
1547         char *from;
1548
1549         from = iks_find_attrib(pak->x,"to");
1550         if (!from) {
1551                 from = c->jid->full;
1552         }
1553
1554         for (tmp = client->p; tmp; tmp = tmp->next) {
1555                 if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid) ||
1556                         (iks_find_attrib(pak->query, "id") && !strcmp(iks_find_attrib(pak->query, "id"), tmp->sid))) {
1557                         p = tmp;
1558                         break;
1559                 }
1560         }
1561
1562         if (!p) {
1563                 return -1;
1564         }
1565         traversenodes = pak->query;
1566         while(traversenodes) {
1567                 if(!strcasecmp(S_OR(iks_name(traversenodes), ""), "session")) {
1568                         traversenodes = iks_first_tag(traversenodes);
1569                         continue;
1570                 }
1571                 if(!strcasecmp(S_OR(iks_name(traversenodes), ""), "ses:session")) {
1572                         traversenodes = iks_child(traversenodes);
1573                         continue;
1574                 }
1575                 if(!strcasecmp(S_OR(iks_name(traversenodes), ""), "candidate") || !strcasecmp(S_OR(iks_name(traversenodes), ""), "ses:candidate")) {
1576                         newcandidate = ast_calloc(1, sizeof(*newcandidate));
1577                         if (!newcandidate)
1578                                 return 0;
1579                         ast_copy_string(newcandidate->name,
1580                                 S_OR(iks_find_attrib(traversenodes, "name"), ""),
1581                                 sizeof(newcandidate->name));
1582                         ast_copy_string(newcandidate->ip,
1583                                 S_OR(iks_find_attrib(traversenodes, "address"), ""),
1584                                 sizeof(newcandidate->ip));
1585                         newcandidate->port = atoi(iks_find_attrib(traversenodes, "port"));
1586                         ast_copy_string(newcandidate->username,
1587                                 S_OR(iks_find_attrib(traversenodes, "username"), ""),
1588                                 sizeof(newcandidate->username));
1589                         ast_copy_string(newcandidate->password,
1590                                 S_OR(iks_find_attrib(traversenodes, "password"), ""),
1591                                 sizeof(newcandidate->password));
1592                         newcandidate->preference = atof(iks_find_attrib(traversenodes, "preference"));
1593                         if (!strcasecmp(S_OR(iks_find_attrib(traversenodes, "protocol"), ""), "udp"))
1594                                 newcandidate->protocol = AJI_PROTOCOL_UDP;
1595                         if (!strcasecmp(S_OR(iks_find_attrib(traversenodes, "protocol"), ""), "ssltcp"))
1596                                 newcandidate->protocol = AJI_PROTOCOL_SSLTCP;
1597
1598                         if (!strcasecmp(S_OR(iks_find_attrib(traversenodes, "type"), ""), "stun"))
1599                                 newcandidate->type = AJI_CONNECT_STUN;
1600                         if (!strcasecmp(S_OR(iks_find_attrib(traversenodes, "type"), ""), "local"))
1601                                 newcandidate->type = AJI_CONNECT_LOCAL;
1602                         if (!strcasecmp(S_OR(iks_find_attrib(traversenodes, "type"), ""), "relay"))
1603                                 newcandidate->type = AJI_CONNECT_RELAY;
1604                         ast_copy_string(newcandidate->network,
1605                                 S_OR(iks_find_attrib(traversenodes, "network"), ""),
1606                                 sizeof(newcandidate->network));
1607                         newcandidate->generation = atoi(S_OR(iks_find_attrib(traversenodes, "generation"), "0"));
1608                         newcandidate->next = NULL;
1609
1610                         newcandidate->next = p->theircandidates;
1611                         p->theircandidates = newcandidate;
1612                         p->laststun = 0;
1613                         gtalk_update_stun(p->parent, p);
1614                         newcandidate = NULL;
1615                 }
1616                 traversenodes = iks_next_tag(traversenodes);
1617         }
1618
1619         receipt = iks_new("iq");
1620         iks_insert_attrib(receipt, "type", "result");
1621         iks_insert_attrib(receipt, "from", from);
1622         iks_insert_attrib(receipt, "to", S_OR(iks_find_attrib(pak->x, "from"), ""));
1623         iks_insert_attrib(receipt, "id", S_OR(iks_find_attrib(pak->x, "id"), ""));
1624         ast_aji_send(c, receipt);
1625
1626         iks_delete(receipt);
1627
1628         return 1;
1629 }
1630
1631 static struct ast_frame *gtalk_rtp_read(struct ast_channel *ast, struct gtalk_pvt *p)
1632 {
1633         struct ast_frame *f;
1634
1635         if (!p->rtp) {
1636                 return &ast_null_frame;
1637         }
1638         f = ast_rtp_instance_read(p->rtp, 0);
1639         gtalk_update_stun(p->parent, p);
1640         if (p->owner) {
1641                 /* We already hold the channel lock */
1642                 if (f->frametype == AST_FRAME_VOICE) {
1643                         if (!ast_format_cap_iscompatible(ast_channel_nativeformats(p->owner), &f->subclass.format)) {
1644                                 ast_debug(1, "Oooh, format changed to %s\n", ast_getformatname(&f->subclass.format));
1645                                 ast_format_cap_remove_bytype(ast_channel_nativeformats(p->owner), AST_FORMAT_TYPE_AUDIO);
1646                                 ast_format_cap_add(ast_channel_nativeformats(p->owner), &f->subclass.format);
1647                                 ast_set_read_format(p->owner, ast_channel_readformat(p->owner));
1648                                 ast_set_write_format(p->owner, ast_channel_writeformat(p->owner));
1649                         }
1650                         /* if ((ast_test_flag(p, SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
1651                                 f = ast_dsp_process(p->owner, p->vad, f);
1652                                 if (option_debug && f && (f->frametype == AST_FRAME_DTMF))
1653                                         ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass);
1654                 } */
1655                 }
1656         }
1657         return f;
1658 }
1659
1660 static struct ast_frame *gtalk_read(struct ast_channel *ast)
1661 {
1662         struct ast_frame *fr;
1663         struct gtalk_pvt *p = ast_channel_tech_pvt(ast);
1664
1665         ast_mutex_lock(&p->lock);
1666         fr = gtalk_rtp_read(ast, p);
1667         ast_mutex_unlock(&p->lock);
1668         return fr;
1669 }
1670
1671 /*! \brief Send frame to media channel (rtp) */
1672 static int gtalk_write(struct ast_channel *ast, struct ast_frame *frame)
1673 {
1674         struct gtalk_pvt *p = ast_channel_tech_pvt(ast);
1675         int res = 0;
1676         char buf[256];
1677
1678         switch (frame->frametype) {
1679         case AST_FRAME_VOICE:
1680                 if (!(ast_format_cap_iscompatible(ast_channel_nativeformats(ast), &frame->subclass.format))) {
1681                         ast_log(LOG_WARNING,
1682                                         "Asked to transmit frame type %s, while native formats is %s (read/write = %s/%s)\n",
1683                                         ast_getformatname(&frame->subclass.format),
1684                                         ast_getformatname_multiple(buf, sizeof(buf), ast_channel_nativeformats(ast)),
1685                                         ast_getformatname(ast_channel_readformat(ast)),
1686                                         ast_getformatname(ast_channel_writeformat(ast)));
1687                         return 0;
1688                 }
1689                 if (p) {
1690                         ast_mutex_lock(&p->lock);
1691                         if (p->rtp) {
1692                                 res = ast_rtp_instance_write(p->rtp, frame);
1693                         }
1694                         ast_mutex_unlock(&p->lock);
1695                 }
1696                 break;
1697         case AST_FRAME_VIDEO:
1698                 if (p) {
1699                         ast_mutex_lock(&p->lock);
1700                         if (p->vrtp) {
1701                                 res = ast_rtp_instance_write(p->vrtp, frame);
1702                         }
1703                         ast_mutex_unlock(&p->lock);
1704                 }
1705                 break;
1706         case AST_FRAME_IMAGE:
1707                 return 0;
1708                 break;
1709         default:
1710                 ast_log(LOG_WARNING, "Can't send %d type frames with Gtalk write\n",
1711                                 frame->frametype);
1712                 return 0;
1713         }
1714
1715         return res;
1716 }
1717
1718 static int gtalk_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1719 {
1720         struct gtalk_pvt *p = ast_channel_tech_pvt(newchan);
1721         ast_mutex_lock(&p->lock);
1722
1723         if ((p->owner != oldchan)) {
1724                 ast_mutex_unlock(&p->lock);
1725                 return -1;
1726         }
1727         if (p->owner == oldchan) {
1728                 gtalk_set_owner(p, newchan);
1729         }
1730         ast_mutex_unlock(&p->lock);
1731         return 0;
1732 }
1733
1734 static int gtalk_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
1735 {
1736         int res = 0;
1737
1738         switch (condition) {
1739         case AST_CONTROL_HOLD:
1740                 ast_moh_start(ast, data, NULL);
1741                 break;
1742         case AST_CONTROL_UNHOLD:
1743                 ast_moh_stop(ast);
1744                 break;
1745         default:
1746                 ast_debug(3, "Don't know how to indicate condition '%d'\n", condition);
1747                 /* fallthrough */
1748         case AST_CONTROL_PVT_CAUSE_CODE:
1749                 res = -1;
1750         }
1751
1752         return res;
1753 }
1754
1755 static int gtalk_sendtext(struct ast_channel *chan, const char *text)
1756 {
1757         int res = 0;
1758         struct aji_client *client = NULL;
1759         struct gtalk_pvt *p = ast_channel_tech_pvt(chan);
1760
1761         if (!p->parent) {
1762                 ast_log(LOG_ERROR, "Parent channel not found\n");
1763                 return -1;
1764         }
1765         if (!p->parent->connection) {
1766                 ast_log(LOG_ERROR, "XMPP client not found\n");
1767                 return -1;
1768         }
1769         client = p->parent->connection;
1770         res = ast_aji_send_chat(client, p->them, text);
1771         return res;
1772 }
1773
1774 static int gtalk_digit_begin(struct ast_channel *chan, char digit)
1775 {
1776         struct gtalk_pvt *p = ast_channel_tech_pvt(chan);
1777         int res = 0;
1778
1779         ast_mutex_lock(&p->lock);
1780         if (p->rtp) {
1781                 ast_rtp_instance_dtmf_begin(p->rtp, digit);
1782         } else {
1783                 res = -1;
1784         }
1785         ast_mutex_unlock(&p->lock);
1786
1787         return res;
1788 }
1789
1790 static int gtalk_digit_end(struct ast_channel *chan, char digit, unsigned int duration)
1791 {
1792         struct gtalk_pvt *p = ast_channel_tech_pvt(chan);
1793         int res = 0;
1794
1795         ast_mutex_lock(&p->lock);
1796         if (p->rtp) {
1797                 ast_rtp_instance_dtmf_end_with_duration(p->rtp, digit, duration);
1798         } else {
1799                 res = -1;
1800         }
1801         ast_mutex_unlock(&p->lock);
1802
1803         return res;
1804 }
1805
1806 /* This function is of not in use at the moment, but I am choosing to leave this
1807  * within the code base as a reference to how DTMF is possible through
1808  * jingle signaling.  However, google currently does DTMF through the RTP. */
1809 #if 0
1810 static int gtalk_digit(struct ast_channel *ast, char digit, unsigned int duration)
1811 {
1812         struct gtalk_pvt *p = ast->tech_pvt;
1813         struct gtalk *client = p->parent;
1814         iks *iq, *gtalk, *dtmf;
1815         char buffer[2] = {digit, '\0'};
1816         char *lowerthem = NULL;
1817         iq = iks_new("iq");
1818         gtalk = iks_new("gtalk");
1819         dtmf = iks_new("dtmf");
1820         if(!iq || !gtalk || !dtmf) {
1821                 iks_delete(iq);
1822                 iks_delete(gtalk);
1823                 iks_delete(dtmf);
1824                 ast_log(LOG_ERROR, "Did not send dtmf do to memory issue\n");
1825                 return -1;
1826         }
1827
1828         iks_insert_attrib(iq, "type", "set");
1829         iks_insert_attrib(iq, "to", p->them);
1830         iks_insert_attrib(iq, "from", p->us);
1831         iks_insert_attrib(iq, "id", client->connection->mid);
1832         ast_aji_increment_mid(client->connection->mid);
1833         iks_insert_attrib(gtalk, "xmlns", "http://jabber.org/protocol/gtalk");
1834         iks_insert_attrib(gtalk, "action", "session-info");
1835         // put the initiator attribute to lower case if we receive the call
1836         // otherwise GoogleTalk won't establish the session
1837         if (!p->initiator) {
1838                 char c;
1839                 char *t = lowerthem = ast_strdupa(p->them);
1840                 while (((c = *t) != '/') && (*t++ = tolower(c)));
1841         }
1842         iks_insert_attrib(gtalk, "initiator", p->initiator ? p->us: lowerthem);
1843         iks_insert_attrib(gtalk, "sid", p->sid);
1844         iks_insert_attrib(dtmf, "xmlns", "http://jabber.org/protocol/gtalk/info/dtmf");
1845         iks_insert_attrib(dtmf, "code", buffer);
1846         iks_insert_node(iq, gtalk);
1847         iks_insert_node(gtalk, dtmf);
1848
1849         ast_mutex_lock(&p->lock);
1850         if (ast->dtmff.frametype == AST_FRAME_DTMF_BEGIN || duration == 0) {
1851                 iks_insert_attrib(dtmf, "action", "button-down");
1852         } else if (ast->dtmff.frametype == AST_FRAME_DTMF_END || duration != 0) {
1853                 iks_insert_attrib(dtmf, "action", "button-up");
1854         }
1855         ast_aji_send(client->connection, iq);
1856
1857         iks_delete(iq);
1858         iks_delete(gtalk);
1859         iks_delete(dtmf);
1860         ast_mutex_unlock(&p->lock);
1861         return 0;
1862 }
1863 #endif
1864
1865 static int gtalk_sendhtml(struct ast_channel *ast, int subclass, const char *data, int datalen)
1866 {
1867         ast_log(LOG_NOTICE, "XXX Implement gtalk sendhtml XXX\n");
1868
1869         return -1;
1870 }
1871
1872 /*!\brief Initiate new call, part of PBX interface
1873  * dest is the dial string */
1874 static int gtalk_call(struct ast_channel *ast, const char *dest, int timeout)
1875 {
1876         struct gtalk_pvt *p = ast_channel_tech_pvt(ast);
1877
1878         if ((ast_channel_state(ast) != AST_STATE_DOWN) && (ast_channel_state(ast) != AST_STATE_RESERVED)) {
1879                 ast_log(LOG_WARNING, "gtalk_call called on %s, neither down nor reserved\n", ast_channel_name(ast));
1880                 return -1;
1881         }
1882
1883         ast_setstate(ast, AST_STATE_RING);
1884         if (!p->ringrule) {
1885                 ast_copy_string(p->ring, p->parent->connection->mid, sizeof(p->ring));
1886                 p->ringrule = iks_filter_add_rule(p->parent->connection->f, gtalk_ringing_ack, p,
1887                                                         IKS_RULE_ID, p->ring, IKS_RULE_DONE);
1888         } else {
1889                 ast_log(LOG_WARNING, "Whoa, already have a ring rule!\n");
1890         }
1891
1892         gtalk_invite(p, p->them, p->us, p->sid, 1);
1893
1894         return 0;
1895 }
1896
1897 /*! \brief Hangup a call through the gtalk proxy channel */
1898 static int gtalk_hangup(struct ast_channel *ast)
1899 {
1900         struct gtalk_pvt *p = ast_channel_tech_pvt(ast);
1901         struct gtalk *client;
1902
1903         ast_mutex_lock(&p->lock);
1904         client = p->parent;
1905         gtalk_set_owner(p, NULL);
1906         ast_channel_tech_pvt_set(ast, NULL);
1907         if (!p->alreadygone) {
1908                 gtalk_action(client, p, "terminate");
1909         }
1910         ast_mutex_unlock(&p->lock);
1911
1912         gtalk_free_pvt(client, p);
1913         ast_module_unref(ast_module_info->self);
1914
1915         return 0;
1916 }
1917
1918 /*!\brief Part of PBX interface */
1919 static struct ast_channel *gtalk_request(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, const char *data, int *cause)
1920 {
1921         struct gtalk_pvt *p = NULL;
1922         struct gtalk *client = NULL;
1923         char *sender = NULL, *to = NULL, *s = NULL;
1924         struct ast_channel *chan = NULL;
1925
1926         if (data) {
1927                 s = ast_strdupa(data);
1928                 sender = strsep(&s, "/");
1929                 if (sender && (sender[0] != '\0')) {
1930                         to = strsep(&s, "/");
1931                 }
1932                 if (!to) {
1933                         ast_log(LOG_ERROR, "Bad arguments in Gtalk Dialstring: %s\n", data);
1934                         return NULL;
1935                 }
1936                 if (!to) {
1937                         ast_log(LOG_ERROR, "Bad arguments in Gtalk Dialstring: %s\n", (char*) data);
1938                         return NULL;
1939                 }
1940         }
1941
1942         client = find_gtalk(to, sender);
1943         if (!client) {
1944                 ast_log(LOG_WARNING, "Could not find recipient.\n");
1945                 return NULL;
1946         }
1947         if (!strcasecmp(client->name, "guest")){
1948                 /* the guest account is not tied to any configured XMPP client,
1949                    let's set it now */
1950                 if (client->connection) {
1951                         ASTOBJ_UNREF(client->connection, ast_aji_client_destroy);
1952                 }
1953                 client->connection = ast_aji_get_client(sender);
1954                 if (!client->connection) {
1955                         ast_log(LOG_ERROR, "No XMPP client to talk to, us (partial JID) : %s\n", sender);
1956                         ASTOBJ_UNREF(client, gtalk_member_destroy);
1957                         return NULL;
1958                 }
1959         }
1960
1961         ASTOBJ_WRLOCK(client);
1962         p = gtalk_alloc(client, strchr(sender, '@') ? sender : client->connection->jid->full, strchr(to, '@') ? to : client->user, NULL);
1963         if (p) {
1964                 chan = gtalk_new(client, p, AST_STATE_DOWN, to, requestor ? ast_channel_linkedid(requestor) : NULL);
1965         }
1966         ASTOBJ_UNLOCK(client);
1967         return chan;
1968 }
1969
1970 /*! \brief CLI command "gtalk show channels" */
1971 static char *gtalk_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1972 {
1973 #define FORMAT  "%-30.30s  %-30.30s  %-15.15s  %-5.5s %-5.5s \n"
1974         struct gtalk_pvt *p;
1975         struct ast_channel *chan;
1976         int numchans = 0;
1977         char them[AJI_MAX_JIDLEN];
1978         char *jid = NULL;
1979         char *resource = NULL;
1980
1981         switch (cmd) {
1982         case CLI_INIT:
1983                 e->command = "gtalk show channels";
1984                 e->usage =
1985                         "Usage: gtalk show channels\n"
1986                         "       Shows current state of the Gtalk channels.\n";
1987                 return NULL;
1988         case CLI_GENERATE:
1989                 return NULL;
1990         }
1991
1992         if (a->argc != 3)
1993                 return CLI_SHOWUSAGE;
1994
1995         ast_mutex_lock(&gtalklock);
1996         ast_cli(a->fd, FORMAT, "Channel", "Jabber ID", "Resource", "Read", "Write");
1997         ASTOBJ_CONTAINER_TRAVERSE(&gtalk_list, 1, {
1998                 ASTOBJ_WRLOCK(iterator);
1999                 p = iterator->p;
2000                 while(p) {
2001                         chan = p->owner;
2002                         ast_copy_string(them, p->them, sizeof(them));
2003                         jid = them;
2004                         resource = strchr(them, '/');
2005                         if (!resource)
2006                                 resource = "None";
2007                         else {
2008                                 *resource = '\0';
2009                                 resource ++;
2010                         }
2011                         if (chan)
2012                                 ast_cli(a->fd, FORMAT,
2013                                         ast_channel_name(chan),
2014                                         jid,
2015                                         resource,
2016                                         ast_getformatname(ast_channel_readformat(chan)),
2017                                         ast_getformatname(ast_channel_writeformat(chan))
2018                                         );
2019                         else
2020                                 ast_log(LOG_WARNING, "No available channel\n");
2021                         numchans ++;
2022                         p = p->next;
2023                 }
2024                 ASTOBJ_UNLOCK(iterator);
2025         });
2026
2027         ast_mutex_unlock(&gtalklock);
2028
2029         ast_cli(a->fd, "%d active gtalk channel%s\n", numchans, (numchans != 1) ? "s" : "");
2030         return CLI_SUCCESS;
2031 #undef FORMAT
2032 }
2033
2034 /*! \brief List global settings for the GoogleTalk channel */
2035 static char *gtalk_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2036 {
2037         char codec_buf[BUFSIZ];
2038         switch (cmd) {
2039         case CLI_INIT:
2040                 e->command = "gtalk show settings";
2041                 e->usage =
2042                         "Usage: gtalk show settings\n"
2043                         "       Provides detailed list of the configuration on the GoogleTalk channel.\n";
2044                 return NULL;
2045         case CLI_GENERATE:
2046                 return NULL;
2047         }
2048
2049         if (a->argc != 3) {
2050                 return CLI_SHOWUSAGE;
2051         }
2052
2053 #define FORMAT "  %-25.20s  %-15.30s\n"
2054
2055         ast_cli(a->fd, "\nGlobal Settings:\n");
2056         ast_cli(a->fd, "----------------\n");
2057         ast_cli(a->fd, FORMAT, "UDP Bindaddress:", ast_inet_ntoa(bindaddr.sin_addr));
2058         ast_cli(a->fd, FORMAT, "Stun Address:", global_stunaddr != 0 ? ast_inet_ntoa(stunaddr.sin_addr) : "Disabled");
2059         ast_cli(a->fd, FORMAT, "External IP:", S_OR(externip, "Disabled"));
2060         ast_cli(a->fd, FORMAT, "Context:", global_context);
2061         ast_cli(a->fd, FORMAT, "Codecs:", ast_getformatname_multiple(codec_buf, sizeof(codec_buf) - 1, global_capability));
2062         ast_cli(a->fd, FORMAT, "Parking Lot:", global_parkinglot);
2063         ast_cli(a->fd, FORMAT, "Allow Guest:", AST_CLI_YESNO(global_allowguest));
2064         ast_cli(a->fd, "\n----\n");
2065
2066         return CLI_SUCCESS;
2067 #undef FORMAT
2068 }
2069
2070 /*! \brief CLI command "gtalk reload"
2071  *  \todo XXX TODO make this work. */
2072 #if 0
2073 static char *gtalk_do_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2074 {
2075         switch (cmd) {
2076         case CLI_INIT:
2077                 e->command = "gtalk reload";
2078                 e->usage =
2079                         "Usage: gtalk reload\n"
2080                         "       Reload gtalk channel driver.\n";
2081                 return NULL;
2082         case CLI_GENERATE:
2083                 return NULL;
2084         }
2085
2086         ast_verbose("IT DOES WORK!\n");
2087         return CLI_SUCCESS;
2088 }
2089 #endif
2090
2091 static int gtalk_parser(void *data, ikspak *pak)
2092 {
2093         struct gtalk *client = ASTOBJ_REF((struct gtalk *) data);
2094         int res;
2095         iks *tmp;
2096
2097         if (!strcasecmp(iks_name(pak->query), "jin:jingle") && (tmp = iks_next(pak->query)) && !strcasecmp(iks_name(tmp), "ses:session")) {
2098                 ast_debug(1, "New method detected. Skipping jingle offer and using old gtalk method.\n");
2099                 pak->query = tmp;
2100         }
2101
2102         if (!strcmp(S_OR(iks_find_attrib(pak->x, "type"), ""), "error")) {
2103                 ast_log(LOG_NOTICE, "Remote peer reported an error, trying to establish the call anyway\n");
2104         }
2105
2106         if (ast_strlen_zero(iks_find_attrib(pak->query, "type"))) {
2107                 ast_log(LOG_NOTICE, "No attribute \"type\" found.  Ignoring message.\n");
2108         } else if (!strcmp(iks_find_attrib(pak->query, "type"), "initiate")) {
2109                 /* New call */
2110                 gtalk_newcall(client, pak);
2111         } else if (!strcmp(iks_find_attrib(pak->query, "type"), "candidates") || !strcmp(iks_find_attrib(pak->query, "type"), "transport-info")) {
2112                 ast_debug(3, "About to add candidate!\n");
2113                 res = gtalk_add_candidate(client, pak);
2114                 if (!res) {
2115                         ast_log(LOG_WARNING, "Could not add any candidate\n");
2116                 } else {
2117                         ast_debug(3, "Candidate Added!\n");
2118                 }
2119         } else if (!strcmp(iks_find_attrib(pak->query, "type"), "accept")) {
2120                 gtalk_is_answered(client, pak);
2121         } else if (!strcmp(iks_find_attrib(pak->query, "type"), "transport-accept")) {
2122                 gtalk_is_accepted(client, pak);
2123         } else if (!strcmp(iks_find_attrib(pak->query, "type"), "content-info") || iks_find_with_attrib(pak->x, "gtalk", "action", "session-info")) {
2124                 gtalk_handle_dtmf(client, pak);
2125         } else if (!strcmp(iks_find_attrib(pak->query, "type"), "terminate")) {
2126                 gtalk_hangup_farend(client, pak);
2127         } else if (!strcmp(iks_find_attrib(pak->query, "type"), "reject")) {
2128                 gtalk_hangup_farend(client, pak);
2129         }
2130         ASTOBJ_UNREF(client, gtalk_member_destroy);
2131         return IKS_FILTER_EAT;
2132 }
2133
2134 static int gtalk_create_member(char *label, struct ast_variable *var, int allowguest,
2135                                                                 struct ast_codec_pref prefs, char *context,
2136                                                                 struct gtalk *member)
2137 {
2138         struct aji_client *client;
2139
2140         if (!member)
2141                 ast_log(LOG_WARNING, "Out of memory.\n");
2142
2143         ast_copy_string(member->name, label, sizeof(member->name));
2144         ast_copy_string(member->user, label, sizeof(member->user));
2145         ast_copy_string(member->context, context, sizeof(member->context));
2146         member->allowguest = allowguest;
2147         member->prefs = prefs;
2148         while (var) {
2149                 if (!strcasecmp(var->name, "username"))
2150                         ast_copy_string(member->user, var->value, sizeof(member->user));
2151                 else if (!strcasecmp(var->name, "disallow"))
2152                         ast_parse_allow_disallow(&member->prefs, member->cap, var->value, 0);
2153                 else if (!strcasecmp(var->name, "allow"))
2154                         ast_parse_allow_disallow(&member->prefs, member->cap, var->value, 1);
2155                 else if (!strcasecmp(var->name, "context"))
2156                         ast_copy_string(member->context, var->value, sizeof(member->context));
2157                 else if (!strcasecmp(var->name, "parkinglot"))
2158                         ast_copy_string(member->parkinglot, var->value, sizeof(member->parkinglot));
2159                 else if (!strcasecmp(var->name, "connection")) {
2160                         if ((client = ast_aji_get_client(var->value))) {
2161                                 member->connection = client;
2162                                 iks_filter_add_rule(client->f, gtalk_parser, member,
2163                                                     IKS_RULE_TYPE, IKS_PAK_IQ,
2164                                                     IKS_RULE_FROM_PARTIAL, member->user,
2165                                                     IKS_RULE_NS, GOOGLE_NS,
2166                                                     IKS_RULE_DONE);
2167                         } else {
2168                                 ast_log(LOG_ERROR, "connection referenced not found!\n");
2169                                 return 0;
2170                         }
2171                 }
2172                 var = var->next;
2173         }
2174         if (member->connection && member->user)
2175                 member->buddy = ASTOBJ_CONTAINER_FIND(&member->connection->buddies, member->user);
2176         else {
2177                 ast_log(LOG_ERROR, "No Connection or Username!\n");
2178         }
2179         return 1;
2180 }
2181
2182 static int gtalk_load_config(void)
2183 {
2184         char *cat = NULL;
2185         struct ast_config *cfg = NULL;
2186         struct ast_variable *var;
2187         struct gtalk *member;
2188         struct ast_codec_pref prefs;
2189         struct aji_client_container *clients;
2190         struct gtalk_candidate *global_candidates = NULL;
2191         struct hostent *hp;
2192         struct ast_hostent ahp;
2193         struct ast_flags config_flags = { 0 };
2194
2195         cfg = ast_config_load(GOOGLE_CONFIG, config_flags);
2196         if (!cfg) {
2197                 return 0;
2198         } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2199                 ast_log(LOG_ERROR, "Config file %s is in an invalid format.  Aborting.\n", GOOGLE_CONFIG);
2200                 return 0;
2201         }
2202
2203         /* Copy the default jb config over global_jbconf */
2204         memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
2205
2206         /* set defaults */
2207         memset(&prefs, 0, sizeof(prefs));
2208         memset(&stunaddr, 0, sizeof(stunaddr));
2209         global_stunaddr = 0;
2210         global_allowguest = DEFAULT_ALLOWGUEST;
2211         ast_copy_string(global_context, DEFAULT_CONTEXT, sizeof(global_context));
2212         ast_copy_string(global_parkinglot, DEFAULT_PARKINGLOT, sizeof(global_parkinglot));
2213
2214         cat = ast_category_browse(cfg, NULL);
2215         for (var = ast_variable_browse(cfg, "general"); var; var = var->next) {
2216                 /* handle jb conf */
2217                 if (!ast_jb_read_conf(&global_jbconf, var->name, var->value)) {
2218                         continue;
2219                 }
2220
2221                 if (!strcasecmp(var->name, "allowguest")) {
2222                         global_allowguest = (ast_true(ast_variable_retrieve(cfg, "general", "allowguest"))) ? 1 : 0;
2223                 } else if (!strcasecmp(var->name, "disallow")) {
2224                         ast_parse_allow_disallow(&prefs, global_capability, var->value, 0);
2225                 } else if (!strcasecmp(var->name, "allow")) {
2226                         ast_parse_allow_disallow(&prefs, global_capability, var->value, 1);
2227                 } else if (!strcasecmp(var->name, "context")) {
2228                         ast_copy_string(global_context, var->value, sizeof(global_context));
2229                 } else if (!strcasecmp(var->name, "externip")) {
2230                         ast_copy_string(externip, var->value, sizeof(externip));
2231                 } else if (!strcasecmp(var->name, "parkinglot")) {
2232                         ast_copy_string(global_parkinglot, var->value, sizeof(global_parkinglot));
2233                 } else if (!strcasecmp(var->name, "bindaddr")) {
2234                         if (!(hp = ast_gethostbyname(var->value, &ahp))) {
2235                                 ast_log(LOG_WARNING, "Invalid address: %s\n", var->value);
2236                         } else {
2237                                 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
2238                         }
2239                 } else if (!strcasecmp(var->name, "stunaddr")) {
2240                         stunaddr.sin_port = htons(STANDARD_STUN_PORT);
2241                         global_stunaddr = 1;
2242                         if (ast_parse_arg(var->value, PARSE_INADDR, &stunaddr)) {
2243                                 ast_log(LOG_WARNING, "Invalid STUN server address: %s\n", var->value);
2244                         }
2245                 }
2246         }
2247         while (cat) {
2248                 if (strcasecmp(cat, "general")) {
2249                         var = ast_variable_browse(cfg, cat);
2250                         member = ast_calloc(1, sizeof(*member));
2251                         ASTOBJ_INIT(member);
2252                         ASTOBJ_WRLOCK(member);
2253                         member->cap = ast_format_cap_alloc_nolock();
2254                         if (!strcasecmp(cat, "guest")) {
2255                                 ast_copy_string(member->name, "guest", sizeof(member->name));
2256                                 ast_copy_string(member->user, "guest", sizeof(member->user));
2257                                 ast_copy_string(member->context, global_context, sizeof(member->context));
2258                                 ast_copy_string(member->parkinglot, global_parkinglot, sizeof(member->parkinglot));
2259                                 member->allowguest = global_allowguest;
2260                                 member->prefs = prefs;
2261                                 while (var) {
2262                                         if (!strcasecmp(var->name, "disallow")) {
2263                                                 ast_parse_allow_disallow(&member->prefs, member->cap,
2264                                                                                                  var->value, 0);
2265                                         } else if (!strcasecmp(var->name, "allow")) {
2266                                                 ast_parse_allow_disallow(&member->prefs, member->cap,
2267                                                                                                  var->value, 1);
2268                                         } else if (!strcasecmp(var->name, "context")) {
2269                                                 ast_copy_string(member->context, var->value,
2270                                                                                 sizeof(member->context));
2271                                         } else if (!strcasecmp(var->name, "parkinglot")) {
2272                                                 ast_copy_string(member->parkinglot, var->value,
2273                                                                                 sizeof(member->parkinglot));
2274                                         }
2275                                         var = var->next;
2276                                 }
2277                                 ASTOBJ_UNLOCK(member);
2278                                 clients = ast_aji_get_clients();
2279                                 if (clients) {
2280                                         ASTOBJ_CONTAINER_TRAVERSE(clients, 1, {
2281                                                 ASTOBJ_WRLOCK(iterator);
2282                                                 ASTOBJ_WRLOCK(member);
2283                                                 if (member->connection) {
2284                                                         ASTOBJ_UNREF(member->connection, ast_aji_client_destroy);
2285                                                 }
2286                                                 member->connection = NULL;
2287                                                 iks_filter_add_rule(iterator->f, gtalk_parser, member, IKS_RULE_TYPE, IKS_PAK_IQ, IKS_RULE_NS, GOOGLE_NS, IKS_RULE_DONE);
2288                                                 iks_filter_add_rule(iterator->f, gtalk_parser, member, IKS_RULE_TYPE, IKS_PAK_IQ, IKS_RULE_NS, GOOGLE_JINGLE_NS, IKS_RULE_DONE);
2289                                                 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);
2290                                                 ASTOBJ_UNLOCK(member);
2291                                                 ASTOBJ_UNLOCK(iterator);
2292                                         });
2293                                         ASTOBJ_CONTAINER_LINK(&gtalk_list, member);
2294                                         ASTOBJ_UNREF(member, gtalk_member_destroy);
2295                                 } else {
2296                                         ASTOBJ_UNLOCK(member);
2297                                         ASTOBJ_UNREF(member, gtalk_member_destroy);
2298                                 }
2299                         } else {
2300                                 ASTOBJ_UNLOCK(member);
2301                                 if (gtalk_create_member(cat, var, global_allowguest, prefs, global_context, member)) {
2302                                         ASTOBJ_CONTAINER_LINK(&gtalk_list, member);
2303                                 }
2304                                 ASTOBJ_UNREF(member, gtalk_member_destroy);
2305                         }
2306                 }
2307                 cat = ast_category_browse(cfg, cat);
2308         }
2309
2310         ast_config_destroy(cfg);
2311         gtalk_update_externip();
2312         gtalk_free_candidates(global_candidates);
2313         return 1;
2314 }
2315
2316 /*!
2317  * \brief Load the module
2318  *
2319  * Module loading including tests for configuration or dependencies.
2320  * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
2321  * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
2322  * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
2323  * configuration file or other non-critical problem return
2324  * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
2325  */
2326 static int load_module(void)
2327 {
2328         struct ast_sockaddr bindaddr_tmp;
2329         struct ast_sockaddr ourip_tmp;
2330         char *jabber_loaded = ast_module_helper("", "res_jabber.so", 0, 0, 0, 0);
2331         struct ast_format tmpfmt;
2332
2333         if (!(gtalk_tech.capabilities = ast_format_cap_alloc())) {
2334                 return AST_MODULE_LOAD_DECLINE;
2335         }
2336         if (!(global_capability = ast_format_cap_alloc())) {
2337                 return AST_MODULE_LOAD_DECLINE;
2338         }
2339
2340         ast_format_cap_add_all_by_type(gtalk_tech.capabilities, AST_FORMAT_TYPE_AUDIO);
2341         ast_format_cap_add(global_capability, ast_format_set(&tmpfmt, AST_FORMAT_ULAW, 0));
2342         ast_format_cap_add(global_capability, ast_format_set(&tmpfmt, AST_FORMAT_GSM, 0));
2343         ast_format_cap_add(global_capability, ast_format_set(&tmpfmt, AST_FORMAT_ALAW, 0));
2344         ast_format_cap_add(global_capability, ast_format_set(&tmpfmt, AST_FORMAT_H263, 0));
2345
2346         free(jabber_loaded);
2347         if (!jabber_loaded) {
2348                 /* If embedded, check for a different module name */
2349                 jabber_loaded = ast_module_helper("", "res_jabber", 0, 0, 0, 0);
2350                 free(jabber_loaded);
2351                 if (!jabber_loaded) {
2352                         ast_log(LOG_ERROR, "chan_gtalk.so depends upon res_jabber.so\n");
2353                         return AST_MODULE_LOAD_DECLINE;
2354                 }
2355         }
2356
2357         ASTOBJ_CONTAINER_INIT(&gtalk_list);
2358         if (!gtalk_load_config()) {
2359                 ast_log(LOG_ERROR, "Unable to read config file %s. Not loading module.\n", GOOGLE_CONFIG);
2360                 return 0;
2361         }
2362
2363         sched = ast_sched_context_create();
2364         if (!sched) {
2365                 ast_log(LOG_WARNING, "Unable to create schedule context\n");
2366         }
2367
2368         io = io_context_create();
2369         if (!io) {
2370                 ast_log(LOG_WARNING, "Unable to create I/O context\n");
2371         }
2372
2373         ast_sockaddr_from_sin(&bindaddr_tmp, &bindaddr);
2374         if (gtalk_get_local_ip(&ourip_tmp)) {
2375                 ast_log(LOG_WARNING, "Unable to get own IP address, Gtalk disabled\n");
2376                 return 0;
2377         }
2378         __ourip.s_addr = htonl(ast_sockaddr_ipv4(&ourip_tmp));
2379
2380         ast_rtp_glue_register(&gtalk_rtp_glue);
2381         ast_cli_register_multiple(gtalk_cli, ARRAY_LEN(gtalk_cli));
2382
2383         /* Make sure we can register our channel type */
2384         if (ast_channel_register(&gtalk_tech)) {
2385                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", gtalk_tech.type);
2386                 return -1;
2387         }
2388         return 0;
2389 }
2390
2391 /*! \brief Reload module
2392  *  \todo XXX TODO make this work. */
2393 #if 0
2394 static int reload(void)
2395 {
2396         return 0;
2397 }
2398 #endif
2399 /*! \brief Unload the gtalk channel from Asterisk */
2400 static int unload_module(void)
2401 {
2402         struct gtalk_pvt *privates = NULL;
2403         ast_cli_unregister_multiple(gtalk_cli, ARRAY_LEN(gtalk_cli));
2404         /* First, take us out of the channel loop */
2405         ast_channel_unregister(&gtalk_tech);
2406         ast_rtp_glue_unregister(&gtalk_rtp_glue);
2407
2408         if (!ast_mutex_lock(&gtalklock)) {
2409                 /* Hangup all interfaces if they have an owner */
2410                 ASTOBJ_CONTAINER_TRAVERSE(&gtalk_list, 1, {
2411                         ASTOBJ_WRLOCK(iterator);
2412                         privates = iterator->p;
2413                         while(privates) {
2414                                 if (privates->owner)
2415                                         ast_softhangup(privates->owner, AST_SOFTHANGUP_APPUNLOAD);
2416                                 privates = privates->next;
2417                         }
2418                         iterator->p = NULL;
2419                         ASTOBJ_UNLOCK(iterator);
2420                 });
2421                 ast_mutex_unlock(&gtalklock);
2422         } else {
2423                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
2424                 return -1;
2425         }
2426         ASTOBJ_CONTAINER_DESTROYALL(&gtalk_list, gtalk_member_destroy);
2427         ASTOBJ_CONTAINER_DESTROY(&gtalk_list);
2428         global_capability = ast_format_cap_destroy(global_capability);
2429         gtalk_tech.capabilities = ast_format_cap_destroy(gtalk_tech.capabilities);
2430         return 0;
2431 }
2432
2433 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Gtalk Channel Driver",
2434                 .load = load_module,
2435                 .unload = unload_module,
2436                 /* .reload = reload, */
2437                 .load_pri = AST_MODPRI_CHANNEL_DRIVER,
2438                 );