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