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