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