bug #8076 check option_debug before printing to debug channel.
[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         if (option_debug)
601                 ast_log(LOG_DEBUG, "The client is %s\n", client->name);
602         /* Make sure our new call doesn't exist yet */
603         for (tmp = client->p; tmp; tmp = tmp->next) {
604                 if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid))
605                         break;
606         }
607         
608         from = iks_find_attrib(pak->x, "to");
609         if(!from)
610                 from = client->connection->jid->full;
611
612         if (tmp) {
613                 if (tmp->owner)
614                         ast_queue_control(tmp->owner, AST_CONTROL_ANSWER);
615         } else
616                 ast_log(LOG_NOTICE, "Whoa, didn't find call!\n");
617         gtalk_response(client, from, pak, NULL, NULL);
618         return 1;
619 }
620
621 static int gtalk_handle_dtmf(struct gtalk *client, ikspak *pak)
622 {
623         struct gtalk_pvt *tmp;
624         iks *dtmfnode = NULL;
625         char *dtmf;
626         char *from;
627         /* Make sure our new call doesn't exist yet */
628         for (tmp = client->p; tmp; tmp = tmp->next) {
629                 if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid))
630                         break;
631         }
632         from = iks_find_attrib(pak->x, "to");
633         if(!from)
634                 from = client->connection->jid->full;
635
636
637         if (tmp) {
638                 if(iks_find_with_attrib(pak->x, "dtmf-method", "method", "rtp")) {
639                         gtalk_response(client, from, pak,
640                                         "feature-not-implemented xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'",
641                                         "unsupported-dtmf-method xmlns='http://jabber.org/protocol/gtalk/info/dtmf#errors'");
642                         return -1;
643                 }
644                 if ((dtmfnode = iks_find(pak->x, "dtmf"))) {
645                         if((dtmf = iks_find_attrib(dtmfnode, "code"))) {
646                                 if(iks_find_with_attrib(pak->x, "dtmf", "action", "button-up")) {
647                                         struct ast_frame f = {AST_FRAME_DTMF_BEGIN, };
648                                         f.subclass = dtmf[0];
649                                         ast_queue_frame(tmp->owner, &f);
650                                         ast_verbose("GOOGLE! DTMF-relay event received: %c\n", f.subclass);
651                                 } else if(iks_find_with_attrib(pak->x, "dtmf", "action", "button-down")) {
652                                         struct ast_frame f = {AST_FRAME_DTMF_END, };
653                                         f.subclass = dtmf[0];
654                                         ast_queue_frame(tmp->owner, &f);
655                                         ast_verbose("GOOGLE! DTMF-relay event received: %c\n", f.subclass);
656                                 } else if(iks_find_attrib(pak->x, "dtmf")) { /* 250 millasecond default */
657                                         struct ast_frame f = {AST_FRAME_DTMF, };
658                                         f.subclass = dtmf[0];
659                                         ast_queue_frame(tmp->owner, &f);
660                                         ast_verbose("GOOGLE! DTMF-relay event received: %c\n", f.subclass);
661                                 }
662                         }
663                 }
664                 gtalk_response(client, from, pak, NULL, NULL);
665                 return 1;
666         } else
667                 ast_log(LOG_NOTICE, "Whoa, didn't find call!\n");
668
669         gtalk_response(client, from, pak, NULL, NULL);
670         return 1;
671 }
672
673
674 static int gtalk_hangup_farend(struct gtalk *client, ikspak *pak)
675 {
676         struct gtalk_pvt *tmp;
677         char *from;
678
679         if (option_debug)
680                 ast_log(LOG_DEBUG, "The client is %s\n", client->name);
681         /* Make sure our new call doesn't exist yet */
682         for (tmp = client->p; tmp; tmp = tmp->next) {
683                 if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid))
684                         break;
685         }
686         from = iks_find_attrib(pak->x, "to");
687         if(!from)
688                 from = client->connection->jid->full;
689
690
691         if (tmp) {
692                 tmp->alreadygone = 1;
693                 ast_queue_hangup(tmp->owner);
694         } else
695                 ast_log(LOG_NOTICE, "Whoa, didn't find call!\n");
696         gtalk_response(client, from, pak, NULL, NULL);
697         return 1;
698 }
699
700 static int gtalk_create_candidates(struct gtalk *client, struct gtalk_pvt *p, char *sid, char *from, char *to)
701 {
702         struct gtalk_candidate *tmp;
703         struct aji_client *c = client->connection;
704         struct gtalk_candidate *ours1 = NULL, *ours2 = NULL;
705         struct sockaddr_in sin;
706         struct sockaddr_in dest;
707         struct in_addr us;
708         iks *iq, *gtalk, *candidate, *transport;
709         char user[17], pass[17], preference[5], port[7];
710
711
712         iq = iks_new("iq");
713         gtalk = iks_new("session");
714         candidate = iks_new("candidate");
715         transport = iks_new("transport");
716         if (!iq || !gtalk || !candidate || !transport) {
717                 ast_log(LOG_ERROR, "Memory allocation error\n");
718                 goto safeout;
719         }
720         ours1 = ast_calloc(1, sizeof(*ours1));
721         ours2 = ast_calloc(1, sizeof(*ours2));
722         if (!ours1 || !ours2)
723                 goto safeout;
724
725         iks_insert_attrib(transport, "xmlns","http://www.google.com/transport/p2p");
726         iks_insert_node(iq, gtalk);
727         iks_insert_node(gtalk,transport);
728         iks_insert_node(transport, candidate);
729
730         for (; p; p = p->next) {
731                 if (!strcasecmp(p->sid, sid))
732                         break;
733         }
734
735         if (!p) {
736                 ast_log(LOG_NOTICE, "No matching gtalk session - SID %s!\n", sid);
737                 goto safeout;
738         }
739
740         ast_rtp_get_us(p->rtp, &sin);
741         ast_find_ourip(&us, bindaddr);
742
743         /* Setup our gtalk candidates */
744         ast_copy_string(ours1->name, "rtp", sizeof(ours1->name));
745         ours1->port = ntohs(sin.sin_port);
746         ours1->preference = 1;
747         snprintf(user, sizeof(user), "%08lx%08lx", ast_random(), ast_random());
748         snprintf(pass, sizeof(pass), "%08lx%08lx", ast_random(), ast_random());
749         ast_copy_string(ours1->username, user, sizeof(ours1->username));
750         ast_copy_string(ours1->password, pass, sizeof(ours1->password));
751         ast_copy_string(ours1->ip, ast_inet_ntoa(us), sizeof(ours1->ip));
752         ours1->protocol = AJI_PROTOCOL_UDP;
753         ours1->type = AJI_CONNECT_LOCAL;
754         ours1->generation = 0;
755         p->ourcandidates = ours1;
756
757         if (!ast_strlen_zero(externip)) {
758                 /* XXX We should really stun for this one not just go with externip XXX */
759                 snprintf(user, sizeof(user), "%08lx%08lx", ast_random(), ast_random());
760                 snprintf(pass, sizeof(pass), "%08lx%08lx", ast_random(), ast_random());
761                 ast_copy_string(ours2->username, user, sizeof(ours2->username));
762                 ast_copy_string(ours2->password, pass, sizeof(ours2->password));
763                 ast_copy_string(ours2->ip, externip, sizeof(ours2->ip));
764                 ast_copy_string(ours2->name, "rtp", sizeof(ours1->name));
765                 ours2->port = ntohs(sin.sin_port);
766                 ours2->preference = 0.9;
767                 ours2->protocol = AJI_PROTOCOL_UDP;
768                 ours2->type = AJI_CONNECT_STUN;
769                 ours2->generation = 0;
770                 ours1->next = ours2;
771                 ours2 = NULL;
772         }
773         ours1 = NULL;
774         dest.sin_addr = __ourip;
775         dest.sin_port = sin.sin_port;
776
777
778         for (tmp = p->ourcandidates; tmp; tmp = tmp->next) {
779                 snprintf(port, sizeof(port), "%d", tmp->port);
780                 snprintf(preference, sizeof(preference), "%.2f", tmp->preference);
781                 iks_insert_attrib(iq, "from", to);
782                 iks_insert_attrib(iq, "to", from);
783                 iks_insert_attrib(iq, "type", "set");
784                 iks_insert_attrib(iq, "id", c->mid);
785                 ast_aji_increment_mid(c->mid);
786                 iks_insert_attrib(gtalk, "type", "transport-info");
787                 iks_insert_attrib(gtalk, "id", sid);
788                 iks_insert_attrib(gtalk, "initiator", (p->initiator) ? to : from);
789                 iks_insert_attrib(gtalk, "xmlns", GOOGLE_NS);
790                 iks_insert_attrib(candidate, "name", tmp->name);
791                 iks_insert_attrib(candidate, "address", tmp->ip);
792                 iks_insert_attrib(candidate, "port", port);
793                 iks_insert_attrib(candidate, "username", tmp->username);
794                 iks_insert_attrib(candidate, "password", tmp->password);
795                 iks_insert_attrib(candidate, "preference", preference);
796                 if (tmp->protocol == AJI_PROTOCOL_UDP)
797                         iks_insert_attrib(candidate, "protocol", "udp");
798                 if (tmp->protocol == AJI_PROTOCOL_SSLTCP)
799                         iks_insert_attrib(candidate, "protocol", "ssltcp");
800                 if (tmp->type == AJI_CONNECT_STUN)
801                         iks_insert_attrib(candidate, "type", "stun");
802                 if (tmp->type == AJI_CONNECT_LOCAL)
803                         iks_insert_attrib(candidate, "type", "local");
804                 if (tmp->type == AJI_CONNECT_RELAY)
805                         iks_insert_attrib(candidate, "type", "relay");
806                 iks_insert_attrib(candidate, "network", "0");
807                 iks_insert_attrib(candidate, "generation", "0");
808                 iks_send(c->p, iq);
809         }
810         p->laststun = 0;
811
812 safeout:
813         if (ours1)
814                 free(ours1);
815         if (ours2)
816                 free(ours2);
817         if (iq)
818                 iks_delete(iq);
819         if (gtalk)
820                 iks_delete(gtalk);
821         if (candidate)
822                 iks_delete(candidate);
823         if(transport)
824                 iks_delete(transport);
825         return 1;
826 }
827
828 static struct gtalk_pvt *gtalk_alloc(struct gtalk *client, const char *us, const char *them, const char *sid)
829 {
830         struct gtalk_pvt *tmp = NULL;
831         struct aji_resource *resources = NULL;
832         struct aji_buddy *buddy;
833         char idroster[200];
834         char *data, *exten = NULL;
835
836         if (option_debug)
837                 ast_log(LOG_DEBUG, "The client is %s for alloc\n", client->name);
838         if (!sid && !strchr(them, '/')) {       /* I started call! */
839                 if (!strcasecmp(client->name, "guest")) {
840                         buddy = ASTOBJ_CONTAINER_FIND(&client->connection->buddies, them);
841                         if (buddy)
842                                 resources = buddy->resources;
843                 } else 
844                         resources = client->buddy->resources;
845                 while (resources) {
846                         if (resources->cap->jingle) {
847                                 break;
848                         }
849                         resources = resources->next;
850                 }
851                 if (resources)
852                         snprintf(idroster, sizeof(idroster), "%s/%s", them, resources->resource);
853                 else {
854                         ast_log(LOG_ERROR, "no gtalk capable clients to talk to.\n");
855                         return NULL;
856                 }
857         }
858         if (!(tmp = ast_calloc(1, sizeof(*tmp)))) {
859                 return NULL;
860         }
861         if (sid) {
862                 ast_copy_string(tmp->sid, sid, sizeof(tmp->sid));
863                 ast_copy_string(tmp->them, them, sizeof(tmp->them));
864                 ast_copy_string(tmp->us, us, sizeof(tmp->us));
865         } else {
866                 snprintf(tmp->sid, sizeof(tmp->sid), "%08lx%08lx", ast_random(), ast_random());
867                 ast_copy_string(tmp->them, idroster, sizeof(tmp->them));
868                 ast_copy_string(tmp->us, us, sizeof(tmp->us));
869                 tmp->initiator = 1;
870         }
871         tmp->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
872         tmp->parent = client;
873         if (!tmp->rtp) {
874                 ast_log(LOG_WARNING, "Out of RTP sessions?\n");
875                 free(tmp);
876                 return NULL;
877         }
878
879         if(strchr(tmp->us, '/')) {
880                 data = ast_strdupa((char *) tmp->us);
881                 exten = strsep(&data, "/");
882                 free(data);
883         }
884         ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
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
900         tmp = ast_channel_alloc(1);
901         if (!tmp) {
902                 ast_log(LOG_WARNING, "Unable to allocate Gtalk channel structure!\n");
903                 return NULL;
904         }
905         tmp->tech = &gtalk_tech;
906
907         /* Select our native format based on codec preference until we receive
908            something from another device to the contrary. */
909 /*      ast_verbose("XXXXXXXXXXXXX\nXXX i->jointcapability = %X\nXXX i->capability = %X\nXXX global_capability %X\n XXXXXXXXXXXX\n",i->jointcapability,i->capability,global_capability); */
910         if (i->jointcapability)
911                 what = i->jointcapability;
912         else if (i->capability)
913                 what = i->capability;
914         else
915                 what = global_capability;
916         tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | (i->jointcapability & AST_FORMAT_VIDEO_MASK);
917         fmt = ast_best_codec(tmp->nativeformats);
918
919         if (title)
920                 ast_string_field_build(tmp, name, "Gtalk/%s-%04lx", title, ast_random() & 0xffff);
921         else
922                 ast_string_field_build(tmp, name, "Gtalk/%s-%04lx", i->us, ast_random() & 0xffff);
923
924         if (i->rtp) {
925                 tmp->fds[0] = ast_rtp_fd(i->rtp);
926                 tmp->fds[1] = ast_rtcp_fd(i->rtp);
927         }
928         if (i->vrtp) {
929                 tmp->fds[2] = ast_rtp_fd(i->vrtp);
930                 tmp->fds[3] = ast_rtcp_fd(i->vrtp);
931         }
932         if (state == AST_STATE_RING)
933                 tmp->rings = 1;
934         tmp->adsicpe = AST_ADSI_UNAVAILABLE;
935         tmp->writeformat = fmt;
936         tmp->rawwriteformat = fmt;
937         tmp->readformat = fmt;
938         tmp->rawreadformat = fmt;
939         tmp->tech_pvt = i;
940
941         tmp->callgroup = client->callgroup;
942         tmp->pickupgroup = client->pickupgroup;
943         tmp->cid.cid_pres = client->callingpres;
944         if (!ast_strlen_zero(client->accountcode))
945                 ast_string_field_set(tmp, accountcode, client->accountcode);
946         if (client->amaflags)
947                 tmp->amaflags = client->amaflags;
948         if (!ast_strlen_zero(client->language))
949                 ast_string_field_set(tmp, language, client->language);
950         if (!ast_strlen_zero(client->musicclass))
951                 ast_string_field_set(tmp, musicclass, client->musicclass);
952         i->owner = tmp;
953         ast_mutex_lock(&usecnt_lock);
954         usecnt++;
955         ast_mutex_unlock(&usecnt_lock);
956         ast_copy_string(tmp->context, client->context, sizeof(tmp->context));
957         ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
958         ast_set_callerid(tmp, i->cid_num, i->cid_name, i->cid_num);
959         if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
960                 tmp->cid.cid_dnid = ast_strdup(i->exten);
961         tmp->priority = 1;
962         ast_setstate(tmp, state);
963         if (i->rtp)
964                 ast_jb_configure(tmp, &global_jbconf);
965         if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
966                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
967                 tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
968                 ast_hangup(tmp);
969                 tmp = NULL;
970         }
971
972         return tmp;
973 }
974
975 static int gtalk_action(struct gtalk *client, struct gtalk_pvt *p, const char *action)
976 {
977         iks *request, *session = NULL;
978         int res = -1;
979
980         request = iks_new("iq");
981         if (request) {
982                 iks_insert_attrib(request, "type", "set");
983                 iks_insert_attrib(request, "from", p->us);
984                 iks_insert_attrib(request, "to", p->them);
985                 iks_insert_attrib(request, "id", client->connection->mid);
986                 ast_aji_increment_mid(client->connection->mid);
987                 session = iks_new("session");
988                 if (session) {
989                         iks_insert_attrib(session, "type", action);
990                         iks_insert_attrib(session, "id", p->sid);
991                         iks_insert_attrib(session, "initiator", p->initiator ? p->us : p->them);
992                         iks_insert_attrib(session, "xmlns", "http://www.google.com/session");
993                         iks_insert_node(request, session);
994                         iks_send(client->connection->p, request);
995                         iks_delete(session);
996                         res = 0;
997                 }
998                 iks_delete(request);
999         }
1000         return res;
1001 }
1002
1003 static void gtalk_free_candidates(struct gtalk_candidate *candidate)
1004 {
1005         struct gtalk_candidate *last;
1006         while (candidate) {
1007                 last = candidate;
1008                 candidate = candidate->next;
1009                 free(last);
1010         }
1011 }
1012
1013 static void gtalk_free_pvt(struct gtalk *client, struct gtalk_pvt *p)
1014 {
1015         struct gtalk_pvt *cur, *prev = NULL;
1016         cur = client->p;
1017         while (cur) {
1018                 if (cur == p) {
1019                         if (prev)
1020                                 prev->next = p->next;
1021                         else
1022                                 client->p = p->next;
1023                         break;
1024                 }
1025                 prev = cur;
1026                 cur = cur->next;
1027         }
1028         if (p->ringrule)
1029                 iks_filter_remove_rule(p->parent->connection->f, p->ringrule);
1030         if (p->owner)
1031                 ast_log(LOG_WARNING, "Uh oh, there's an owner, this is going to be messy.\n");
1032         if (p->rtp)
1033                 ast_rtp_destroy(p->rtp);
1034         if (p->vrtp)
1035                 ast_rtp_destroy(p->vrtp);
1036         gtalk_free_candidates(p->theircandidates);
1037         free(p);
1038 }
1039
1040
1041 static int gtalk_newcall(struct gtalk *client, ikspak *pak)
1042 {
1043         struct gtalk_pvt *p, *tmp = client->p;
1044         struct ast_channel *chan;
1045         int res;
1046         iks *codec;
1047         char *from = NULL;
1048         /* Make sure our new call doesn't exist yet */
1049         from = iks_find_attrib(pak->x,"to");
1050         if(!from)
1051                 from = client->connection->jid->full;
1052         
1053         while (tmp) {
1054                 if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid)) {
1055                         ast_log(LOG_NOTICE, "Ignoring duplicate call setup on SID %s\n", tmp->sid);
1056                         gtalk_response(client, from, pak, "out-of-order", NULL);
1057                         return -1;
1058                 }
1059                 tmp = tmp->next;
1060         }
1061
1062         p = gtalk_alloc(client, from, pak->from->full, iks_find_attrib(pak->query, "id"));
1063         if (!p) {
1064                 ast_log(LOG_WARNING, "Unable to allocate gtalk structure!\n");
1065                 return -1;
1066         }
1067         chan = gtalk_new(client, p, AST_STATE_DOWN, pak->from->user);
1068         if (chan) {
1069                 ast_mutex_lock(&p->lock);
1070                 ast_copy_string(p->them, pak->from->full, sizeof(p->them));
1071                 if (iks_find_attrib(pak->query, "id")) {
1072                         ast_copy_string(p->sid, iks_find_attrib(pak->query, "id"),
1073                                                         sizeof(p->sid));
1074                 }
1075
1076                 codec = iks_child(iks_child(iks_child(pak->x)));
1077                 while (codec) {
1078                         ast_rtp_set_m_type(p->rtp, atoi(iks_find_attrib(codec, "id")));
1079                         ast_rtp_set_rtpmap_type(p->rtp, atoi(iks_find_attrib(codec, "id")), "audio",
1080                                                 iks_find_attrib(codec, "name"), 0);
1081                         codec = iks_next(codec);
1082                 }
1083                 
1084                 ast_mutex_unlock(&p->lock);
1085                 ast_setstate(chan, AST_STATE_RING);
1086                 res = ast_pbx_start(chan);
1087
1088                 switch (res) {
1089                 case AST_PBX_FAILED:
1090                         ast_log(LOG_WARNING, "Failed to start PBX :(\n");
1091                         gtalk_response(client, from, pak, "service-unavailable", NULL);
1092                         break;
1093                 case AST_PBX_CALL_LIMIT:
1094                         ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
1095                         gtalk_response(client, from, pak, "service-unavailable", NULL);
1096                         break;
1097                 case AST_PBX_SUCCESS:
1098                         gtalk_response(client, from, pak, NULL, NULL);
1099                         gtalk_invite_response(p, p->them, p->us,p->sid, 0);
1100                         gtalk_create_candidates(client, p, p->sid, p->them, p->us);
1101                         /* nothing to do */
1102                         break;
1103                 }
1104         } else {
1105                 gtalk_free_pvt(client, p);
1106         }
1107         return 1;
1108 }
1109
1110 static int gtalk_update_stun(struct gtalk *client, struct gtalk_pvt *p)
1111 {
1112         struct gtalk_candidate *tmp;
1113         struct hostent *hp;
1114         struct ast_hostent ahp;
1115         struct sockaddr_in sin;
1116
1117         if (time(NULL) == p->laststun)
1118                 return 0;
1119
1120         tmp = p->theircandidates;
1121         p->laststun = time(NULL);
1122         while (tmp) {
1123                 char username[256];
1124                 hp = ast_gethostbyname(tmp->ip, &ahp);
1125                 sin.sin_family = AF_INET;
1126                 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
1127                 sin.sin_port = htons(tmp->port);
1128                 snprintf(username, sizeof(username), "%s%s", tmp->username,
1129                                  p->ourcandidates->username);
1130
1131                 ast_rtp_stun_request(p->rtp, &sin, username);
1132                 tmp = tmp->next;
1133         }
1134         return 1;
1135 }
1136
1137 static int gtalk_add_candidate(struct gtalk *client, ikspak *pak)
1138 {
1139         struct gtalk_pvt *p = NULL, *tmp = NULL;
1140         struct aji_client *c = client->connection;
1141         struct gtalk_candidate *newcandidate = NULL;
1142         iks *traversenodes = NULL, *receipt = NULL;
1143         char *from;
1144
1145         from = iks_find_attrib(pak->x,"to");
1146         if(!from)
1147                 from = c->jid->full;
1148
1149         newcandidate = ast_calloc(1, sizeof(*newcandidate));
1150         if (!newcandidate)
1151                 return 0;
1152         for (tmp = client->p; tmp; tmp = tmp->next) {
1153                 if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid)) {
1154                         p = tmp;
1155                         break;
1156                 }
1157         }
1158
1159         if (!p)
1160                 return -1;
1161
1162         traversenodes = pak->query;
1163         while(traversenodes) {
1164                 if(!strcasecmp(iks_name(traversenodes), "session")) {
1165                         traversenodes = iks_child(traversenodes);
1166                         continue;
1167                 }
1168                 if(!strcasecmp(iks_name(traversenodes), "transport")) {
1169                         traversenodes = iks_child(traversenodes);
1170                         continue;
1171                 }
1172                 if(!strcasecmp(iks_name(traversenodes), "candidate")) {
1173                         newcandidate = ast_calloc(1, sizeof(*newcandidate));
1174                         if (!newcandidate)
1175                                 return 0;
1176                         ast_copy_string(newcandidate->name, iks_find_attrib(traversenodes, "name"),
1177                                                         sizeof(newcandidate->name));
1178                         ast_copy_string(newcandidate->ip, iks_find_attrib(traversenodes, "address"),
1179                                                         sizeof(newcandidate->ip));
1180                         newcandidate->port = atoi(iks_find_attrib(traversenodes, "port"));
1181                         ast_copy_string(newcandidate->username, iks_find_attrib(traversenodes, "username"),
1182                                                         sizeof(newcandidate->username));
1183                         ast_copy_string(newcandidate->password, iks_find_attrib(traversenodes, "password"),
1184                                                         sizeof(newcandidate->password));
1185                         newcandidate->preference = atof(iks_find_attrib(traversenodes, "preference"));
1186                         if (!strcasecmp(iks_find_attrib(traversenodes, "protocol"), "udp"))
1187                                 newcandidate->protocol = AJI_PROTOCOL_UDP;
1188                         if (!strcasecmp(iks_find_attrib(traversenodes, "protocol"), "ssltcp"))
1189                                 newcandidate->protocol = AJI_PROTOCOL_SSLTCP;
1190                 
1191                         if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "stun"))
1192                                 newcandidate->type = AJI_CONNECT_STUN;
1193                         if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "local"))
1194                                 newcandidate->type = AJI_CONNECT_LOCAL;
1195                         if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "relay"))
1196                                 newcandidate->type = AJI_CONNECT_RELAY;
1197                         ast_copy_string(newcandidate->network, iks_find_attrib(traversenodes, "network"),
1198                                                         sizeof(newcandidate->network));
1199                         newcandidate->generation = atoi(iks_find_attrib(traversenodes, "generation"));
1200                         newcandidate->next = NULL;
1201                 
1202                         newcandidate->next = p->theircandidates;
1203                         p->theircandidates = newcandidate;
1204                         p->laststun = 0;
1205                         gtalk_update_stun(p->parent, p);
1206                         newcandidate = NULL;
1207                 }
1208                 traversenodes = iks_next(traversenodes);
1209         }
1210         
1211         receipt = iks_new("iq");
1212         iks_insert_attrib(receipt, "type", "result");
1213         iks_insert_attrib(receipt, "from", from);
1214         iks_insert_attrib(receipt, "to", iks_find_attrib(pak->x, "from"));
1215         iks_insert_attrib(receipt, "id", iks_find_attrib(pak->x, "id"));
1216         iks_send(c->p, receipt);
1217         iks_delete(receipt);
1218
1219         return 1;
1220 }
1221
1222 static struct ast_frame *gtalk_rtp_read(struct ast_channel *ast, struct gtalk_pvt *p)
1223 {
1224         struct ast_frame *f;
1225
1226         if (!p->rtp)
1227                 return &ast_null_frame;
1228         f = ast_rtp_read(p->rtp);
1229         gtalk_update_stun(p->parent, p);
1230         if (p->owner) {
1231                 /* We already hold the channel lock */
1232                 if (f->frametype == AST_FRAME_VOICE) {
1233                         if (f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
1234                                 if (option_debug)
1235                                         ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
1236                                 p->owner->nativeformats =
1237                                         (p->owner->nativeformats & AST_FORMAT_VIDEO_MASK) | f->subclass;
1238                                 ast_set_read_format(p->owner, p->owner->readformat);
1239                                 ast_set_write_format(p->owner, p->owner->writeformat);
1240                         }
1241 /*                      if ((ast_test_flag(p, SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
1242                                 f = ast_dsp_process(p->owner, p->vad, f);
1243                                 if (option_debug && f && (f->frametype == AST_FRAME_DTMF))
1244                                         if (option_debug)
1245                                                 ast_log(LOG_DEBUG, "* Detected inband DTMF '%c'\n", f->subclass);
1246                         } */
1247                 }
1248         }
1249         return f;
1250 }
1251
1252 static struct ast_frame *gtalk_read(struct ast_channel *ast)
1253 {
1254         struct ast_frame *fr;
1255         struct gtalk_pvt *p = ast->tech_pvt;
1256
1257         ast_mutex_lock(&p->lock);
1258         fr = gtalk_rtp_read(ast, p);
1259         ast_mutex_unlock(&p->lock);
1260         return fr;
1261 }
1262
1263 /*! \brief Send frame to media channel (rtp) */
1264 static int gtalk_write(struct ast_channel *ast, struct ast_frame *frame)
1265 {
1266         struct gtalk_pvt *p = ast->tech_pvt;
1267         int res = 0;
1268
1269         switch (frame->frametype) {
1270         case AST_FRAME_VOICE:
1271                 if (!(frame->subclass & ast->nativeformats)) {
1272                         ast_log(LOG_WARNING,
1273                                         "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
1274                                         frame->subclass, ast->nativeformats, ast->readformat,
1275                                         ast->writeformat);
1276                         return 0;
1277                 }
1278                 if (p) {
1279                         ast_mutex_lock(&p->lock);
1280                         if (p->rtp) {
1281                                 res = ast_rtp_write(p->rtp, frame);
1282                         }
1283                         ast_mutex_unlock(&p->lock);
1284                 }
1285                 break;
1286         case AST_FRAME_VIDEO:
1287                 if (p) {
1288                         ast_mutex_lock(&p->lock);
1289                         if (p->vrtp) {
1290                                 res = ast_rtp_write(p->vrtp, frame);
1291                         }
1292                         ast_mutex_unlock(&p->lock);
1293                 }
1294                 break;
1295         case AST_FRAME_IMAGE:
1296                 return 0;
1297                 break;
1298         default:
1299                 ast_log(LOG_WARNING, "Can't send %d type frames with Gtalk write\n",
1300                                 frame->frametype);
1301                 return 0;
1302         }
1303
1304         return res;
1305 }
1306
1307 static int gtalk_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1308 {
1309         struct gtalk_pvt *p = newchan->tech_pvt;
1310         ast_mutex_lock(&p->lock);
1311
1312         if ((p->owner != oldchan)) {
1313                 ast_mutex_unlock(&p->lock);
1314                 return -1;
1315         }
1316         if (p->owner == oldchan)
1317                 p->owner = newchan;
1318         ast_mutex_unlock(&p->lock);
1319         return 0;
1320 }
1321
1322 static int gtalk_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
1323 {
1324         int res = 0;
1325
1326         switch (condition) {
1327         case AST_CONTROL_HOLD:
1328                 ast_moh_start(ast, data, NULL);
1329                 break;
1330         case AST_CONTROL_UNHOLD:
1331                 ast_moh_stop(ast);
1332                 break;
1333         default:
1334                 ast_log(LOG_NOTICE, "Don't know how to indicate condition '%d'\n", condition);
1335                 res = -1;
1336         }
1337
1338         return res;
1339 }
1340
1341 static int gtalk_digit(struct ast_channel *ast, char digit)
1342 {
1343         struct gtalk_pvt *p = ast->tech_pvt;
1344         struct gtalk *client = p->parent;
1345         iks *iq, *gtalk, *dtmf;
1346         char buffer[2] = {digit, '\0'};
1347         iq = iks_new("iq");
1348         gtalk = iks_new("gtalk");
1349         dtmf = iks_new("dtmf");
1350         if(!iq || !gtalk || !dtmf) {
1351                 if(iq)
1352                         iks_delete(iq);
1353                 if(gtalk)
1354                         iks_delete(gtalk);
1355                 if(dtmf)
1356                         iks_delete(dtmf);
1357                 ast_log(LOG_ERROR, "Did not send dtmf do to memory issue\n");
1358                 return -1;
1359         }
1360
1361         iks_insert_attrib(iq, "type", "set");
1362         iks_insert_attrib(iq, "to", p->them);
1363         iks_insert_attrib(iq, "from", p->us);
1364         iks_insert_attrib(iq, "id", client->connection->mid);
1365         ast_aji_increment_mid(client->connection->mid);
1366         iks_insert_attrib(gtalk, "xmlns", "http://jabber.org/protocol/gtalk");
1367         iks_insert_attrib(gtalk, "action", "content-info");
1368         iks_insert_attrib(gtalk, "initiator", p->initiator ? p->us: p->them);
1369         iks_insert_attrib(gtalk, "sid", p->sid);
1370         iks_insert_attrib(dtmf, "xmlns", "http://jabber.org/protocol/gtalk/info/dtmf");
1371         iks_insert_attrib(dtmf, "code", buffer);
1372         iks_insert_node(iq, gtalk);
1373         iks_insert_node(gtalk, dtmf);
1374
1375         ast_mutex_lock(&p->lock);
1376         if(ast->dtmff.frametype == AST_FRAME_DTMF) {
1377                 ast_verbose("Sending 250ms dtmf!\n");
1378         } else if (ast->dtmff.frametype == AST_FRAME_DTMF_BEGIN) {
1379                 iks_insert_attrib(dtmf, "action", "button-down");
1380         } else if (ast->dtmff.frametype == AST_FRAME_DTMF_END) {
1381                 iks_insert_attrib(dtmf, "action", "button-up");
1382         }
1383         iks_send(client->connection->p, iq);
1384         iks_delete(iq);
1385         iks_delete(gtalk);
1386         iks_delete(dtmf);
1387         ast_mutex_unlock(&p->lock);
1388         return 0;
1389 }
1390
1391 static int gtalk_sendhtml(struct ast_channel *ast, int subclass, const char *data, int datalen)
1392 {
1393         ast_log(LOG_NOTICE, "XXX Implement gtalk sendhtml XXX\n");
1394
1395         return -1;
1396 }
1397
1398 /* Not in use right now.
1399 static int gtalk_auto_congest(void *nothing)
1400 {
1401         struct gtalk_pvt *p = nothing;
1402
1403         ast_mutex_lock(&p->lock);
1404         if (p->owner) {
1405                 if (!ast_channel_trylock(p->owner)) {
1406                         ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
1407                         ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
1408                         ast_channel_unlock(p->owner);
1409                 }
1410         }
1411         ast_mutex_unlock(&p->lock);
1412         return 0;
1413 }
1414 */
1415
1416 /*! \brief Initiate new call, part of PBX interface 
1417  *      dest is the dial string */
1418 static int gtalk_call(struct ast_channel *ast, char *dest, int timeout)
1419 {
1420         struct gtalk_pvt *p = ast->tech_pvt;
1421
1422         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
1423                 ast_log(LOG_WARNING, "gtalk_call called on %s, neither down nor reserved\n", ast->name);
1424                 return -1;
1425         }
1426
1427         ast_setstate(ast, AST_STATE_RING);
1428         p->jointcapability = p->capability;
1429         if (!p->ringrule) {
1430                 ast_copy_string(p->ring, p->parent->connection->mid, sizeof(p->ring));
1431                 p->ringrule = iks_filter_add_rule(p->parent->connection->f, gtalk_ringing_ack, p,
1432                                                         IKS_RULE_ID, p->ring, IKS_RULE_DONE);
1433         } else
1434                 ast_log(LOG_WARNING, "Whoa, already have a ring rule!\n");
1435
1436         gtalk_invite(p, p->them, p->us, p->sid, 1);
1437         gtalk_create_candidates(p->parent, p, p->sid, p->them, p->us);
1438
1439         return 0;
1440 }
1441
1442 /*! \brief Hangup a call through the gtalk proxy channel */
1443 static int gtalk_hangup(struct ast_channel *ast)
1444 {
1445         struct gtalk_pvt *p = ast->tech_pvt;
1446         struct gtalk *client;
1447
1448         ast_mutex_lock(&p->lock);
1449         client = p->parent;
1450         p->owner = NULL;
1451         ast->tech_pvt = NULL;
1452         if (!p->alreadygone)
1453                 gtalk_action(client, p, "terminate");
1454         ast_mutex_unlock(&p->lock);
1455
1456         gtalk_free_pvt(client, p);
1457         ast_mutex_lock(&usecnt_lock);
1458         usecnt--;
1459         ast_mutex_unlock(&usecnt_lock);
1460
1461         return 0;
1462 }
1463
1464 /*! \brief Part of PBX interface */
1465 static struct ast_channel *gtalk_request(const char *type, int format, void *data, int *cause)
1466 {
1467         struct gtalk_pvt *p = NULL;
1468         struct gtalk *client = NULL;
1469         char *sender = NULL, *to = NULL, *s = NULL;
1470         struct ast_channel *chan = NULL;
1471
1472         if (data) {
1473                 s = ast_strdupa((char *) data);
1474                 if (s) {
1475                         sender = strsep(&s, "/");
1476                         if (sender && (sender[0] != '\0'))
1477                                 to = strsep(&s, "/");
1478                         if (!to) {
1479                                 ast_log(LOG_ERROR, "Bad arguments in Gtalk Dialstring: %s\n", (char*) data);
1480                                 if (s)
1481                                         free(s);
1482                                 return NULL;
1483                         }
1484                 }
1485         }
1486         client = find_gtalk(to, sender);
1487         if (!client) {
1488                 ast_log(LOG_WARNING, "Could not find recipient.\n");
1489                 if (s)
1490                         free(s);
1491                 return NULL;
1492         }
1493         p = gtalk_alloc(client, strchr(sender, '@') ? sender : client->connection->jid->full, strchr(to, '@') ? to : client->user, NULL);
1494         if (p)
1495                 chan = gtalk_new(client, p, AST_STATE_DOWN, to);
1496
1497         return chan;
1498 }
1499
1500 /*! \brief CLI command "gtalk show channels" */
1501 static int gtalk_show_channels(int fd, int argc, char **argv)
1502 {
1503         if (argc != 3)
1504                 return RESULT_SHOWUSAGE;
1505         ast_mutex_lock(&gtalklock);
1506 //      if (!gtalk_list->p)
1507                 ast_cli(fd, "No gtalk channels in use\n");
1508         ast_mutex_unlock(&gtalklock);
1509         return RESULT_SUCCESS;
1510 }
1511
1512 /*! \brief CLI command "gtalk show channels" */
1513 static int gtalk_do_reload(int fd, int argc, char **argv)
1514 {
1515         ast_verbose("IT DOES WORK!\n");
1516         return RESULT_SUCCESS;
1517 }
1518 static int gtalk_parser(void *data, ikspak *pak)
1519 {
1520         struct gtalk *client = ASTOBJ_REF((struct gtalk *) data);
1521
1522         if (iks_find_with_attrib(pak->x, "session", "type", "initiate")) {
1523                 /* New call */
1524                 gtalk_newcall(client, pak);
1525         } else if (iks_find_with_attrib(pak->x, "session", "type", "candidates") || iks_find_with_attrib(pak->x, "session", "type", "transport-info") ) {
1526                 if (option_debug > 2)
1527                         ast_log(LOG_DEBUG, "About to add candidate!\n");
1528                 gtalk_add_candidate(client, pak);
1529                 if (option_debug > 2)
1530                         ast_log(LOG_DEBUG, "Candidate Added!\n");
1531         } else if (iks_find_with_attrib(pak->x, "session", "type", "accept")) {
1532                 gtalk_is_answered(client, pak);
1533         } else if (iks_find_with_attrib(pak->x, "session", "type", "content-info")) {
1534                 gtalk_handle_dtmf(client, pak);
1535         } else if (iks_find_with_attrib(pak->x, "session", "type", "terminate")) {
1536                 gtalk_hangup_farend(client, pak);
1537         } else if (iks_find_with_attrib(pak->x, "session", "type", "reject")) {
1538                 gtalk_hangup_farend(client, pak);
1539         }
1540         ASTOBJ_UNREF(client, gtalk_member_destroy);
1541         return IKS_FILTER_EAT;
1542 }
1543 /* Not using this anymore probably take out soon 
1544 static struct gtalk_candidate *gtalk_create_candidate(char *args)
1545 {
1546         char *name, *type, *preference, *protocol;
1547         struct gtalk_candidate *res;
1548         res = malloc(sizeof(struct gtalk_candidate));
1549         memset(res, 0, sizeof(struct gtalk_candidate));
1550         if (args)
1551                 name = args;
1552         if ((args = strchr(args, ','))) {
1553                 *args = '\0';
1554                 args++;
1555                 preference = args;
1556         }
1557         if ((args = strchr(args, ','))) {
1558                 *args = '\0';
1559                 args++;
1560                 protocol = args;
1561         }
1562         if ((args = strchr(args, ','))) {
1563                 *args = '\0';
1564                 args++;
1565                 type = args;
1566         }
1567         if (name)
1568                 ast_copy_string(res->name, name, sizeof(res->name));
1569         if (preference) {
1570                 res->preference = atof(preference);
1571         }
1572         if (protocol) {
1573                 if (!strcasecmp("udp", protocol))
1574                         res->protocol = AJI_PROTOCOL_UDP;
1575                 if (!strcasecmp("ssltcp", protocol))
1576                         res->protocol = AJI_PROTOCOL_SSLTCP;
1577         }
1578         if (type) {
1579                 if (!strcasecmp("stun", type))
1580                         res->type = AJI_CONNECT_STUN;
1581                 if (!strcasecmp("local", type))
1582                         res->type = AJI_CONNECT_LOCAL;
1583                 if (!strcasecmp("relay", type))
1584                         res->type = AJI_CONNECT_RELAY;
1585         }
1586
1587         return res;
1588 }
1589 */
1590
1591 static int gtalk_create_member(char *label, struct ast_variable *var, int allowguest,
1592                                                                 struct ast_codec_pref prefs, char *context,
1593                                                                 struct gtalk *member)
1594 {
1595         struct aji_client *client;
1596
1597         if (!member)
1598                 ast_log(LOG_WARNING, "Out of memory.\n");
1599
1600         ast_copy_string(member->name, label, sizeof(member->name));
1601         ast_copy_string(member->user, label, sizeof(member->user));
1602         ast_copy_string(member->context, context, sizeof(member->context));
1603         member->allowguest = allowguest;
1604         member->prefs = prefs;
1605         while (var) {
1606 #if 0
1607                 struct gtalk_candidate *candidate = NULL;
1608 #endif
1609                 if (!strcasecmp(var->name, "username"))
1610                         ast_copy_string(member->user, var->value, sizeof(member->user));
1611                 else if (!strcasecmp(var->name, "disallow"))
1612                         ast_parse_allow_disallow(&member->prefs, &member->capability, var->value, 0);
1613                 else if (!strcasecmp(var->name, "allow"))
1614                         ast_parse_allow_disallow(&member->prefs, &member->capability, var->value, 1);
1615                 else if (!strcasecmp(var->name, "context"))
1616                         ast_copy_string(member->context, var->value, sizeof(member->context));
1617 #if 0
1618                 else if (!strcasecmp(var->name, "candidate")) {
1619                         candidate = gtalk_create_candidate(var->value);
1620                         if (candidate) {
1621                                 candidate->next = member->ourcandidates;
1622                                 member->ourcandidates = candidate;
1623                         }
1624                 }
1625 #endif
1626                 else if (!strcasecmp(var->name, "connection")) {
1627                         if ((client = ast_aji_get_client(var->value))) {
1628                                 member->connection = client;
1629                                 iks_filter_add_rule(client->f, gtalk_parser, member, IKS_RULE_TYPE,
1630                                                                         IKS_PAK_IQ, IKS_RULE_FROM_PARTIAL, member->user,
1631                                                                         IKS_RULE_NS, "http://www.google.com/session",
1632                                                                         IKS_RULE_DONE);
1633                         } else {
1634                                 ast_log(LOG_ERROR, "connection referenced not found!\n");
1635                                 return 0;
1636                         }
1637                 }
1638                 var = var->next;
1639         }
1640         if (member->connection && member->user)
1641                 member->buddy = ASTOBJ_CONTAINER_FIND(&member->connection->buddies, member->user);
1642         else {
1643                 ast_log(LOG_ERROR, "No Connection or Username!\n");
1644         }
1645         return 1;
1646 }
1647
1648 static int gtalk_load_config(void)
1649 {
1650         char *cat = NULL;
1651         struct ast_config *cfg = NULL;
1652         char context[100];
1653         int allowguest = 1;
1654         struct ast_variable *var;
1655         struct gtalk *member;
1656         struct ast_codec_pref prefs;
1657         struct aji_client_container *clients;
1658         struct gtalk_candidate *global_candidates = NULL;
1659
1660         cfg = ast_config_load(GOOGLE_CONFIG);
1661         if (!cfg)
1662                 return 0;
1663
1664         /* Copy the default jb config over global_jbconf */
1665         memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
1666
1667         cat = ast_category_browse(cfg, NULL);
1668         for (var = ast_variable_browse(cfg, "general"); var; var = var->next) {
1669                 /* handle jb conf */
1670                 if (!ast_jb_read_conf(&global_jbconf, var->name, var->value))
1671                         continue;
1672
1673                 if (!strcasecmp(var->name, "allowguest"))
1674                         allowguest =
1675                                 (ast_true(ast_variable_retrieve(cfg, "general", "allowguest"))) ? 1 : 0;
1676                 else if (!strcasecmp(var->name, "disallow"))
1677                         ast_parse_allow_disallow(&prefs, &global_capability, var->value, 0);
1678                 else if (!strcasecmp(var->name, "allow"))
1679                         ast_parse_allow_disallow(&prefs, &global_capability, var->value, 1);
1680                 else if (!strcasecmp(var->name, "context"))
1681                         ast_copy_string(context, var->value, sizeof(context));
1682 /*  Idea to allow for custom candidates  */
1683 /*
1684                 else if (!strcasecmp(var->name, "candidate")) {
1685                         candidate = gtalk_create_candidate(var->value);
1686                         if (candidate) {
1687                                 candidate->next = global_candidates;
1688                                 global_candidates = candidate;
1689                         }
1690                 }
1691 */
1692         }
1693         while (cat) {
1694                 if (strcasecmp(cat, "general")) {
1695                         var = ast_variable_browse(cfg, cat);
1696                         member = (struct gtalk *) malloc(sizeof(struct gtalk));
1697                         memset(member, 0, sizeof(struct gtalk));
1698                         ASTOBJ_INIT(member);
1699                         ASTOBJ_WRLOCK(member);
1700                         if (!strcasecmp(cat, "guest")) {
1701                                 ast_copy_string(member->name, "guest", sizeof(member->name));
1702                                 ast_copy_string(member->user, "guest", sizeof(member->user));
1703                                 ast_copy_string(member->context, context, sizeof(member->context));
1704                                 member->allowguest = allowguest;
1705                                 member->prefs = prefs;
1706                                 while (var) {
1707                                         if (!strcasecmp(var->name, "disallow"))
1708                                                 ast_parse_allow_disallow(&member->prefs, &member->capability,
1709                                                                                                  var->value, 0);
1710                                         else if (!strcasecmp(var->name, "allow"))
1711                                                 ast_parse_allow_disallow(&member->prefs, &member->capability,
1712                                                                                                  var->value, 1);
1713                                         else if (!strcasecmp(var->name, "context"))
1714                                                 ast_copy_string(member->context, var->value,
1715                                                                                 sizeof(member->context));
1716 /*  Idea to allow for custom candidates  */
1717 /*
1718                                         else if (!strcasecmp(var->name, "candidate")) {
1719                                                 candidate = gtalk_create_candidate(var->value);
1720                                                 if (candidate) {
1721                                                         candidate->next = member->ourcandidates;
1722                                                         member->ourcandidates = candidate;
1723                                                 }
1724                                         }
1725 */
1726                                         var = var->next;
1727                                 }
1728                                 ASTOBJ_UNLOCK(member);
1729                                 clients = ast_aji_get_clients();
1730                                 if (clients) {
1731                                         ASTOBJ_CONTAINER_TRAVERSE(clients, 1, {
1732                                                 ASTOBJ_WRLOCK(iterator);
1733                                                 ASTOBJ_WRLOCK(member);
1734                                                 member->connection = iterator;
1735                                                 iks_filter_add_rule(iterator->f, gtalk_parser, member, IKS_RULE_TYPE, IKS_PAK_IQ, IKS_RULE_NS,
1736                                                                                 "http://www.google.com/session", IKS_RULE_DONE);
1737                                                 ASTOBJ_UNLOCK(member);
1738                                                 ASTOBJ_CONTAINER_LINK(&gtalk_list, member);
1739                                                 ASTOBJ_UNLOCK(iterator);
1740                                         });
1741                                 } else {
1742                                         ASTOBJ_UNLOCK(member);
1743                                         ASTOBJ_UNREF(member, gtalk_member_destroy);
1744                                 }
1745                         } else {
1746                                 ASTOBJ_UNLOCK(member);
1747                                 if (gtalk_create_member(cat, var, allowguest, prefs, context, member))
1748                                         ASTOBJ_CONTAINER_LINK(&gtalk_list, member);
1749                                 ASTOBJ_UNREF(member, gtalk_member_destroy);
1750                         }
1751                 }
1752                 cat = ast_category_browse(cfg, cat);
1753         }
1754         gtalk_free_candidates(global_candidates);
1755         return 1;
1756 }
1757
1758 /*! \brief Load module into PBX, register channel */
1759 static int load_module(void)
1760 {
1761         ASTOBJ_CONTAINER_INIT(&gtalk_list);
1762         if (!gtalk_load_config()) {
1763                 ast_log(LOG_ERROR, "Unable to read config file %s. Not loading module.\n", GOOGLE_CONFIG);
1764                 return 0;
1765         }
1766
1767         sched = sched_context_create();
1768         if (!sched) 
1769                 ast_log(LOG_WARNING, "Unable to create schedule context\n");
1770
1771         io = io_context_create();
1772         if (!io) 
1773                 ast_log(LOG_WARNING, "Unable to create I/O context\n");
1774
1775         if (ast_find_ourip(&__ourip, bindaddr)) {
1776                 ast_log(LOG_WARNING, "Unable to get own IP address, Gtalk disabled\n");
1777                 return 0;
1778         }
1779
1780         ast_rtp_proto_register(&gtalk_rtp);
1781         ast_cli_register_multiple(gtalk_cli, sizeof(gtalk_cli) / sizeof(gtalk_cli[0]));
1782
1783         /* Make sure we can register our channel type */
1784         if (ast_channel_register(&gtalk_tech)) {
1785                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
1786                 return -1;
1787         }
1788         return 0;
1789 }
1790
1791 /*! \brief Reload module */
1792 static int reload(void)
1793 {
1794         return 0;
1795 }
1796
1797 /*! \brief Unload the gtalk channel from Asterisk */
1798 static int unload_module(void)
1799 {
1800         struct gtalk_pvt *privates = NULL;
1801         ast_cli_unregister_multiple(gtalk_cli, sizeof(gtalk_cli) / sizeof(gtalk_cli[0]));
1802         /* First, take us out of the channel loop */
1803         ast_channel_unregister(&gtalk_tech);
1804         ast_rtp_proto_unregister(&gtalk_rtp);
1805
1806         if (!ast_mutex_lock(&gtalklock)) {
1807                 /* Hangup all interfaces if they have an owner */
1808                 ASTOBJ_CONTAINER_TRAVERSE(&gtalk_list, 1, {
1809                         ASTOBJ_WRLOCK(iterator);
1810                         privates = iterator->p;
1811                         while(privates) {
1812                                 if (privates->owner)
1813                                         ast_softhangup(privates->owner, AST_SOFTHANGUP_APPUNLOAD);
1814                                 privates = privates->next;
1815                         }
1816                         iterator->p = NULL;
1817                         ASTOBJ_UNLOCK(iterator);
1818                 });
1819                 ast_mutex_unlock(&gtalklock);
1820         } else {
1821                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
1822                 return -1;
1823         }
1824         ASTOBJ_CONTAINER_DESTROYALL(&gtalk_list, gtalk_member_destroy);
1825         ASTOBJ_CONTAINER_DESTROY(&gtalk_list);
1826         return 0;
1827 }
1828
1829 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Gtalk Channel Driver",
1830                 .load = load_module,
1831                 .unload = unload_module,
1832                 .reload = reload,
1833                );