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