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