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