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