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