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