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