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