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