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