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