Constify a bunch of usage strings for CLI commands.
[asterisk/asterisk.git] / channels / chan_gtalk.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2005, Digium, Inc.
5  *
6  * Matt O'Gorman <mogorman@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \author Matt O'Gorman <mogorman@digium.com>
22  *
23  * \brief Gtalk Channel Driver, until google/libjingle works with jingle spec
24  * 
25  * \ingroup channel_drivers
26  */
27
28 /*** MODULEINFO
29         <depend>iksemel</depend>
30  ***/
31
32 #include "asterisk.h"
33
34 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
35
36 #include <stdlib.h>
37 #include <stdio.h>
38 #include <string.h>
39 #include <unistd.h>
40 #include <sys/socket.h>
41 #include <errno.h>
42 #include <stdlib.h>
43 #include <fcntl.h>
44 #include <netdb.h>
45 #include <netinet/in.h>
46 #include <arpa/inet.h>
47 #include <sys/signal.h>
48 #include <iksemel.h>
49
50 #include "asterisk/lock.h"
51 #include "asterisk/channel.h"
52 #include "asterisk/config.h"
53 #include "asterisk/logger.h"
54 #include "asterisk/module.h"
55 #include "asterisk/pbx.h"
56 #include "asterisk/options.h"
57 #include "asterisk/lock.h"
58 #include "asterisk/sched.h"
59 #include "asterisk/io.h"
60 #include "asterisk/rtp.h"
61 #include "asterisk/acl.h"
62 #include "asterisk/callerid.h"
63 #include "asterisk/file.h"
64 #include "asterisk/cli.h"
65 #include "asterisk/app.h"
66 #include "asterisk/musiconhold.h"
67 #include "asterisk/manager.h"
68 #include "asterisk/stringfields.h"
69 #include "asterisk/utils.h"
70 #include "asterisk/causes.h"
71 #include "asterisk/astobj.h"
72 #include "asterisk/abstract_jb.h"
73 #include "asterisk/jabber.h"
74
75 #define GOOGLE_CONFIG "gtalk.conf"
76
77 #define GOOGLE_NS "http://www.google.com/session"
78
79
80 /*! Global jitterbuffer configuration - by default, jb is disabled */
81 static struct ast_jb_conf default_jbconf =
82 {
83         .flags = 0,
84         .max_size = -1,
85         .resync_threshold = -1,
86         .impl = ""
87 };
88 static struct ast_jb_conf global_jbconf;
89
90 enum gtalk_protocol {
91         AJI_PROTOCOL_UDP = 1,
92         AJI_PROTOCOL_SSLTCP = 2,
93 };
94
95 enum gtalk_connect_type {
96         AJI_CONNECT_STUN = 1,
97         AJI_CONNECT_LOCAL = 2,
98         AJI_CONNECT_RELAY = 3,
99 };
100
101 struct gtalk_pvt {
102         ast_mutex_t lock;                /*!< Channel private lock */
103         time_t laststun;
104         struct gtalk *parent;            /*!< Parent client */
105         char sid[100];
106         char us[100];
107         char them[100];
108         char ring[10];                   /*!< Message ID of ring */
109         iksrule *ringrule;               /*!< Rule for matching RING request */
110         int initiator;                   /*!< If we're the initiator */
111         int alreadygone;
112         int capability;
113         struct ast_codec_pref prefs;
114         struct gtalk_candidate *theircandidates;
115         struct gtalk_candidate *ourcandidates;
116         char cid_num[80];                /*!< Caller ID num */
117         char cid_name[80];               /*!< Caller ID name */
118         char exten[80];                  /*!< Called extension */
119         struct ast_channel *owner;       /*!< Master Channel */
120         struct ast_rtp *rtp;             /*!< RTP audio session */
121         struct ast_rtp *vrtp;            /*!< RTP video session */
122         int jointcapability;             /*!< Supported capability at both ends (codecs ) */
123         int peercapability;
124         struct gtalk_pvt *next; /* Next entity */
125 };
126
127 struct gtalk_candidate {
128         char name[100];
129         enum gtalk_protocol protocol;
130         double preference;
131         char username[100];
132         char password[100];
133         enum gtalk_connect_type type;
134         char network[6];
135         int generation;
136         char ip[16];
137         int port;
138         int receipt;
139         struct gtalk_candidate *next;
140 };
141
142 struct gtalk {
143         ASTOBJ_COMPONENTS(struct gtalk);
144         struct aji_client *connection;
145         struct aji_buddy *buddy;
146         struct gtalk_pvt *p;
147         struct ast_codec_pref prefs;
148         int amaflags;                   /*!< AMA Flags */
149         char user[100];
150         char context[100];
151         char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */
152         int capability;
153         ast_group_t callgroup;  /*!< Call group */
154         ast_group_t pickupgroup;        /*!< Pickup group */
155         int callingpres;                /*!< Calling presentation */
156         int allowguest;
157         char language[MAX_LANGUAGE];    /*!<  Default language for prompts */
158         char musicclass[MAX_MUSICCLASS];        /*!<  Music on Hold class */
159 };
160
161 struct gtalk_container {
162         ASTOBJ_CONTAINER_COMPONENTS(struct gtalk);
163 };
164
165 static const char desc[] = "Gtalk Channel";
166
167 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
168
169 AST_MUTEX_DEFINE_STATIC(gtalklock); /*!< Protect the interface list (of gtalk_pvt's) */
170
171 /* Forward declarations */
172 static struct ast_channel *gtalk_request(const char *type, int format, void *data, int *cause);
173 static int gtalk_digit(struct ast_channel *ast, char digit);
174 static int gtalk_call(struct ast_channel *ast, char *dest, int timeout);
175 static int gtalk_hangup(struct ast_channel *ast);
176 static int gtalk_answer(struct ast_channel *ast);
177 static int gtalk_newcall(struct gtalk *client, ikspak *pak);
178 static struct ast_frame *gtalk_read(struct ast_channel *ast);
179 static int gtalk_write(struct ast_channel *ast, struct ast_frame *f);
180 static int gtalk_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
181 static int gtalk_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
182 static int gtalk_sendhtml(struct ast_channel *ast, int subclass, const char *data, int datalen);
183 static struct gtalk_pvt *gtalk_alloc(struct gtalk *client, const char *us, const char *them, const char *sid);
184 static int gtalk_do_reload(int fd, int argc, char **argv);
185 static int gtalk_show_channels(int fd, int argc, char **argv);
186 /*----- RTP interface functions */
187 static int gtalk_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp,
188                                                            struct ast_rtp *vrtp, int codecs, int nat_active);
189 static enum ast_rtp_get_result gtalk_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
190 static int gtalk_get_codec(struct ast_channel *chan);
191
192 /*! \brief PBX interface structure for channel registration */
193 static const struct ast_channel_tech gtalk_tech = {
194         .type = "Gtalk",
195         .description = "Gtalk Channel Driver",
196         .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
197         .requester = gtalk_request,
198         .send_digit_begin = gtalk_digit,
199         .send_digit_end = gtalk_digit,
200         .bridge = ast_rtp_bridge,
201         .call = gtalk_call,
202         .hangup = gtalk_hangup,
203         .answer = gtalk_answer,
204         .read = gtalk_read,
205         .write = gtalk_write,
206         .exception = gtalk_read,
207         .indicate = gtalk_indicate,
208         .fixup = gtalk_fixup,
209         .send_html = gtalk_sendhtml,
210         .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER
211 };
212
213 static struct sockaddr_in bindaddr = { 0, };    /*!< The address we bind to */
214
215 static struct sched_context *sched;     /*!< The scheduling context */
216 static struct io_context *io;   /*!< The IO context */
217 static struct in_addr __ourip;
218
219
220 /*! \brief RTP driver interface */
221 static struct ast_rtp_protocol gtalk_rtp = {
222         type: "Gtalk",
223         get_rtp_info: gtalk_get_rtp_peer,
224         set_rtp_peer: gtalk_set_rtp_peer,
225         get_codec: gtalk_get_codec,
226 };
227
228 static const char debug_usage[] = 
229 "Usage: gtalk show channels\n" 
230 "       Shows current state of the Gtalk channels.\n";
231
232 static const char reload_usage[] = 
233 "Usage: gtalk reload\n" 
234 "       Reload gtalk channel driver.\n";
235
236
237 static struct ast_cli_entry gtalk_cli[] = {
238         {{ "gtalk", "reload", NULL}, gtalk_do_reload, "Enable Jabber debugging", reload_usage },
239         {{ "gtalk", "show", "channels", NULL}, gtalk_show_channels, "Show GoogleTalk Channels", debug_usage },
240  };
241
242
243
244 static char externip[16];
245
246 static struct gtalk_container gtalk_list;
247
248 static void gtalk_member_destroy(struct gtalk *obj)
249 {
250         free(obj);
251 }
252
253 static struct gtalk *find_gtalk(char *name, char *connection)
254 {
255         struct gtalk *gtalk = NULL;
256         char *domain = NULL , *s = NULL;
257         if(strchr(connection, '@')) {
258                 s = ast_strdupa((char *) connection);
259                 domain = strsep(&s, "@");
260                 ast_verbose("OOOOH domain = %s\n", domain);
261                 free(s);
262         }
263         gtalk = ASTOBJ_CONTAINER_FIND(&gtalk_list, name);
264         if (!gtalk && strchr(name, '@'))
265                 gtalk = ASTOBJ_CONTAINER_FIND_FULL(&gtalk_list, name, user,,, strcasecmp);
266
267         if (!gtalk) {                           /* guest call */
268                 ASTOBJ_CONTAINER_TRAVERSE(&gtalk_list, 1, {
269                         ASTOBJ_WRLOCK(iterator);
270                         if (!strcasecmp(iterator->name, "guest")) {
271                                 if (!strcasecmp(iterator->connection->jid->partial, connection)) {
272                                         gtalk = iterator;
273                                         break;
274                                 } else if (!strcasecmp(iterator->connection->name, connection)) {
275                                         gtalk = iterator;
276                                         break;
277                                 } else if (iterator->connection->component && !strcasecmp(iterator->connection->user,domain)) {
278                                         gtalk = iterator;
279                                         break;
280                                 }
281                         }
282                         ASTOBJ_UNLOCK(iterator);
283                 });
284
285         }
286         return gtalk;
287 }
288
289
290 static int add_codec_to_answer(const struct gtalk_pvt *p, int codec, iks *dcodecs)
291 {
292         char *format = ast_getformatname(codec);
293
294         if (!strcasecmp("ulaw", format)) {
295                 iks *payload_eg711u, *payload_pcmu;
296                 payload_pcmu = iks_new("payload-type");
297                 payload_eg711u = iks_new("payload-type");
298         
299                 if(!payload_eg711u || !payload_pcmu) {
300                         if(payload_pcmu)
301                                 iks_delete(payload_pcmu);
302                         if(payload_eg711u)
303                                 iks_delete(payload_eg711u);
304                         ast_log(LOG_WARNING,"Failed to allocate iks node");
305                         return -1;
306                 }
307                 iks_insert_attrib(payload_pcmu, "id", "0");
308                 iks_insert_attrib(payload_pcmu, "name", "PCMU");
309                 iks_insert_attrib(payload_pcmu, "clockrate","8000");
310                 iks_insert_attrib(payload_pcmu, "bitrate","64000");
311                 iks_insert_attrib(payload_eg711u, "id", "100");
312                 iks_insert_attrib(payload_eg711u, "name", "EG711U");
313                 iks_insert_attrib(payload_eg711u, "clockrate","8000");
314                 iks_insert_attrib(payload_eg711u, "bitrate","64000");
315                 iks_insert_node(dcodecs, payload_pcmu);
316                 iks_insert_node(dcodecs, payload_eg711u);
317         }
318         if (!strcasecmp("alaw", format)) {
319                 iks *payload_eg711a, *payload_pcma;
320                 payload_pcma = iks_new("payload-type");
321                 payload_eg711a = iks_new("payload-type");
322                 if(!payload_eg711a || !payload_pcma) {
323                         if(payload_eg711a)
324                                 iks_delete(payload_eg711a);
325                         if(payload_pcma)
326                                 iks_delete(payload_pcma);
327                         ast_log(LOG_WARNING,"Failed to allocate iks node");
328                         return -1;
329                 }
330                 iks_insert_attrib(payload_pcma, "id", "8");
331                 iks_insert_attrib(payload_pcma, "name", "PCMA");
332                 iks_insert_attrib(payload_pcma, "clockrate","8000");
333                 iks_insert_attrib(payload_pcma, "bitrate","64000");
334                 payload_eg711a = iks_new("payload-type");
335                 iks_insert_attrib(payload_eg711a, "id", "101");
336                 iks_insert_attrib(payload_eg711a, "name", "EG711A");
337                 iks_insert_attrib(payload_eg711a, "clockrate","8000");
338                 iks_insert_attrib(payload_eg711a, "bitrate","64000");
339                 iks_insert_node(dcodecs, payload_pcma);
340                 iks_insert_node(dcodecs, payload_eg711a);
341         }
342         if (!strcasecmp("ilbc", format)) {
343                 iks *payload_ilbc = iks_new("payload-type");
344                 if(!payload_ilbc) {
345                         ast_log(LOG_WARNING,"Failed to allocate iks node");
346                         return -1;
347                 }
348                 iks_insert_attrib(payload_ilbc, "id", "102");
349                 iks_insert_attrib(payload_ilbc, "name", "iLBC");
350                 iks_insert_attrib(payload_ilbc, "clockrate","8000");
351                 iks_insert_attrib(payload_ilbc, "bitrate","13300");
352                 iks_insert_node(dcodecs, payload_ilbc);
353         }
354         if (!strcasecmp("g723", format)) {
355                 iks *payload_g723 = iks_new("payload-type");
356                 if(!payload_g723) {
357                         ast_log(LOG_WARNING,"Failed to allocate iks node");
358                         return -1;
359                 }
360                 iks_insert_attrib(payload_g723, "id", "4");
361                 iks_insert_attrib(payload_g723, "name", "G723");
362                 iks_insert_attrib(payload_g723, "clockrate","8000");
363                 iks_insert_attrib(payload_g723, "bitrate","6300");
364                 iks_insert_node(dcodecs, payload_g723);
365         }
366         if (!strcasecmp("speex", format)) {
367                 iks *payload_speex = iks_new("payload-type");
368                 if(!payload_speex) {
369                         ast_log(LOG_WARNING,"Failed to allocate iks node");
370                         return -1;
371                 }
372                 iks_insert_attrib(payload_speex, "id", "98");
373                 iks_insert_attrib(payload_speex, "name", "speex");
374                 iks_insert_attrib(payload_speex, "clockrate","8000");
375                 iks_insert_attrib(payload_speex, "bitrate","11000");
376                 iks_insert_node(dcodecs, payload_speex);
377         }
378         ast_rtp_lookup_code(p->rtp, 1, codec);
379         return 0;
380 }
381
382 static int gtalk_invite(struct gtalk_pvt *p, char *to, char *from, char *sid, int initiator)
383 {
384         struct gtalk *client = p->parent;
385         iks *iq, *gtalk, *dcodecs, *payload_telephone, *transport;
386         int x;
387         int pref_codec = 0;
388         int alreadysent = 0;
389
390
391         iq = iks_new("iq");
392         gtalk = iks_new("session");
393         dcodecs = iks_new("description");
394         transport = iks_new("transport");
395         payload_telephone = iks_new("payload-type");
396         if (!(iq && gtalk && dcodecs && transport && payload_telephone)){
397                 if(iq)
398                         iks_delete(iq);
399                 if(gtalk)
400                         iks_delete(gtalk);
401                 if(dcodecs)
402                         iks_delete(dcodecs);
403                 if(transport)
404                         iks_delete(transport);
405                 if(payload_telephone)
406                         iks_delete(payload_telephone);
407
408                 ast_log(LOG_ERROR, "Could not allocate iksemel nodes\n");
409                 return 0;
410         }
411         iks_insert_attrib(dcodecs, "xmlns", "http://www.google.com/session/phone");
412         iks_insert_attrib(dcodecs, "xml:lang", "en");
413
414         for (x = 0; x < 32; x++) {
415                 if (!(pref_codec = ast_codec_pref_index(&client->prefs, x)))
416                         break;
417                 if (!(client->capability & pref_codec))
418                         continue;
419                 if (alreadysent & pref_codec)
420                         continue;
421                 add_codec_to_answer(p, pref_codec, dcodecs);
422                 alreadysent |= pref_codec;
423         }
424         
425         iks_insert_attrib(payload_telephone, "id", "106");
426         iks_insert_attrib(payload_telephone, "name", "telephone-event");
427         iks_insert_attrib(payload_telephone, "clockrate", "8000");
428         
429         iks_insert_attrib(transport,"xmlns","http://www.google.com/transport/p2p");
430         
431         iks_insert_attrib(iq, "type", "set");
432         iks_insert_attrib(iq, "to", to);
433         iks_insert_attrib(iq, "from", from);
434         iks_insert_attrib(iq, "id", client->connection->mid);
435         ast_aji_increment_mid(client->connection->mid);
436
437         iks_insert_attrib(gtalk, "xmlns", "http://www.google.com/session");
438         iks_insert_attrib(gtalk, "type",initiator ? "initiate": "accept");
439         iks_insert_attrib(gtalk, "initiator", initiator ? from : to);
440         iks_insert_attrib(gtalk, "id", sid);
441         iks_insert_node(iq, gtalk);
442         iks_insert_node(gtalk, dcodecs);
443         iks_insert_node(gtalk, transport);
444         iks_insert_node(dcodecs, payload_telephone);
445
446         iks_send(client->connection->p, iq);
447         iks_delete(payload_telephone);
448         iks_delete(transport);
449         iks_delete(dcodecs);
450         iks_delete(gtalk);
451         iks_delete(iq);
452         return 1;
453 }
454
455 static int gtalk_invite_response(struct gtalk_pvt *p, char *to , char *from, char *sid, int initiator)
456 {
457         iks *iq, *session, *transport;
458         iq = iks_new("iq");
459         session = iks_new("session");
460         transport = iks_new("transport");
461         if(!(iq && session && transport)) {
462                 if(iq)
463                         iks_delete(iq);
464                 if(session)
465                         iks_delete(session);
466                 if(transport)
467                         iks_delete(transport);
468                 ast_log(LOG_ERROR, " Unable to allocate IKS node\n");
469                 return -1;
470         }
471         iks_insert_attrib(iq, "from", from);
472         iks_insert_attrib(iq, "to", to);
473         iks_insert_attrib(iq, "type", "set");
474         iks_insert_attrib(iq, "id",p->parent->connection->mid);
475         ast_aji_increment_mid(p->parent->connection->mid);
476         iks_insert_attrib(session, "type", "transport-accept");
477         iks_insert_attrib(session, "id", sid);
478         iks_insert_attrib(session, "initiator", initiator ? from : to);
479         iks_insert_attrib(session, "xmlns", "http://www.google.com/session");
480         iks_insert_attrib(transport, "xmlns", "http://www.google.com/transport/p2p");
481         iks_insert_node(iq,session);
482         iks_insert_node(session,transport);
483         iks_send(p->parent->connection->p, iq);
484         iks_delete(transport);
485         iks_delete(session);
486         iks_delete(iq);
487         return 1;
488
489 }
490
491 static int gtalk_ringing_ack(void *data, ikspak *pak)
492 {
493         struct gtalk_pvt *p = data;
494
495         if (p->ringrule)
496                 iks_filter_remove_rule(p->parent->connection->f, p->ringrule);
497         p->ringrule = NULL;
498         if (p->owner)
499                 ast_queue_control(p->owner, AST_CONTROL_RINGING);
500         return IKS_FILTER_EAT;
501 }
502
503 static int gtalk_answer(struct ast_channel *ast)
504 {
505         struct gtalk_pvt *p = ast->tech_pvt;
506         int res = 0;
507         
508         if (option_debug)
509                 ast_log(LOG_DEBUG, "Answer!\n");
510         ast_mutex_lock(&p->lock);
511         gtalk_invite(p, p->them, p->us,p->sid, 0);
512         ast_mutex_unlock(&p->lock);
513         return res;
514 }
515
516 static enum ast_rtp_get_result gtalk_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
517 {
518         struct gtalk_pvt *p = chan->tech_pvt;
519         enum ast_rtp_get_result res = AST_RTP_GET_FAILED;
520
521         if (!p)
522                 return res;
523
524         ast_mutex_lock(&p->lock);
525         if (p->rtp){
526                 *rtp = p->rtp;
527                 res = AST_RTP_TRY_NATIVE;
528         }
529         ast_mutex_unlock(&p->lock);
530
531         return res;
532 }
533
534 static int gtalk_get_codec(struct ast_channel *chan)
535 {
536         struct gtalk_pvt *p = chan->tech_pvt;
537         return p->peercapability;
538 }
539
540 static int gtalk_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active)
541 {
542         struct gtalk_pvt *p;
543
544         p = chan->tech_pvt;
545         if (!p)
546                 return -1;
547         ast_mutex_lock(&p->lock);
548
549 /*      if (rtp)
550                 ast_rtp_get_peer(rtp, &p->redirip);
551         else
552                 memset(&p->redirip, 0, sizeof(p->redirip));
553         p->redircodecs = codecs; */
554
555         /* Reset lastrtprx timer */
556         ast_mutex_unlock(&p->lock);
557         return 0;
558 }
559
560 static int gtalk_response(struct gtalk *client, char *from, ikspak *pak, const char *reasonstr, const char *reasonstr2)
561 {
562         iks *response = NULL, *error = NULL, *reason = NULL;
563         int res = -1;
564
565         response = iks_new("iq");
566         if (response) {
567                 iks_insert_attrib(response, "type", "result");
568                 iks_insert_attrib(response, "from", from);
569                 iks_insert_attrib(response, "to", iks_find_attrib(pak->x, "from"));
570                 iks_insert_attrib(response, "id", iks_find_attrib(pak->x, "id"));
571                 if (reasonstr) {
572                         error = iks_new("error");
573                         if (error) {
574                                 iks_insert_attrib(error, "type", "cancel");
575                                 reason = iks_new(reasonstr);
576                                 if (reason)
577                                         iks_insert_node(error, reason);
578                                 iks_insert_node(response, error);
579                         }
580                 }
581                 iks_send(client->connection->p, response);
582                 if (reason)
583                         iks_delete(reason);
584                 if (error)
585                         iks_delete(error);
586                 iks_delete(response);
587                 res = 0;
588         }
589         return res;
590 }
591
592 static int gtalk_is_answered(struct gtalk *client, ikspak *pak)
593 {
594         struct gtalk_pvt *tmp;
595         char *from;
596         if (option_debug)
597                 ast_log(LOG_DEBUG, "The client is %s\n", client->name);
598         /* Make sure our new call doesn't exist yet */
599         for (tmp = client->p; tmp; tmp = tmp->next) {
600                 if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid))
601                         break;
602         }
603         
604         from = iks_find_attrib(pak->x, "to");
605         if(!from)
606                 from = client->connection->jid->full;
607
608         if (tmp) {
609                 if (tmp->owner)
610                         ast_queue_control(tmp->owner, AST_CONTROL_ANSWER);
611         } else
612                 ast_log(LOG_NOTICE, "Whoa, didn't find call!\n");
613         gtalk_response(client, from, pak, NULL, NULL);
614         return 1;
615 }
616
617 static int gtalk_handle_dtmf(struct gtalk *client, ikspak *pak)
618 {
619         struct gtalk_pvt *tmp;
620         iks *dtmfnode = NULL;
621         char *dtmf;
622         char *from;
623         /* Make sure our new call doesn't exist yet */
624         for (tmp = client->p; tmp; tmp = tmp->next) {
625                 if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid))
626                         break;
627         }
628         from = iks_find_attrib(pak->x, "to");
629         if(!from)
630                 from = client->connection->jid->full;
631
632
633         if (tmp) {
634                 if(iks_find_with_attrib(pak->x, "dtmf-method", "method", "rtp")) {
635                         gtalk_response(client, from, pak,
636                                         "feature-not-implemented xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'",
637                                         "unsupported-dtmf-method xmlns='http://jabber.org/protocol/gtalk/info/dtmf#errors'");
638                         return -1;
639                 }
640                 if ((dtmfnode = iks_find(pak->x, "dtmf"))) {
641                         if((dtmf = iks_find_attrib(dtmfnode, "code"))) {
642                                 if(iks_find_with_attrib(pak->x, "dtmf", "action", "button-up")) {
643                                         struct ast_frame f = {AST_FRAME_DTMF_BEGIN, };
644                                         f.subclass = dtmf[0];
645                                         ast_queue_frame(tmp->owner, &f);
646                                         ast_verbose("GOOGLE! DTMF-relay event received: %c\n", f.subclass);
647                                 } else if(iks_find_with_attrib(pak->x, "dtmf", "action", "button-down")) {
648                                         struct ast_frame f = {AST_FRAME_DTMF_END, };
649                                         f.subclass = dtmf[0];
650                                         ast_queue_frame(tmp->owner, &f);
651                                         ast_verbose("GOOGLE! DTMF-relay event received: %c\n", f.subclass);
652                                 } else if(iks_find_attrib(pak->x, "dtmf")) { /* 250 millasecond default */
653                                         struct ast_frame f = {AST_FRAME_DTMF, };
654                                         f.subclass = dtmf[0];
655                                         ast_queue_frame(tmp->owner, &f);
656                                         ast_verbose("GOOGLE! DTMF-relay event received: %c\n", f.subclass);
657                                 }
658                         }
659                 }
660                 gtalk_response(client, from, pak, NULL, NULL);
661                 return 1;
662         } else
663                 ast_log(LOG_NOTICE, "Whoa, didn't find call!\n");
664
665         gtalk_response(client, from, pak, NULL, NULL);
666         return 1;
667 }
668
669
670 static int gtalk_hangup_farend(struct gtalk *client, ikspak *pak)
671 {
672         struct gtalk_pvt *tmp;
673         char *from;
674
675         if (option_debug)
676                 ast_log(LOG_DEBUG, "The client is %s\n", client->name);
677         /* Make sure our new call doesn't exist yet */
678         for (tmp = client->p; tmp; tmp = tmp->next) {
679                 if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid))
680                         break;
681         }
682         from = iks_find_attrib(pak->x, "to");
683         if(!from)
684                 from = client->connection->jid->full;
685
686
687         if (tmp) {
688                 tmp->alreadygone = 1;
689                 ast_queue_hangup(tmp->owner);
690         } else
691                 ast_log(LOG_NOTICE, "Whoa, didn't find call!\n");
692         gtalk_response(client, from, pak, NULL, NULL);
693         return 1;
694 }
695
696 static int gtalk_create_candidates(struct gtalk *client, struct gtalk_pvt *p, char *sid, char *from, char *to)
697 {
698         struct gtalk_candidate *tmp;
699         struct aji_client *c = client->connection;
700         struct gtalk_candidate *ours1 = NULL, *ours2 = NULL;
701         struct sockaddr_in sin;
702         struct sockaddr_in dest;
703         struct in_addr us;
704         iks *iq, *gtalk, *candidate, *transport;
705         char user[17], pass[17], preference[5], port[7];
706
707
708         iq = iks_new("iq");
709         gtalk = iks_new("session");
710         candidate = iks_new("candidate");
711         transport = iks_new("transport");
712         if (!iq || !gtalk || !candidate || !transport) {
713                 ast_log(LOG_ERROR, "Memory allocation error\n");
714                 goto safeout;
715         }
716         ours1 = ast_calloc(1, sizeof(*ours1));
717         ours2 = ast_calloc(1, sizeof(*ours2));
718         if (!ours1 || !ours2)
719                 goto safeout;
720
721         iks_insert_attrib(transport, "xmlns","http://www.google.com/transport/p2p");
722         iks_insert_node(iq, gtalk);
723         iks_insert_node(gtalk,transport);
724         iks_insert_node(transport, candidate);
725
726         for (; p; p = p->next) {
727                 if (!strcasecmp(p->sid, sid))
728                         break;
729         }
730
731         if (!p) {
732                 ast_log(LOG_NOTICE, "No matching gtalk session - SID %s!\n", sid);
733                 goto safeout;
734         }
735
736         ast_rtp_get_us(p->rtp, &sin);
737         ast_find_ourip(&us, bindaddr);
738
739         /* Setup our gtalk candidates */
740         ast_copy_string(ours1->name, "rtp", sizeof(ours1->name));
741         ours1->port = ntohs(sin.sin_port);
742         ours1->preference = 1;
743         snprintf(user, sizeof(user), "%08lx%08lx", ast_random(), ast_random());
744         snprintf(pass, sizeof(pass), "%08lx%08lx", ast_random(), ast_random());
745         ast_copy_string(ours1->username, user, sizeof(ours1->username));
746         ast_copy_string(ours1->password, pass, sizeof(ours1->password));
747         ast_copy_string(ours1->ip, ast_inet_ntoa(us), sizeof(ours1->ip));
748         ours1->protocol = AJI_PROTOCOL_UDP;
749         ours1->type = AJI_CONNECT_LOCAL;
750         ours1->generation = 0;
751         p->ourcandidates = ours1;
752
753         if (!ast_strlen_zero(externip)) {
754                 /* XXX We should really stun for this one not just go with externip XXX */
755                 snprintf(user, sizeof(user), "%08lx%08lx", ast_random(), ast_random());
756                 snprintf(pass, sizeof(pass), "%08lx%08lx", ast_random(), ast_random());
757                 ast_copy_string(ours2->username, user, sizeof(ours2->username));
758                 ast_copy_string(ours2->password, pass, sizeof(ours2->password));
759                 ast_copy_string(ours2->ip, externip, sizeof(ours2->ip));
760                 ast_copy_string(ours2->name, "rtp", sizeof(ours1->name));
761                 ours2->port = ntohs(sin.sin_port);
762                 ours2->preference = 0.9;
763                 ours2->protocol = AJI_PROTOCOL_UDP;
764                 ours2->type = AJI_CONNECT_STUN;
765                 ours2->generation = 0;
766                 ours1->next = ours2;
767                 ours2 = NULL;
768         }
769         ours1 = NULL;
770         dest.sin_addr = __ourip;
771         dest.sin_port = sin.sin_port;
772
773
774         for (tmp = p->ourcandidates; tmp; tmp = tmp->next) {
775                 snprintf(port, sizeof(port), "%d", tmp->port);
776                 snprintf(preference, sizeof(preference), "%.2f", tmp->preference);
777                 iks_insert_attrib(iq, "from", to);
778                 iks_insert_attrib(iq, "to", from);
779                 iks_insert_attrib(iq, "type", "set");
780                 iks_insert_attrib(iq, "id", c->mid);
781                 ast_aji_increment_mid(c->mid);
782                 iks_insert_attrib(gtalk, "type", "transport-info");
783                 iks_insert_attrib(gtalk, "id", sid);
784                 iks_insert_attrib(gtalk, "initiator", (p->initiator) ? to : from);
785                 iks_insert_attrib(gtalk, "xmlns", GOOGLE_NS);
786                 iks_insert_attrib(candidate, "name", tmp->name);
787                 iks_insert_attrib(candidate, "address", tmp->ip);
788                 iks_insert_attrib(candidate, "port", port);
789                 iks_insert_attrib(candidate, "username", tmp->username);
790                 iks_insert_attrib(candidate, "password", tmp->password);
791                 iks_insert_attrib(candidate, "preference", preference);
792                 if (tmp->protocol == AJI_PROTOCOL_UDP)
793                         iks_insert_attrib(candidate, "protocol", "udp");
794                 if (tmp->protocol == AJI_PROTOCOL_SSLTCP)
795                         iks_insert_attrib(candidate, "protocol", "ssltcp");
796                 if (tmp->type == AJI_CONNECT_STUN)
797                         iks_insert_attrib(candidate, "type", "stun");
798                 if (tmp->type == AJI_CONNECT_LOCAL)
799                         iks_insert_attrib(candidate, "type", "local");
800                 if (tmp->type == AJI_CONNECT_RELAY)
801                         iks_insert_attrib(candidate, "type", "relay");
802                 iks_insert_attrib(candidate, "network", "0");
803                 iks_insert_attrib(candidate, "generation", "0");
804                 iks_send(c->p, iq);
805         }
806         p->laststun = 0;
807
808 safeout:
809         if (ours1)
810                 free(ours1);
811         if (ours2)
812                 free(ours2);
813         if (iq)
814                 iks_delete(iq);
815         if (gtalk)
816                 iks_delete(gtalk);
817         if (candidate)
818                 iks_delete(candidate);
819         if(transport)
820                 iks_delete(transport);
821         return 1;
822 }
823
824 static struct gtalk_pvt *gtalk_alloc(struct gtalk *client, const char *us, const char *them, const char *sid)
825 {
826         struct gtalk_pvt *tmp = NULL;
827         struct aji_resource *resources = NULL;
828         struct aji_buddy *buddy;
829         char idroster[200];
830         char *data, *exten = NULL;
831
832         if (option_debug)
833                 ast_log(LOG_DEBUG, "The client is %s for alloc\n", client->name);
834         if (!sid && !strchr(them, '/')) {       /* I started call! */
835                 if (!strcasecmp(client->name, "guest")) {
836                         buddy = ASTOBJ_CONTAINER_FIND(&client->connection->buddies, them);
837                         if (buddy)
838                                 resources = buddy->resources;
839                 } else 
840                         resources = client->buddy->resources;
841                 while (resources) {
842                         if (resources->cap->jingle) {
843                                 break;
844                         }
845                         resources = resources->next;
846                 }
847                 if (resources)
848                         snprintf(idroster, sizeof(idroster), "%s/%s", them, resources->resource);
849                 else {
850                         ast_log(LOG_ERROR, "no gtalk capable clients to talk to.\n");
851                         return NULL;
852                 }
853         }
854         if (!(tmp = ast_calloc(1, sizeof(*tmp)))) {
855                 return NULL;
856         }
857         if (sid) {
858                 ast_copy_string(tmp->sid, sid, sizeof(tmp->sid));
859                 ast_copy_string(tmp->them, them, sizeof(tmp->them));
860                 ast_copy_string(tmp->us, us, sizeof(tmp->us));
861         } else {
862                 snprintf(tmp->sid, sizeof(tmp->sid), "%08lx%08lx", ast_random(), ast_random());
863                 ast_copy_string(tmp->them, idroster, sizeof(tmp->them));
864                 ast_copy_string(tmp->us, us, sizeof(tmp->us));
865                 tmp->initiator = 1;
866         }
867         tmp->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
868         tmp->parent = client;
869         if (!tmp->rtp) {
870                 ast_log(LOG_WARNING, "Out of RTP sessions?\n");
871                 free(tmp);
872                 return NULL;
873         }
874
875         if(strchr(tmp->us, '/')) {
876                 data = ast_strdupa((char *) tmp->us);
877                 exten = strsep(&data, "/");
878         } else
879                 exten = tmp->us;
880         ast_copy_string(tmp->exten,  exten, sizeof(tmp->exten));
881         if(data)
882                 free(data);
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         const char *n2;
898
899         if (title)
900                 n2 = title;
901         else
902                 n2 = i->us;
903         tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, "Gtalk/%s-%04lx", n2, ast_random() & 0xffff);
904         if (!tmp) {
905                 ast_log(LOG_WARNING, "Unable to allocate Gtalk channel structure!\n");
906                 return NULL;
907         }
908         tmp->tech = &gtalk_tech;
909
910         /* Select our native format based on codec preference until we receive
911            something from another device to the contrary. */
912 /*      ast_verbose("XXXXXXXXXXXXX\nXXX i->jointcapability = %X\nXXX i->capability = %X\nXXX global_capability %X\n XXXXXXXXXXXX\n",i->jointcapability,i->capability,global_capability); */
913         if (i->jointcapability)
914                 what = i->jointcapability;
915         else if (i->capability)
916                 what = i->capability;
917         else
918                 what = global_capability;
919         tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | (i->jointcapability & AST_FORMAT_VIDEO_MASK);
920         fmt = ast_best_codec(tmp->nativeformats);
921
922         if (i->rtp) {
923                 ast_rtp_setstun(i->rtp, 1);
924                 tmp->fds[0] = ast_rtp_fd(i->rtp);
925                 tmp->fds[1] = ast_rtcp_fd(i->rtp);
926         }
927         if (i->vrtp) {
928                 ast_rtp_setstun(i->rtp, 1);
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_copy_string(tmp->context, client->context, sizeof(tmp->context));
954         ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
955         /* Don't use ast_set_callerid() here because it will
956          * generate a needless NewCallerID event */
957         tmp->cid.cid_num = ast_strdup(i->cid_num);
958         tmp->cid.cid_ani = ast_strdup(i->cid_num);
959         tmp->cid.cid_name = ast_strdup(i->cid_name);
960         if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
961                 tmp->cid.cid_dnid = ast_strdup(i->exten);
962         tmp->priority = 1;
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
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
1516 static int gtalk_parser(void *data, ikspak *pak)
1517 {
1518         struct gtalk *client = ASTOBJ_REF((struct gtalk *) data);
1519
1520         if (iks_find_with_attrib(pak->x, "session", "type", "initiate")) {
1521                 /* New call */
1522                 gtalk_newcall(client, pak);
1523         } else if (iks_find_with_attrib(pak->x, "session", "type", "candidates") || iks_find_with_attrib(pak->x, "session", "type", "transport-info") ) {
1524                 if (option_debug > 2)
1525                         ast_log(LOG_DEBUG, "About to add candidate!\n");
1526                 gtalk_add_candidate(client, pak);
1527                 if (option_debug > 2)
1528                         ast_log(LOG_DEBUG, "Candidate Added!\n");
1529         } else if (iks_find_with_attrib(pak->x, "session", "type", "accept")) {
1530                 gtalk_is_answered(client, pak);
1531         } else if (iks_find_with_attrib(pak->x, "session", "type", "content-info")) {
1532                 gtalk_handle_dtmf(client, pak);
1533         } else if (iks_find_with_attrib(pak->x, "session", "type", "terminate")) {
1534                 gtalk_hangup_farend(client, pak);
1535         } else if (iks_find_with_attrib(pak->x, "session", "type", "reject")) {
1536                 gtalk_hangup_farend(client, pak);
1537         }
1538         ASTOBJ_UNREF(client, gtalk_member_destroy);
1539         return IKS_FILTER_EAT;
1540 }
1541
1542 /* Not using this anymore probably take out soon 
1543 static struct gtalk_candidate *gtalk_create_candidate(char *args)
1544 {
1545         char *name, *type, *preference, *protocol;
1546         struct gtalk_candidate *res;
1547         res = malloc(sizeof(struct gtalk_candidate));
1548         memset(res, 0, sizeof(struct gtalk_candidate));
1549         if (args)
1550                 name = args;
1551         if ((args = strchr(args, ','))) {
1552                 *args = '\0';
1553                 args++;
1554                 preference = args;
1555         }
1556         if ((args = strchr(args, ','))) {
1557                 *args = '\0';
1558                 args++;
1559                 protocol = args;
1560         }
1561         if ((args = strchr(args, ','))) {
1562                 *args = '\0';
1563                 args++;
1564                 type = args;
1565         }
1566         if (name)
1567                 ast_copy_string(res->name, name, sizeof(res->name));
1568         if (preference) {
1569                 res->preference = atof(preference);
1570         }
1571         if (protocol) {
1572                 if (!strcasecmp("udp", protocol))
1573                         res->protocol = AJI_PROTOCOL_UDP;
1574                 if (!strcasecmp("ssltcp", protocol))
1575                         res->protocol = AJI_PROTOCOL_SSLTCP;
1576         }
1577         if (type) {
1578                 if (!strcasecmp("stun", type))
1579                         res->type = AJI_CONNECT_STUN;
1580                 if (!strcasecmp("local", type))
1581                         res->type = AJI_CONNECT_LOCAL;
1582                 if (!strcasecmp("relay", type))
1583                         res->type = AJI_CONNECT_RELAY;
1584         }
1585
1586         return res;
1587 }
1588 */
1589
1590 static int gtalk_create_member(char *label, struct ast_variable *var, int allowguest,
1591                                                                 struct ast_codec_pref prefs, char *context,
1592                                                                 struct gtalk *member)
1593 {
1594         struct aji_client *client;
1595
1596         if (!member)
1597                 ast_log(LOG_WARNING, "Out of memory.\n");
1598
1599         ast_copy_string(member->name, label, sizeof(member->name));
1600         ast_copy_string(member->user, label, sizeof(member->user));
1601         ast_copy_string(member->context, context, sizeof(member->context));
1602         member->allowguest = allowguest;
1603         member->prefs = prefs;
1604         while (var) {
1605 #if 0
1606                 struct gtalk_candidate *candidate = NULL;
1607 #endif
1608                 if (!strcasecmp(var->name, "username"))
1609                         ast_copy_string(member->user, var->value, sizeof(member->user));
1610                 else if (!strcasecmp(var->name, "disallow"))
1611                         ast_parse_allow_disallow(&member->prefs, &member->capability, var->value, 0);
1612                 else if (!strcasecmp(var->name, "allow"))
1613                         ast_parse_allow_disallow(&member->prefs, &member->capability, var->value, 1);
1614                 else if (!strcasecmp(var->name, "context"))
1615                         ast_copy_string(member->context, var->value, sizeof(member->context));
1616 #if 0
1617                 else if (!strcasecmp(var->name, "candidate")) {
1618                         candidate = gtalk_create_candidate(var->value);
1619                         if (candidate) {
1620                                 candidate->next = member->ourcandidates;
1621                                 member->ourcandidates = candidate;
1622                         }
1623                 }
1624 #endif
1625                 else if (!strcasecmp(var->name, "connection")) {
1626                         if ((client = ast_aji_get_client(var->value))) {
1627                                 member->connection = client;
1628                                 iks_filter_add_rule(client->f, gtalk_parser, member, IKS_RULE_TYPE,
1629                                                                         IKS_PAK_IQ, IKS_RULE_FROM_PARTIAL, member->user,
1630                                                                         IKS_RULE_NS, "http://www.google.com/session",
1631                                                                         IKS_RULE_DONE);
1632
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         struct hostent *hp;
1660         struct ast_hostent ahp;
1661
1662         cfg = ast_config_load(GOOGLE_CONFIG);
1663         if (!cfg)
1664                 return 0;
1665
1666         /* Copy the default jb config over global_jbconf */
1667         memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
1668
1669         cat = ast_category_browse(cfg, NULL);
1670         for (var = ast_variable_browse(cfg, "general"); var; var = var->next) {
1671                 /* handle jb conf */
1672                 if (!ast_jb_read_conf(&global_jbconf, var->name, var->value))
1673                         continue;
1674
1675                 if (!strcasecmp(var->name, "allowguest"))
1676                         allowguest =
1677                                 (ast_true(ast_variable_retrieve(cfg, "general", "allowguest"))) ? 1 : 0;
1678                 else if (!strcasecmp(var->name, "disallow"))
1679                         ast_parse_allow_disallow(&prefs, &global_capability, var->value, 0);
1680                 else if (!strcasecmp(var->name, "allow"))
1681                         ast_parse_allow_disallow(&prefs, &global_capability, var->value, 1);
1682                 else if (!strcasecmp(var->name, "context"))
1683                         ast_copy_string(context, var->value, sizeof(context));
1684                 else if (!strcasecmp(var->name, "bindaddr")) {
1685                         if (!(hp = ast_gethostbyname(var->value, &ahp))) {
1686                                 ast_log(LOG_WARNING, "Invalid address: %s\n", var->value);
1687                         } else {
1688                                 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
1689                         }
1690                 }
1691 /*  Idea to allow for custom candidates  */
1692 /*
1693                 else if (!strcasecmp(var->name, "candidate")) {
1694                         candidate = gtalk_create_candidate(var->value);
1695                         if (candidate) {
1696                                 candidate->next = global_candidates;
1697                                 global_candidates = candidate;
1698                         }
1699                 }
1700 */
1701         }
1702         while (cat) {
1703                 if (strcasecmp(cat, "general")) {
1704                         var = ast_variable_browse(cfg, cat);
1705                         member = (struct gtalk *) malloc(sizeof(struct gtalk));
1706                         memset(member, 0, sizeof(struct gtalk));
1707                         ASTOBJ_INIT(member);
1708                         ASTOBJ_WRLOCK(member);
1709                         if (!strcasecmp(cat, "guest")) {
1710                                 ast_copy_string(member->name, "guest", sizeof(member->name));
1711                                 ast_copy_string(member->user, "guest", sizeof(member->user));
1712                                 ast_copy_string(member->context, context, sizeof(member->context));
1713                                 member->allowguest = allowguest;
1714                                 member->prefs = prefs;
1715                                 while (var) {
1716                                         if (!strcasecmp(var->name, "disallow"))
1717                                                 ast_parse_allow_disallow(&member->prefs, &member->capability,
1718                                                                                                  var->value, 0);
1719                                         else if (!strcasecmp(var->name, "allow"))
1720                                                 ast_parse_allow_disallow(&member->prefs, &member->capability,
1721                                                                                                  var->value, 1);
1722                                         else if (!strcasecmp(var->name, "context"))
1723                                                 ast_copy_string(member->context, var->value,
1724                                                                                 sizeof(member->context));
1725 /*  Idea to allow for custom candidates  */
1726 /*
1727                                         else if (!strcasecmp(var->name, "candidate")) {
1728                                                 candidate = gtalk_create_candidate(var->value);
1729                                                 if (candidate) {
1730                                                         candidate->next = member->ourcandidates;
1731                                                         member->ourcandidates = candidate;
1732                                                 }
1733                                         }
1734 */
1735                                         var = var->next;
1736                                 }
1737                                 ASTOBJ_UNLOCK(member);
1738                                 clients = ast_aji_get_clients();
1739                                 if (clients) {
1740                                         ASTOBJ_CONTAINER_TRAVERSE(clients, 1, {
1741                                                 ASTOBJ_WRLOCK(iterator);
1742                                                 ASTOBJ_WRLOCK(member);
1743                                                 member->connection = iterator;
1744                                                 iks_filter_add_rule(iterator->f, gtalk_parser, member, IKS_RULE_TYPE, IKS_PAK_IQ, IKS_RULE_NS,
1745                                                                                 "http://www.google.com/session", IKS_RULE_DONE);
1746                                                 ASTOBJ_UNLOCK(member);
1747                                                 ASTOBJ_CONTAINER_LINK(&gtalk_list, member);
1748                                                 ASTOBJ_UNLOCK(iterator);
1749                                         });
1750                                 } else {
1751                                         ASTOBJ_UNLOCK(member);
1752                                         ASTOBJ_UNREF(member, gtalk_member_destroy);
1753                                 }
1754                         } else {
1755                                 ASTOBJ_UNLOCK(member);
1756                                 if (gtalk_create_member(cat, var, allowguest, prefs, context, member))
1757                                         ASTOBJ_CONTAINER_LINK(&gtalk_list, member);
1758                                 ASTOBJ_UNREF(member, gtalk_member_destroy);
1759                         }
1760                 }
1761                 cat = ast_category_browse(cfg, cat);
1762         }
1763         gtalk_free_candidates(global_candidates);
1764         return 1;
1765 }
1766
1767 /*! \brief Load module into PBX, register channel */
1768 static int load_module(void)
1769 {
1770         ASTOBJ_CONTAINER_INIT(&gtalk_list);
1771         if (!gtalk_load_config()) {
1772                 ast_log(LOG_ERROR, "Unable to read config file %s. Not loading module.\n", GOOGLE_CONFIG);
1773                 return 0;
1774         }
1775
1776         sched = sched_context_create();
1777         if (!sched) 
1778                 ast_log(LOG_WARNING, "Unable to create schedule context\n");
1779
1780         io = io_context_create();
1781         if (!io) 
1782                 ast_log(LOG_WARNING, "Unable to create I/O context\n");
1783
1784         if (ast_find_ourip(&__ourip, bindaddr)) {
1785                 ast_log(LOG_WARNING, "Unable to get own IP address, Gtalk disabled\n");
1786                 return 0;
1787         }
1788
1789         ast_rtp_proto_register(&gtalk_rtp);
1790         ast_cli_register_multiple(gtalk_cli, sizeof(gtalk_cli) / sizeof(gtalk_cli[0]));
1791
1792         /* Make sure we can register our channel type */
1793         if (ast_channel_register(&gtalk_tech)) {
1794                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", gtalk_tech.type);
1795                 return -1;
1796         }
1797         return 0;
1798 }
1799
1800 /*! \brief Reload module */
1801 static int reload(void)
1802 {
1803         return 0;
1804 }
1805
1806 /*! \brief Unload the gtalk channel from Asterisk */
1807 static int unload_module(void)
1808 {
1809         struct gtalk_pvt *privates = NULL;
1810         ast_cli_unregister_multiple(gtalk_cli, sizeof(gtalk_cli) / sizeof(gtalk_cli[0]));
1811         /* First, take us out of the channel loop */
1812         ast_channel_unregister(&gtalk_tech);
1813         ast_rtp_proto_unregister(&gtalk_rtp);
1814
1815         if (!ast_mutex_lock(&gtalklock)) {
1816                 /* Hangup all interfaces if they have an owner */
1817                 ASTOBJ_CONTAINER_TRAVERSE(&gtalk_list, 1, {
1818                         ASTOBJ_WRLOCK(iterator);
1819                         privates = iterator->p;
1820                         while(privates) {
1821                                 if (privates->owner)
1822                                         ast_softhangup(privates->owner, AST_SOFTHANGUP_APPUNLOAD);
1823                                 privates = privates->next;
1824                         }
1825                         iterator->p = NULL;
1826                         ASTOBJ_UNLOCK(iterator);
1827                 });
1828                 ast_mutex_unlock(&gtalklock);
1829         } else {
1830                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
1831                 return -1;
1832         }
1833         ASTOBJ_CONTAINER_DESTROYALL(&gtalk_list, gtalk_member_destroy);
1834         ASTOBJ_CONTAINER_DESTROY(&gtalk_list);
1835         return 0;
1836 }
1837
1838 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Gtalk Channel Driver",
1839                 .load = load_module,
1840                 .unload = unload_module,
1841                 .reload = reload,
1842                );