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