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