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