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