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