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