326ea70359e3c0d7f63c38a49eaa8f8a2952ffa1
[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  * Philippe Sultan <philippe.sultan@gmail.com>
8  *
9  * See http://www.asterisk.org for more information about
10  * the Asterisk project. Please do not directly contact
11  * any of the maintainers of this project for assistance;
12  * the project provides a web site, mailing lists and IRC
13  * channels for your use.
14  *
15  * This program is free software, distributed under the terms of
16  * the GNU General Public License Version 2. See the LICENSE file
17  * at the top of the source tree.
18  */
19
20 /*! \file
21  *
22  * \author Matt O'Gorman <mogorman@digium.com>
23  * \author Philippe Sultan <philippe.sultan@gmail.com>
24  *
25  * \brief Gtalk Channel Driver, until google/libjingle works with jingle spec
26  *
27  * \ingroup channel_drivers
28  *
29  * ********** General TODO:s
30  * \todo Support config reloading.
31  * \todo Fix native bridging.
32  */
33
34 /*** MODULEINFO
35         <depend>iksemel</depend>
36         <depend>res_jabber</depend>
37         <use>openssl</use>
38  ***/
39
40
41 #include "asterisk.h"
42
43 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
44
45 #include <sys/socket.h>
46 #include <fcntl.h>
47 #include <netdb.h>
48 #include <netinet/in.h>
49 #include <arpa/inet.h>
50 #include <sys/signal.h>
51 #include <iksemel.h>
52 #include <pthread.h>
53 #include <ctype.h>
54
55 #include "asterisk/lock.h"
56 #include "asterisk/channel.h"
57 #include "asterisk/config.h"
58 #include "asterisk/module.h"
59 #include "asterisk/pbx.h"
60 #include "asterisk/sched.h"
61 #include "asterisk/io.h"
62 #include "asterisk/rtp_engine.h"
63 #include "asterisk/stun.h"
64 #include "asterisk/acl.h"
65 #include "asterisk/callerid.h"
66 #include "asterisk/file.h"
67 #include "asterisk/cli.h"
68 #include "asterisk/app.h"
69 #include "asterisk/musiconhold.h"
70 #include "asterisk/manager.h"
71 #include "asterisk/stringfields.h"
72 #include "asterisk/utils.h"
73 #include "asterisk/causes.h"
74 #include "asterisk/astobj.h"
75 #include "asterisk/abstract_jb.h"
76 #include "asterisk/jabber.h"
77 #include "asterisk/jingle.h"
78
79 #define GOOGLE_CONFIG "gtalk.conf"
80
81 /*! Global jitterbuffer configuration - by default, jb is disabled */
82 static struct ast_jb_conf default_jbconf =
83 {
84         .flags = 0,
85         .max_size = -1,
86         .resync_threshold = -1,
87         .impl = "",
88         .target_extra = -1,
89 };
90 static struct ast_jb_conf global_jbconf;
91
92 enum gtalk_protocol {
93         AJI_PROTOCOL_UDP = 1,
94         AJI_PROTOCOL_SSLTCP = 2,
95 };
96
97 enum gtalk_connect_type {
98         AJI_CONNECT_STUN = 1,
99         AJI_CONNECT_LOCAL = 2,
100         AJI_CONNECT_RELAY = 3,
101 };
102
103 enum gtalk_client_type {
104         AJI_CLIENT_UNKNOWN,
105         AJI_CLIENT_GTALK,               /*!< Remote client type is GoogleTalk */
106         AJI_CLIENT_GMAIL,               /*!< Remote client type is Gmail */
107         AJI_CLIENT_GOOGLE_VOICE,/*!< Remote client type is Google Voice*/
108
109 };
110
111 struct gtalk_pvt {
112         ast_mutex_t lock;                /*!< Channel private lock */
113         time_t laststun;
114         struct gtalk *parent;            /*!< Parent client */
115         char sid[100];
116         char us[AJI_MAX_JIDLEN];
117         char them[AJI_MAX_JIDLEN];
118         char ring[10];                   /*!< Message ID of ring */
119         iksrule *ringrule;               /*!< Rule for matching RING request */
120         int initiator;                   /*!< If we're the initiator */
121         enum gtalk_client_type ctype;
122         int alreadygone;
123         int capability;
124         struct ast_codec_pref prefs;
125         struct gtalk_candidate *theircandidates;
126         struct gtalk_candidate *ourcandidates;
127         char cid_num[80];                /*!< Caller ID num */
128         char cid_name[80];               /*!< Caller ID name */
129         char exten[80];                  /*!< Called extension */
130         struct ast_channel *owner;       /*!< Master Channel */
131         struct ast_rtp_instance *rtp;             /*!< RTP audio session */
132         struct ast_rtp_instance *vrtp;            /*!< RTP video session */
133         format_t jointcapability;             /*!< Supported capability at both ends (codecs ) */
134         format_t peercapability;
135         struct gtalk_pvt *next; /* Next entity */
136 };
137
138 struct gtalk_candidate {
139         char name[100];
140         enum gtalk_protocol protocol;
141         double preference;
142         char username[100];
143         char password[100];
144         enum gtalk_connect_type type;
145         char network[6];
146         int generation;
147         char ip[16];
148         int port;
149         int receipt;
150         struct gtalk_candidate *next;
151 };
152
153 struct gtalk {
154         ASTOBJ_COMPONENTS(struct gtalk);
155         struct aji_client *connection;
156         struct aji_buddy *buddy;
157         struct gtalk_pvt *p;
158         struct ast_codec_pref prefs;
159         int amaflags;                   /*!< AMA Flags */
160         char user[AJI_MAX_JIDLEN];
161         char context[AST_MAX_CONTEXT];
162         char parkinglot[AST_MAX_CONTEXT];       /*!<  Parkinglot */
163         char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */
164         format_t capability;
165         ast_group_t callgroup;  /*!< Call group */
166         ast_group_t pickupgroup;        /*!< Pickup group */
167         int callingpres;                /*!< Calling presentation */
168         int allowguest;
169         char language[MAX_LANGUAGE];    /*!<  Default language for prompts */
170         char musicclass[MAX_MUSICCLASS];        /*!<  Music on Hold class */
171 };
172
173 struct gtalk_container {
174         ASTOBJ_CONTAINER_COMPONENTS(struct gtalk);
175 };
176
177 static const char desc[] = "Gtalk Channel";
178
179 static format_t global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
180
181 AST_MUTEX_DEFINE_STATIC(gtalklock); /*!< Protect the interface list (of gtalk_pvt's) */
182
183 /* Forward declarations */
184 static struct ast_channel *gtalk_request(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause);
185 /*static int gtalk_digit(struct ast_channel *ast, char digit, unsigned int duration);*/
186 static int gtalk_sendtext(struct ast_channel *ast, const char *text);
187 static int gtalk_digit_begin(struct ast_channel *ast, char digit);
188 static int gtalk_digit_end(struct ast_channel *ast, char digit, unsigned int duration);
189 static int gtalk_call(struct ast_channel *ast, char *dest, int timeout);
190 static int gtalk_hangup(struct ast_channel *ast);
191 static int gtalk_answer(struct ast_channel *ast);
192 static int gtalk_action(struct gtalk *client, struct gtalk_pvt *p, const char *action);
193 static void gtalk_free_pvt(struct gtalk *client, struct gtalk_pvt *p);
194 static int gtalk_newcall(struct gtalk *client, ikspak *pak);
195 static struct ast_frame *gtalk_read(struct ast_channel *ast);
196 static int gtalk_write(struct ast_channel *ast, struct ast_frame *f);
197 static int gtalk_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
198 static int gtalk_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
199 static int gtalk_sendhtml(struct ast_channel *ast, int subclass, const char *data, int datalen);
200 static struct gtalk_pvt *gtalk_alloc(struct gtalk *client, const char *us, const char *them, const char *sid);
201 static int gtalk_update_stun(struct gtalk *client, struct gtalk_pvt *p);
202 /* static char *gtalk_do_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a); */
203 static char *gtalk_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
204 static int gtalk_update_externip(void);
205
206 /*! \brief PBX interface structure for channel registration */
207 static const struct ast_channel_tech gtalk_tech = {
208         .type = "Gtalk",
209         .description = "Gtalk Channel Driver",
210         .capabilities = AST_FORMAT_AUDIO_MASK,
211         .requester = gtalk_request,
212         .send_text = gtalk_sendtext,
213         .send_digit_begin = gtalk_digit_begin,
214         .send_digit_end = gtalk_digit_end,
215         /* XXX TODO native bridging is causing odd problems with DTMF pass-through with
216          * the gtalk servers. Enable native bridging once the source of this problem has
217          * been identified.
218         .bridge = ast_rtp_instance_bridge, */
219         .call = gtalk_call,
220         .hangup = gtalk_hangup,
221         .answer = gtalk_answer,
222         .read = gtalk_read,
223         .write = gtalk_write,
224         .exception = gtalk_read,
225         .indicate = gtalk_indicate,
226         .fixup = gtalk_fixup,
227         .send_html = gtalk_sendhtml,
228         .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER
229 };
230
231 static struct sockaddr_in bindaddr = { 0, };    /*!< The address we bind to */
232
233 static struct sched_context *sched;     /*!< The scheduling context */
234 static struct io_context *io;   /*!< The IO context */
235 static struct in_addr __ourip;
236
237 static struct ast_cli_entry gtalk_cli[] = {
238 /*      AST_CLI_DEFINE(gtalk_do_reload, "Reload GoogleTalk configuration"), XXX TODO reloads are not possible yet. */
239         AST_CLI_DEFINE(gtalk_show_channels, "Show GoogleTalk channels"),
240 };
241
242 static char externip[16];
243 static struct sockaddr_in stunaddr; /*!< the stun server we get the externip from */
244
245 static struct gtalk_container gtalk_list;
246
247 static void gtalk_member_destroy(struct gtalk *obj)
248 {
249         ast_free(obj);
250 }
251
252 static struct gtalk *find_gtalk(char *name, char *connection)
253 {
254         struct gtalk *gtalk = NULL;
255         char *domain = NULL , *s = NULL;
256
257         if (strchr(connection, '@')) {
258                 s = ast_strdupa(connection);
259                 domain = strsep(&s, "@");
260                 ast_verbose("OOOOH domain = %s\n", domain);
261         }
262         gtalk = ASTOBJ_CONTAINER_FIND(&gtalk_list, name);
263         if (!gtalk && strchr(name, '@'))
264                 gtalk = ASTOBJ_CONTAINER_FIND_FULL(&gtalk_list, name, user,,, strcasecmp);
265
266         if (!gtalk) {
267                 /* guest call */
268                 ASTOBJ_CONTAINER_TRAVERSE(&gtalk_list, 1, {
269                         ASTOBJ_RDLOCK(iterator);
270                         if (!strcasecmp(iterator->name, "guest")) {
271                                 gtalk = iterator;
272                         }
273                         ASTOBJ_UNLOCK(iterator);
274
275                         if (gtalk)
276                                 break;
277                 });
278
279         }
280         return gtalk;
281 }
282
283
284 static int add_codec_to_answer(const struct gtalk_pvt *p, int codec, iks *dcodecs)
285 {
286         int res = 0;
287         char *format = ast_getformatname(codec);
288
289         if (!strcasecmp("ulaw", format)) {
290                 iks *payload_eg711u, *payload_pcmu;
291                 payload_pcmu = iks_new("payload-type");
292                 payload_eg711u = iks_new("payload-type");
293
294                 if(!payload_eg711u || !payload_pcmu) {
295                         iks_delete(payload_pcmu);
296                         iks_delete(payload_eg711u);
297                         ast_log(LOG_WARNING,"Failed to allocate iks node");
298                         return -1;
299                 }
300                 iks_insert_attrib(payload_pcmu, "id", "0");
301                 iks_insert_attrib(payload_pcmu, "name", "PCMU");
302                 iks_insert_attrib(payload_pcmu, "clockrate","8000");
303                 iks_insert_attrib(payload_pcmu, "bitrate","64000");
304                 iks_insert_attrib(payload_eg711u, "id", "100");
305                 iks_insert_attrib(payload_eg711u, "name", "EG711U");
306                 iks_insert_attrib(payload_eg711u, "clockrate","8000");
307                 iks_insert_attrib(payload_eg711u, "bitrate","64000");
308                 iks_insert_node(dcodecs, payload_pcmu);
309                 iks_insert_node(dcodecs, payload_eg711u);
310                 res ++;
311         }
312         if (!strcasecmp("alaw", format)) {
313                 iks *payload_eg711a, *payload_pcma;
314                 payload_pcma = iks_new("payload-type");
315                 payload_eg711a = iks_new("payload-type");
316                 if(!payload_eg711a || !payload_pcma) {
317                         iks_delete(payload_eg711a);
318                         iks_delete(payload_pcma);
319                         ast_log(LOG_WARNING,"Failed to allocate iks node");
320                         return -1;
321                 }
322                 iks_insert_attrib(payload_pcma, "id", "8");
323                 iks_insert_attrib(payload_pcma, "name", "PCMA");
324                 iks_insert_attrib(payload_pcma, "clockrate","8000");
325                 iks_insert_attrib(payload_pcma, "bitrate","64000");
326                 payload_eg711a = iks_new("payload-type");
327                 iks_insert_attrib(payload_eg711a, "id", "101");
328                 iks_insert_attrib(payload_eg711a, "name", "EG711A");
329                 iks_insert_attrib(payload_eg711a, "clockrate","8000");
330                 iks_insert_attrib(payload_eg711a, "bitrate","64000");
331                 iks_insert_node(dcodecs, payload_pcma);
332                 iks_insert_node(dcodecs, payload_eg711a);
333                 res ++;
334         }
335         if (!strcasecmp("ilbc", format)) {
336                 iks *payload_ilbc = iks_new("payload-type");
337                 if(!payload_ilbc) {
338                         ast_log(LOG_WARNING,"Failed to allocate iks node");
339                         return -1;
340                 }
341                 iks_insert_attrib(payload_ilbc, "id", "97");
342                 iks_insert_attrib(payload_ilbc, "name", "iLBC");
343                 iks_insert_attrib(payload_ilbc, "clockrate","8000");
344                 iks_insert_attrib(payload_ilbc, "bitrate","13300");
345                 iks_insert_node(dcodecs, payload_ilbc);
346                 res ++;
347         }
348         if (!strcasecmp("g723", format)) {
349                 iks *payload_g723 = iks_new("payload-type");
350                 if(!payload_g723) {
351                         ast_log(LOG_WARNING,"Failed to allocate iks node");
352                         return -1;
353                 }
354                 iks_insert_attrib(payload_g723, "id", "4");
355                 iks_insert_attrib(payload_g723, "name", "G723");
356                 iks_insert_attrib(payload_g723, "clockrate","8000");
357                 iks_insert_attrib(payload_g723, "bitrate","6300");
358                 iks_insert_node(dcodecs, payload_g723);
359                 res ++;
360         }
361         if (!strcasecmp("speex", format)) {
362                 iks *payload_speex = iks_new("payload-type");
363                 if(!payload_speex) {
364                         ast_log(LOG_WARNING,"Failed to allocate iks node");
365                         return -1;
366                 }
367                 iks_insert_attrib(payload_speex, "id", "110");
368                 iks_insert_attrib(payload_speex, "name", "speex");
369                 iks_insert_attrib(payload_speex, "clockrate","8000");
370                 iks_insert_attrib(payload_speex, "bitrate","11000");
371                 iks_insert_node(dcodecs, payload_speex);
372                 res++;
373         }
374         if (!strcasecmp("gsm", format)) {
375                 iks *payload_gsm = iks_new("payload-type");
376                 if(!payload_gsm) {
377                         ast_log(LOG_WARNING,"Failed to allocate iks node");
378                         return -1;
379                 }
380                 iks_insert_attrib(payload_gsm, "id", "103");
381                 iks_insert_attrib(payload_gsm, "name", "gsm");
382                 iks_insert_node(dcodecs, payload_gsm);
383                 res++;
384         }
385
386         return res;
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         int codecs_num = 0;
397         char *lowerto = NULL;
398
399         iq = iks_new("iq");
400         gtalk = iks_new("session");
401         dcodecs = iks_new("description");
402         transport = iks_new("transport");
403         payload_telephone = iks_new("payload-type");
404         if (!(iq && gtalk && dcodecs && transport && payload_telephone)){
405                 iks_delete(iq);
406                 iks_delete(gtalk);
407                 iks_delete(dcodecs);
408                 iks_delete(transport);
409                 iks_delete(payload_telephone);
410
411                 ast_log(LOG_ERROR, "Could not allocate iksemel nodes\n");
412                 return 0;
413         }
414         iks_insert_attrib(dcodecs, "xmlns", GOOGLE_AUDIO_NS);
415         iks_insert_attrib(dcodecs, "xml:lang", "en");
416
417         for (x = 0; x < 64; x++) {
418                 if (!(pref_codec = ast_codec_pref_index(&client->prefs, x)))
419                         break;
420                 if (!(client->capability & pref_codec))
421                         continue;
422                 if (alreadysent & pref_codec)
423                         continue;
424                 codecs_num = add_codec_to_answer(p, pref_codec, dcodecs);
425                 alreadysent |= pref_codec;
426         }
427
428         if (codecs_num) {
429                 /* only propose DTMF within an audio session */
430                 iks_insert_attrib(payload_telephone, "id", "101");
431                 iks_insert_attrib(payload_telephone, "name", "telephone-event");
432                 iks_insert_attrib(payload_telephone, "clockrate", "8000");
433         }
434         iks_insert_attrib(transport,"xmlns",GOOGLE_TRANSPORT_NS);
435
436         iks_insert_attrib(iq, "type", "set");
437         iks_insert_attrib(iq, "to", to);
438         iks_insert_attrib(iq, "from", from);
439         iks_insert_attrib(iq, "id", client->connection->mid);
440         ast_aji_increment_mid(client->connection->mid);
441
442         iks_insert_attrib(gtalk, "xmlns", GOOGLE_NS);
443         iks_insert_attrib(gtalk, "type",initiator ? "initiate": "accept");
444         /* put the initiator attribute to lower case if we receive the call
445          * otherwise GoogleTalk won't establish the session */
446         if (!initiator) {
447                 char c;
448                 char *t = lowerto = ast_strdupa(to);
449                 while (((c = *t) != '/') && (*t++ = tolower(c)));
450         }
451         iks_insert_attrib(gtalk, "initiator", initiator ? from : lowerto);
452         iks_insert_attrib(gtalk, "id", sid);
453         iks_insert_node(iq, gtalk);
454         iks_insert_node(gtalk, dcodecs);
455         if (p->ctype != AJI_CLIENT_GOOGLE_VOICE) {
456                 iks_insert_node(gtalk, transport);
457         }
458         iks_insert_node(dcodecs, payload_telephone);
459
460         ast_aji_send(client->connection, iq);
461
462         iks_delete(payload_telephone);
463         iks_delete(transport);
464         iks_delete(dcodecs);
465         iks_delete(gtalk);
466         iks_delete(iq);
467         return 1;
468 }
469
470 static int gtalk_invite_response(struct gtalk_pvt *p, char *to , char *from, char *sid, int initiator)
471 {
472         iks *iq, *session, *transport;
473         char *lowerto = NULL;
474
475         iq = iks_new("iq");
476         session = iks_new("session");
477         transport = iks_new("transport");
478         if(!(iq && session && transport)) {
479                 iks_delete(iq);
480                 iks_delete(session);
481                 iks_delete(transport);
482                 ast_log(LOG_ERROR, " Unable to allocate IKS node\n");
483                 return -1;
484         }
485         iks_insert_attrib(iq, "from", from);
486         iks_insert_attrib(iq, "to", to);
487         iks_insert_attrib(iq, "type", "set");
488         iks_insert_attrib(iq, "id",p->parent->connection->mid);
489         ast_aji_increment_mid(p->parent->connection->mid);
490         iks_insert_attrib(session, "type", "transport-accept");
491         iks_insert_attrib(session, "id", sid);
492         /* put the initiator attribute to lower case if we receive the call
493          * otherwise GoogleTalk won't establish the session */
494         if (!initiator) {
495                 char c;
496                 char *t = lowerto = ast_strdupa(to);
497                 while (((c = *t) != '/') && (*t++ = tolower(c)));
498         }
499         iks_insert_attrib(session, "initiator", initiator ? from : lowerto);
500         iks_insert_attrib(session, "xmlns", GOOGLE_NS);
501         iks_insert_attrib(transport, "xmlns", GOOGLE_TRANSPORT_NS);
502         iks_insert_node(iq,session);
503         iks_insert_node(session,transport);
504         ast_aji_send(p->parent->connection, iq);
505
506         iks_delete(transport);
507         iks_delete(session);
508         iks_delete(iq);
509         return 1;
510
511 }
512
513 static int gtalk_ringing_ack(void *data, ikspak *pak)
514 {
515         struct gtalk_pvt *p = data;
516
517         if (p->ringrule)
518                 iks_filter_remove_rule(p->parent->connection->f, p->ringrule);
519         p->ringrule = NULL;
520         if (p->owner)
521                 ast_queue_control(p->owner, AST_CONTROL_RINGING);
522         return IKS_FILTER_EAT;
523 }
524
525 static int gtalk_answer(struct ast_channel *ast)
526 {
527         struct gtalk_pvt *p = ast->tech_pvt;
528         int res = 0;
529
530         ast_debug(1, "Answer!\n");
531         ast_mutex_lock(&p->lock);
532         gtalk_invite(p, p->them, p->us,p->sid, 0);
533         manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate", "Channel: %s\r\nChanneltype: %s\r\nGtalk-SID: %s\r\n",
534                 ast->name, "GTALK", p->sid);
535         ast_mutex_unlock(&p->lock);
536         return res;
537 }
538
539 static enum ast_rtp_glue_result gtalk_get_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
540 {
541         struct gtalk_pvt *p = chan->tech_pvt;
542         enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_FORBID;
543
544         if (!p)
545                 return res;
546
547         ast_mutex_lock(&p->lock);
548         if (p->rtp){
549                 ao2_ref(p->rtp, +1);
550                 *instance = p->rtp;
551                 res = AST_RTP_GLUE_RESULT_LOCAL;
552         }
553         ast_mutex_unlock(&p->lock);
554
555         return res;
556 }
557
558 static format_t gtalk_get_codec(struct ast_channel *chan)
559 {
560         struct gtalk_pvt *p = chan->tech_pvt;
561         return p->peercapability;
562 }
563
564 static int gtalk_set_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance *rtp, struct ast_rtp_instance *vrtp, struct ast_rtp_instance *trtp, format_t codecs, int nat_active)
565 {
566         struct gtalk_pvt *p;
567
568         p = chan->tech_pvt;
569         if (!p)
570                 return -1;
571         ast_mutex_lock(&p->lock);
572
573 /*      if (rtp)
574                 ast_rtp_get_peer(rtp, &p->redirip);
575         else
576                 memset(&p->redirip, 0, sizeof(p->redirip));
577         p->redircodecs = codecs; */
578
579         /* Reset lastrtprx timer */
580         ast_mutex_unlock(&p->lock);
581         return 0;
582 }
583
584 static struct ast_rtp_glue gtalk_rtp_glue = {
585         .type = "Gtalk",
586         .get_rtp_info = gtalk_get_rtp_peer,
587         .get_codec = gtalk_get_codec,
588         .update_peer = gtalk_set_rtp_peer,
589 };
590
591 static int gtalk_response(struct gtalk *client, char *from, ikspak *pak, const char *reasonstr, const char *reasonstr2)
592 {
593         iks *response = NULL, *error = NULL, *reason = NULL;
594         int res = -1;
595
596         response = iks_new("iq");
597         if (response) {
598                 iks_insert_attrib(response, "type", "result");
599                 iks_insert_attrib(response, "from", from);
600                 iks_insert_attrib(response, "to", iks_find_attrib(pak->x, "from"));
601                 iks_insert_attrib(response, "id", iks_find_attrib(pak->x, "id"));
602                 if (reasonstr) {
603                         error = iks_new("error");
604                         if (error) {
605                                 iks_insert_attrib(error, "type", "cancel");
606                                 reason = iks_new(reasonstr);
607                                 if (reason)
608                                         iks_insert_node(error, reason);
609                                 iks_insert_node(response, error);
610                         }
611                 }
612                 ast_aji_send(client->connection, response);
613                 res = 0;
614         }
615
616         iks_delete(reason);
617         iks_delete(error);
618         iks_delete(response);
619
620         return res;
621 }
622
623 static int gtalk_is_answered(struct gtalk *client, ikspak *pak)
624 {
625         struct gtalk_pvt *tmp = NULL;
626         char *from;
627         iks *codec;
628         char s1[BUFSIZ], s2[BUFSIZ], s3[BUFSIZ];
629         int peernoncodeccapability;
630
631         ast_log(LOG_DEBUG, "The client is %s\n", client->name);
632
633         /* Make sure our new call does exist */
634         for (tmp = client->p; tmp; tmp = tmp->next) {
635                 if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid)) {
636                         break;
637                 } else if (iks_find_with_attrib(pak->x, "ses:session", "id", tmp->sid)) {
638                         break;
639                 }
640         }
641
642         if (!tmp) {
643                 ast_log(LOG_WARNING, "Could not find session in iq\n");
644                 return -1;
645         }
646
647         /* codec points to the first <payload-type/> tag */
648         codec = iks_first_tag(iks_first_tag(iks_first_tag(pak->x)));
649         while (codec) {
650                 ast_rtp_codecs_payloads_set_m_type(ast_rtp_instance_get_codecs(tmp->rtp), tmp->rtp, atoi(iks_find_attrib(codec, "id")));
651                 ast_rtp_codecs_payloads_set_rtpmap_type(ast_rtp_instance_get_codecs(tmp->rtp), tmp->rtp, atoi(iks_find_attrib(codec, "id")), "audio", iks_find_attrib(codec, "name"), 0);
652                 codec = iks_next_tag(codec);
653         }
654
655         /* Now gather all of the codecs that we are asked for */
656         ast_rtp_codecs_payload_formats(ast_rtp_instance_get_codecs(tmp->rtp), &tmp->peercapability, &peernoncodeccapability);
657
658         /* at this point, we received an awser from the remote Gtalk client,
659            which allows us to compare capabilities */
660         tmp->jointcapability = tmp->capability & tmp->peercapability;
661         if (!tmp->jointcapability) {
662                 ast_log(LOG_WARNING, "Capabilities don't match : us - %s, peer - %s, combined - %s \n", ast_getformatname_multiple(s1, BUFSIZ, tmp->capability),
663                         ast_getformatname_multiple(s2, BUFSIZ, tmp->peercapability),
664                         ast_getformatname_multiple(s3, BUFSIZ, tmp->jointcapability));
665                 /* close session if capabilities don't match */
666                 ast_queue_hangup(tmp->owner);
667
668                 return -1;
669
670         }
671
672         from = iks_find_attrib(pak->x, "to");
673         if (!from) {
674                 from = client->connection->jid->full;
675         }
676
677         if (tmp->owner) {
678                 ast_queue_control(tmp->owner, AST_CONTROL_ANSWER);
679         }
680         gtalk_update_stun(tmp->parent, tmp);
681         gtalk_response(client, from, pak, NULL, NULL);
682         return 1;
683 }
684
685 static int gtalk_is_accepted(struct gtalk *client, ikspak *pak)
686 {
687         struct gtalk_pvt *tmp;
688         char *from;
689
690         ast_log(LOG_DEBUG, "The client is %s\n", client->name);
691         /* find corresponding call */
692         for (tmp = client->p; tmp; tmp = tmp->next) {
693                 if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid)) {
694                         break;
695                 }
696         }
697
698         from = iks_find_attrib(pak->x, "to");
699         if (!from) {
700                 from = client->connection->jid->full;
701         }
702
703         if (tmp) {
704                 gtalk_update_stun(tmp->parent, tmp);
705         } else {
706                 ast_log(LOG_NOTICE, "Whoa, didn't find call during accept?!\n");
707         }
708
709         /* answer 'iq' packet to let the remote peer know that we're alive */
710         gtalk_response(client, from, pak, NULL, NULL);
711         return 1;
712 }
713
714 static int gtalk_handle_dtmf(struct gtalk *client, ikspak *pak)
715 {
716         struct gtalk_pvt *tmp;
717         iks *dtmfnode = NULL, *dtmfchild = NULL;
718         char *dtmf;
719         char *from;
720         /* Make sure our new call doesn't exist yet */
721         for (tmp = client->p; tmp; tmp = tmp->next) {
722                 if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid) || iks_find_with_attrib(pak->x, "gtalk", "sid", tmp->sid))
723                         break;
724         }
725         from = iks_find_attrib(pak->x, "to");
726         if (!from) {
727                 from = client->connection->jid->full;
728         }
729
730         if (tmp) {
731                 if(iks_find_with_attrib(pak->x, "dtmf-method", "method", "rtp")) {
732                         gtalk_response(client, from, pak,
733                                         "feature-not-implemented xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'",
734                                         "unsupported-dtmf-method xmlns='http://jabber.org/protocol/gtalk/info/dtmf#errors'");
735                         return -1;
736                 }
737                 if ((dtmfnode = iks_find(pak->x, "dtmf"))) {
738                         if((dtmf = iks_find_attrib(dtmfnode, "code"))) {
739                                 if(iks_find_with_attrib(pak->x, "dtmf", "action", "button-up")) {
740                                         struct ast_frame f = {AST_FRAME_DTMF_BEGIN, };
741                                         f.subclass.integer = dtmf[0];
742                                         ast_queue_frame(tmp->owner, &f);
743                                         ast_verbose("GOOGLE! DTMF-relay event received: %c\n", (int) f.subclass.integer);
744                                 } else if(iks_find_with_attrib(pak->x, "dtmf", "action", "button-down")) {
745                                         struct ast_frame f = {AST_FRAME_DTMF_END, };
746                                         f.subclass.integer = dtmf[0];
747                                         ast_queue_frame(tmp->owner, &f);
748                                         ast_verbose("GOOGLE! DTMF-relay event received: %c\n", (int) f.subclass.integer);
749                                 } else if(iks_find_attrib(pak->x, "dtmf")) { /* 250 millasecond default */
750                                         struct ast_frame f = {AST_FRAME_DTMF, };
751                                         f.subclass.integer = dtmf[0];
752                                         ast_queue_frame(tmp->owner, &f);
753                                         ast_verbose("GOOGLE! DTMF-relay event received: %c\n", (int) f.subclass.integer);
754                                 }
755                         }
756                 } else if ((dtmfnode = iks_find_with_attrib(pak->x, "gtalk", "action", "session-info"))) {
757                         if((dtmfchild = iks_find(dtmfnode, "dtmf"))) {
758                                 if((dtmf = iks_find_attrib(dtmfchild, "code"))) {
759                                         if(iks_find_with_attrib(dtmfnode, "dtmf", "action", "button-up")) {
760                                                 struct ast_frame f = {AST_FRAME_DTMF_END, };
761                                                 f.subclass.integer = dtmf[0];
762                                                 ast_queue_frame(tmp->owner, &f);
763                                                 ast_verbose("GOOGLE! DTMF-relay event received: %c\n", (int) f.subclass.integer);
764                                         } else if(iks_find_with_attrib(dtmfnode, "dtmf", "action", "button-down")) {
765                                                 struct ast_frame f = {AST_FRAME_DTMF_BEGIN, };
766                                                 f.subclass.integer = dtmf[0];
767                                                 ast_queue_frame(tmp->owner, &f);
768                                                 ast_verbose("GOOGLE! DTMF-relay event received: %c\n", (int) f.subclass.integer);
769                                         }
770                                 }
771                         }
772                 }
773                 gtalk_response(client, from, pak, NULL, NULL);
774                 return 1;
775         } else {
776                 ast_log(LOG_NOTICE, "Whoa, didn't find call!\n");
777         }
778
779         gtalk_response(client, from, pak, NULL, NULL);
780         return 1;
781 }
782
783 static int gtalk_hangup_farend(struct gtalk *client, ikspak *pak)
784 {
785         struct gtalk_pvt *tmp;
786         char *from;
787
788         ast_debug(1, "The client is %s\n", client->name);
789         /* Make sure our new call doesn't exist yet */
790         for (tmp = client->p; tmp; tmp = tmp->next) {
791                 if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid) ||
792                         (iks_find_attrib(pak->query, "id") && !strcmp(iks_find_attrib(pak->query, "id"), tmp->sid))) {
793                         break;
794                 }
795         }
796         from = iks_find_attrib(pak->x, "to");
797         if (!from) {
798                 from = client->connection->jid->full;
799         }
800
801         if (tmp) {
802                 tmp->alreadygone = 1;
803                 if (tmp->owner) {
804                         ast_queue_hangup(tmp->owner);
805                 }
806         } else {
807                 ast_log(LOG_NOTICE, "Whoa, didn't find call during hangup!\n");
808         }
809         gtalk_response(client, from, pak, NULL, NULL);
810         return 1;
811 }
812
813 static int gtalk_create_candidates(struct gtalk *client, struct gtalk_pvt *p, char *sid, char *from, char *to)
814 {
815         struct gtalk_candidate *tmp;
816         struct aji_client *c = client->connection;
817         struct gtalk_candidate *ours1 = NULL, *ours2 = NULL;
818         struct sockaddr_in sin = { 0, };
819         struct ast_sockaddr sin_tmp;
820         struct ast_sockaddr bindaddr_tmp;
821         struct ast_sockaddr us;
822         iks *iq, *gtalk, *candidate, *transport;
823         char user[17], pass[17], preference[5], port[7];
824         char *lowerfrom = NULL;
825
826         iq = iks_new("iq");
827         gtalk = iks_new("session");
828         candidate = iks_new("candidate");
829         transport = iks_new("transport");
830         if (!iq || !gtalk || !candidate || !transport) {
831                 ast_log(LOG_ERROR, "Memory allocation error\n");
832                 goto safeout;
833         }
834         ours1 = ast_calloc(1, sizeof(*ours1));
835         ours2 = ast_calloc(1, sizeof(*ours2));
836         if (!ours1 || !ours2)
837                 goto safeout;
838
839         iks_insert_attrib(transport, "xmlns",GOOGLE_TRANSPORT_NS);
840         iks_insert_node(iq, gtalk);
841
842         if (p->ctype == AJI_CLIENT_GMAIL) {
843                 iks_insert_node(gtalk,candidate);
844         } else {
845                 iks_insert_node(gtalk,candidate);
846                 iks_insert_node(gtalk,transport);
847         }
848
849         for (; p; p = p->next) {
850                 if (!strcasecmp(p->sid, sid))
851                         break;
852         }
853
854         if (!p) {
855                 ast_log(LOG_NOTICE, "No matching gtalk session - SID %s!\n", sid);
856                 goto safeout;
857         }
858
859         ast_rtp_instance_get_local_address(p->rtp, &sin_tmp);
860         ast_sockaddr_to_sin(&sin_tmp, &sin);
861         ast_sockaddr_from_sin(&bindaddr_tmp, &bindaddr);
862         ast_find_ourip(&us, &bindaddr_tmp);
863         if (!strcmp(ast_sockaddr_stringify_addr(&us), "127.0.0.1")) {
864                 ast_log(LOG_WARNING, "Found a loopback IP on the system, check your network configuration or set the bindaddr attribute.");
865         }
866
867         /* Setup our gtalk candidates */
868         ast_copy_string(ours1->name, "rtp", sizeof(ours1->name));
869         ours1->port = ntohs(sin.sin_port);
870         ours1->preference = 1;
871         snprintf(user, sizeof(user), "%08lx%08lx", ast_random(), ast_random());
872         snprintf(pass, sizeof(pass), "%08lx%08lx", ast_random(), ast_random());
873         ast_copy_string(ours1->username, user, sizeof(ours1->username));
874         ast_copy_string(ours1->password, pass, sizeof(ours1->password));
875         ast_copy_string(ours1->ip, ast_sockaddr_stringify_addr(&us),
876                         sizeof(ours1->ip));
877         ours1->protocol = AJI_PROTOCOL_UDP;
878         ours1->type = AJI_CONNECT_LOCAL;
879         ours1->generation = 0;
880         p->ourcandidates = ours1;
881
882         /* XXX this is a blocking action.  We send a STUN request to the server
883          * and wait for the response.  If blocking here is a problem the STUN requests/responses
884          * for the externip may need to be done differently. */
885         gtalk_update_externip();
886         if (!ast_strlen_zero(externip)) {
887                 ast_copy_string(ours2->username, user, sizeof(ours2->username));
888                 ast_copy_string(ours2->password, pass, sizeof(ours2->password));
889                 ast_copy_string(ours2->ip, externip, sizeof(ours2->ip));
890                 ast_copy_string(ours2->name, "rtp", sizeof(ours1->name));
891                 ours2->port = ntohs(sin.sin_port);
892                 ours2->preference = 0.9;
893                 ours2->protocol = AJI_PROTOCOL_UDP;
894                 ours2->type = AJI_CONNECT_STUN;
895                 ours2->generation = 0;
896                 ours1->next = ours2;
897                 ours2 = NULL;
898         }
899         ours1 = NULL;
900
901         for (tmp = p->ourcandidates; tmp; tmp = tmp->next) {
902                 snprintf(port, sizeof(port), "%d", tmp->port);
903                 snprintf(preference, sizeof(preference), "%.2f", tmp->preference);
904                 iks_insert_attrib(iq, "from", to);
905                 iks_insert_attrib(iq, "to", from);
906                 iks_insert_attrib(iq, "type", "set");
907                 iks_insert_attrib(iq, "id", c->mid);
908                 ast_aji_increment_mid(c->mid);
909                 switch (p->ctype) {
910                 case AJI_CLIENT_GTALK:
911                         iks_insert_attrib(gtalk, "type", "transport-info");
912                         break;
913                 case AJI_CLIENT_GMAIL:
914                         iks_insert_attrib(gtalk, "type", "candidates");
915                         break;
916                 default:
917                         ast_log(LOG_WARNING, "Client type is unknown\n");
918                         iks_insert_attrib(gtalk, "type", "candidates");
919                         break;
920                 }
921                 iks_insert_attrib(gtalk, "id", sid);
922                 /* put the initiator attribute to lower case if we receive the call
923                  * otherwise GoogleTalk won't establish the session */
924                 if (!p->initiator) {
925                         char c;
926                         char *t = lowerfrom = ast_strdupa(from);
927                         while (((c = *t) != '/') && (*t++ = tolower(c)));
928                 }
929                 iks_insert_attrib(gtalk, "initiator", (p->initiator) ? to : lowerfrom);
930                 iks_insert_attrib(gtalk, "xmlns", GOOGLE_NS);
931                 iks_insert_attrib(candidate, "name", tmp->name);
932                 iks_insert_attrib(candidate, "address", tmp->ip);
933                 iks_insert_attrib(candidate, "port", port);
934                 iks_insert_attrib(candidate, "username", tmp->username);
935                 iks_insert_attrib(candidate, "password", tmp->password);
936                 iks_insert_attrib(candidate, "preference", preference);
937                 if (tmp->protocol == AJI_PROTOCOL_UDP)
938                         iks_insert_attrib(candidate, "protocol", "udp");
939                 if (tmp->protocol == AJI_PROTOCOL_SSLTCP)
940                         iks_insert_attrib(candidate, "protocol", "ssltcp");
941                 if (tmp->type == AJI_CONNECT_STUN)
942                         iks_insert_attrib(candidate, "type", "stun");
943                 if (tmp->type == AJI_CONNECT_LOCAL)
944                         iks_insert_attrib(candidate, "type", "local");
945                 if (tmp->type == AJI_CONNECT_RELAY)
946                         iks_insert_attrib(candidate, "type", "relay");
947                 iks_insert_attrib(candidate, "network", "0");
948                 iks_insert_attrib(candidate, "generation", "0");
949                 ast_aji_send(c, iq);
950         }
951         p->laststun = 0;
952
953 safeout:
954         if (ours1)
955                 ast_free(ours1);
956         if (ours2)
957                 ast_free(ours2);
958         iks_delete(iq);
959         iks_delete(gtalk);
960         iks_delete(candidate);
961         iks_delete(transport);
962
963         return 1;
964 }
965
966 static struct gtalk_pvt *gtalk_alloc(struct gtalk *client, const char *us, const char *them, const char *sid)
967 {
968         struct gtalk_pvt *tmp = NULL;
969         struct aji_resource *resources = NULL;
970         struct aji_buddy *buddy;
971         char idroster[200];
972         char *data, *exten = NULL;
973         struct ast_sockaddr bindaddr_tmp;
974         enum gtalk_client_type ctype = AJI_CLIENT_UNKNOWN;
975
976         ast_debug(1, "The client is %s for alloc\n", client->name);
977         if (!sid && !strchr(them, '/')) {       /* I started call! */
978                 if (!strcasecmp(client->name, "guest")) {
979                         buddy = ASTOBJ_CONTAINER_FIND(&client->connection->buddies, them);
980                         if (buddy) {
981                                 resources = buddy->resources;
982                         }
983                 } else if (client->buddy) {
984                         resources = client->buddy->resources;
985                 }
986
987                 while (resources) {
988                         if (resources->cap->jingle) {
989                                 break;
990                         }
991                         resources = resources->next;
992                 }
993                 if (resources) {
994                         snprintf(idroster, sizeof(idroster), "%s/%s", them, resources->resource);
995                         if (strstr(resources->resource, "gmail")) {
996                                 ctype = AJI_CLIENT_GMAIL;
997                         }
998                 } else if ((*them == '+') || (strstr(them, "@voice.google.com"))) {
999                         snprintf(idroster, sizeof(idroster), "%s/srvres", them);
1000                         ctype = AJI_CLIENT_GOOGLE_VOICE;
1001                 } else {
1002                         ast_log(LOG_ERROR, "no gtalk capable clients to talk to.\n");
1003                         return NULL;
1004                 }
1005         }
1006         if (!(tmp = ast_calloc(1, sizeof(*tmp)))) {
1007                 return NULL;
1008         }
1009         /* set client type to unknown until we have more info */
1010         tmp->ctype = ctype;
1011
1012         memcpy(&tmp->prefs, &client->prefs, sizeof(struct ast_codec_pref));
1013
1014         if (sid) {
1015                 ast_copy_string(tmp->sid, sid, sizeof(tmp->sid));
1016                 ast_copy_string(tmp->them, them, sizeof(tmp->them));
1017                 ast_copy_string(tmp->us, us, sizeof(tmp->us));
1018         } else {
1019                 snprintf(tmp->sid, sizeof(tmp->sid), "%08lx%08lx", ast_random(), ast_random());
1020                 ast_copy_string(tmp->them, idroster, sizeof(tmp->them));
1021                 ast_copy_string(tmp->us, us, sizeof(tmp->us));
1022                 tmp->initiator = 1;
1023         }
1024         /* clear codecs */
1025         bindaddr.sin_family = AF_INET;
1026         ast_sockaddr_from_sin(&bindaddr_tmp, &bindaddr);
1027         if (!(tmp->rtp = ast_rtp_instance_new("asterisk", sched, &bindaddr_tmp, NULL))) {
1028           ast_log(LOG_ERROR, "Failed to create a new RTP instance (possibly an invalid bindaddr?)\n");
1029           ast_free(tmp);
1030           return NULL;
1031         }
1032         ast_rtp_instance_set_prop(tmp->rtp, AST_RTP_PROPERTY_RTCP, 1);
1033         ast_rtp_instance_set_prop(tmp->rtp, AST_RTP_PROPERTY_STUN, 1);
1034         ast_rtp_instance_set_prop(tmp->rtp, AST_RTP_PROPERTY_DTMF, 1);
1035         ast_rtp_instance_dtmf_mode_set(tmp->rtp, AST_RTP_DTMF_MODE_RFC2833);
1036         ast_rtp_codecs_payloads_clear(ast_rtp_instance_get_codecs(tmp->rtp), tmp->rtp);
1037
1038         /* add user configured codec capabilites */
1039         if (client->capability)
1040                 tmp->capability = client->capability;
1041         else if (global_capability)
1042                 tmp->capability = global_capability;
1043
1044         tmp->parent = client;
1045         if (!tmp->rtp) {
1046                 ast_log(LOG_WARNING, "Out of RTP sessions?\n");
1047                 ast_free(tmp);
1048                 return NULL;
1049         }
1050
1051         /* Set CALLERID(name) to the full JID of the remote peer */
1052         ast_copy_string(tmp->cid_name, tmp->them, sizeof(tmp->cid_name));
1053
1054         if(strchr(tmp->us, '/')) {
1055                 data = ast_strdupa(tmp->us);
1056                 exten = strsep(&data, "/");
1057         } else
1058                 exten = tmp->us;
1059         ast_copy_string(tmp->exten,  exten, sizeof(tmp->exten));
1060         ast_mutex_init(&tmp->lock);
1061         ast_mutex_lock(&gtalklock);
1062         tmp->next = client->p;
1063         client->p = tmp;
1064         ast_mutex_unlock(&gtalklock);
1065         return tmp;
1066 }
1067
1068 /*! \brief Start new gtalk channel */
1069 static struct ast_channel *gtalk_new(struct gtalk *client, struct gtalk_pvt *i, int state, const char *title, const char *linkedid)
1070 {
1071         struct ast_channel *tmp;
1072         int fmt;
1073         int what;
1074         const char *n2;
1075
1076         if (title)
1077                 n2 = title;
1078         else
1079                 n2 = i->us;
1080         tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, linkedid, client->accountcode, i->exten, client->context, client->amaflags, "Gtalk/%s-%04lx", n2, ast_random() & 0xffff);
1081         if (!tmp) {
1082                 ast_log(LOG_WARNING, "Unable to allocate Gtalk channel structure!\n");
1083                 return NULL;
1084         }
1085         tmp->tech = &gtalk_tech;
1086
1087         /* Select our native format based on codec preference until we receive
1088            something from another device to the contrary. */
1089         if (i->jointcapability)
1090                 what = i->jointcapability;
1091         else if (i->capability)
1092                 what = i->capability;
1093         else
1094                 what = global_capability;
1095
1096         /* Set Frame packetization */
1097         if (i->rtp) {
1098                 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(i->rtp), i->rtp, &i->prefs);
1099         }
1100
1101         tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | (i->jointcapability & AST_FORMAT_VIDEO_MASK);
1102         fmt = ast_best_codec(tmp->nativeformats);
1103
1104         if (i->rtp) {
1105                 ast_channel_set_fd(tmp, 0, ast_rtp_instance_fd(i->rtp, 0));
1106                 ast_channel_set_fd(tmp, 1, ast_rtp_instance_fd(i->rtp, 1));
1107         }
1108         if (i->vrtp) {
1109                 ast_channel_set_fd(tmp, 2, ast_rtp_instance_fd(i->vrtp, 0));
1110                 ast_channel_set_fd(tmp, 3, ast_rtp_instance_fd(i->vrtp, 1));
1111         }
1112         if (state == AST_STATE_RING)
1113                 tmp->rings = 1;
1114         tmp->adsicpe = AST_ADSI_UNAVAILABLE;
1115         tmp->writeformat = fmt;
1116         tmp->rawwriteformat = fmt;
1117         tmp->readformat = fmt;
1118         tmp->rawreadformat = fmt;
1119         tmp->tech_pvt = i;
1120
1121         tmp->callgroup = client->callgroup;
1122         tmp->pickupgroup = client->pickupgroup;
1123         tmp->caller.id.name.presentation = client->callingpres;
1124         tmp->caller.id.number.presentation = client->callingpres;
1125         if (!ast_strlen_zero(client->accountcode))
1126                 ast_string_field_set(tmp, accountcode, client->accountcode);
1127         if (client->amaflags)
1128                 tmp->amaflags = client->amaflags;
1129         if (!ast_strlen_zero(client->language))
1130                 ast_string_field_set(tmp, language, client->language);
1131         if (!ast_strlen_zero(client->musicclass))
1132                 ast_string_field_set(tmp, musicclass, client->musicclass);
1133         if (!ast_strlen_zero(client->parkinglot))
1134                 ast_string_field_set(tmp, parkinglot, client->parkinglot);
1135         i->owner = tmp;
1136         ast_module_ref(ast_module_info->self);
1137         ast_copy_string(tmp->context, client->context, sizeof(tmp->context));
1138         ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
1139
1140         if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s")) {
1141                 tmp->dialed.number.str = ast_strdup(i->exten);
1142         }
1143         tmp->priority = 1;
1144         if (i->rtp)
1145                 ast_jb_configure(tmp, &global_jbconf);
1146         if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
1147                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
1148                 tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
1149                 ast_hangup(tmp);
1150                 tmp = NULL;
1151         } else {
1152                 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
1153                         "Channel: %s\r\nChanneltype: %s\r\nGtalk-SID: %s\r\n",
1154                         i->owner ? i->owner->name : "", "Gtalk", i->sid);
1155         }
1156         return tmp;
1157 }
1158
1159 static int gtalk_action(struct gtalk *client, struct gtalk_pvt *p, const char *action)
1160 {
1161         iks *request, *session = NULL;
1162         int res = -1;
1163         char *lowerthem = NULL;
1164
1165         request = iks_new("iq");
1166         if (request) {
1167                 iks_insert_attrib(request, "type", "set");
1168                 iks_insert_attrib(request, "from", p->us);
1169                 iks_insert_attrib(request, "to", p->them);
1170                 iks_insert_attrib(request, "id", client->connection->mid);
1171                 ast_aji_increment_mid(client->connection->mid);
1172                 session = iks_new("session");
1173                 if (session) {
1174                         iks_insert_attrib(session, "type", action);
1175                         iks_insert_attrib(session, "id", p->sid);
1176                         /* put the initiator attribute to lower case if we receive the call
1177                          * otherwise GoogleTalk won't establish the session */
1178                         if (!p->initiator) {
1179                                 char c;
1180                                 char *t = lowerthem = ast_strdupa(p->them);
1181                                 while (((c = *t) != '/') && (*t++ = tolower(c)));
1182                         }
1183                         iks_insert_attrib(session, "initiator", p->initiator ? p->us : lowerthem);
1184                         iks_insert_attrib(session, "xmlns", GOOGLE_NS);
1185                         iks_insert_node(request, session);
1186                         ast_aji_send(client->connection, request);
1187                         res = 0;
1188                 }
1189         }
1190
1191         iks_delete(session);
1192         iks_delete(request);
1193
1194         return res;
1195 }
1196
1197 static void gtalk_free_candidates(struct gtalk_candidate *candidate)
1198 {
1199         struct gtalk_candidate *last;
1200         while (candidate) {
1201                 last = candidate;
1202                 candidate = candidate->next;
1203                 ast_free(last);
1204         }
1205 }
1206
1207 static void gtalk_free_pvt(struct gtalk *client, struct gtalk_pvt *p)
1208 {
1209         struct gtalk_pvt *cur, *prev = NULL;
1210         cur = client->p;
1211         while (cur) {
1212                 if (cur == p) {
1213                         if (prev)
1214                                 prev->next = p->next;
1215                         else
1216                                 client->p = p->next;
1217                         break;
1218                 }
1219                 prev = cur;
1220                 cur = cur->next;
1221         }
1222         if (p->ringrule)
1223                 iks_filter_remove_rule(p->parent->connection->f, p->ringrule);
1224         if (p->owner)
1225                 ast_log(LOG_WARNING, "Uh oh, there's an owner, this is going to be messy.\n");
1226         if (p->rtp)
1227                 ast_rtp_instance_destroy(p->rtp);
1228         if (p->vrtp)
1229                 ast_rtp_instance_destroy(p->vrtp);
1230         gtalk_free_candidates(p->theircandidates);
1231         ast_free(p);
1232 }
1233
1234
1235 static int gtalk_newcall(struct gtalk *client, ikspak *pak)
1236 {
1237         struct gtalk_pvt *p, *tmp = client->p;
1238         struct ast_channel *chan;
1239         int res;
1240         iks *codec;
1241         char *from = NULL;
1242         char s1[BUFSIZ], s2[BUFSIZ], s3[BUFSIZ];
1243         int peernoncodeccapability;
1244         char *sid;
1245
1246         /* Make sure our new call doesn't exist yet */
1247         from = iks_find_attrib(pak->x,"to");
1248         if (!from) {
1249                 from = client->connection->jid->full;
1250         }
1251
1252         while (tmp) {
1253                 if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid) ||
1254                         (iks_find_attrib(pak->query, "id") && !strcmp(iks_find_attrib(pak->query, "id"), tmp->sid))) {
1255                         ast_log(LOG_NOTICE, "Ignoring duplicate call setup on SID %s\n", tmp->sid);
1256                         gtalk_response(client, from, pak, "out-of-order", NULL);
1257                         return -1;
1258                 }
1259                 tmp = tmp->next;
1260         }
1261
1262         if (!strcasecmp(client->name, "guest")){
1263                 /* the guest account is not tied to any configured XMPP client,
1264                    let's set it now */
1265                 client->connection = ast_aji_get_client(from);
1266                 if (!client->connection) {
1267                         ast_log(LOG_ERROR, "No XMPP client to talk to, us (partial JID) : %s\n", from);
1268                         return -1;
1269                 }
1270         }
1271
1272         if (!(sid = iks_find_attrib(pak->query, "id"))) {
1273                 ast_log(LOG_WARNING, "Received Initiate without id attribute. Can not start call.\n");
1274                 return -1;
1275         }
1276
1277         p = gtalk_alloc(client, from, pak->from->full, sid);
1278         if (!p) {
1279                 ast_log(LOG_WARNING, "Unable to allocate gtalk structure!\n");
1280                 return -1;
1281         }
1282
1283         /* if the node name of the query contains a semicolon, the remote peer
1284          * is a gmail type client. If not, treat it as a regular GoogleTalk
1285          * client */
1286         if (strchr(iks_name(pak->query), ':')) {
1287                 p->ctype = AJI_CLIENT_GMAIL;
1288         } else {
1289                 p->ctype = AJI_CLIENT_GTALK;
1290         }
1291         chan = gtalk_new(client, p, AST_STATE_DOWN, pak->from->user, NULL);
1292         if (!chan) {
1293                 gtalk_free_pvt(client, p);
1294                 return -1;
1295         }
1296
1297         ast_mutex_lock(&p->lock);
1298         ast_copy_string(p->them, pak->from->full, sizeof(p->them));
1299         ast_copy_string(p->sid, sid, sizeof(p->sid));
1300
1301         /* codec points to the first <payload-type/> tag */
1302         codec = iks_first_tag(iks_first_tag(iks_first_tag(pak->x)));
1303
1304         while (codec) {
1305                 char *codec_id = iks_find_attrib(codec, "id");
1306                 char *codec_name = iks_find_attrib(codec, "name");
1307                 if (!codec_id || !codec_name) {
1308                         codec = iks_next_tag(codec);
1309                         continue;
1310                 }
1311                 if (!strcmp(iks_name(codec), "vid:payload-type") && p->vrtp) {
1312                         ast_rtp_codecs_payloads_set_m_type(ast_rtp_instance_get_codecs(p->vrtp), p->vrtp, atoi(codec_id));
1313                         ast_rtp_codecs_payloads_set_rtpmap_type(ast_rtp_instance_get_codecs(p->vrtp), p->vrtp, atoi(codec_id), "video", codec_name, 0);
1314                 } else {
1315                         ast_rtp_codecs_payloads_set_m_type(ast_rtp_instance_get_codecs(p->rtp), p->rtp, atoi(codec_id));
1316                         ast_rtp_codecs_payloads_set_rtpmap_type(ast_rtp_instance_get_codecs(p->rtp), p->rtp, atoi(codec_id), "audio", codec_name, 0);
1317                 }
1318                 codec = iks_next_tag(codec);
1319         }
1320
1321         /* Now gather all of the codecs that we are asked for */
1322         ast_rtp_codecs_payload_formats(ast_rtp_instance_get_codecs(p->rtp), &p->peercapability, &peernoncodeccapability);
1323         p->jointcapability = p->capability & p->peercapability;
1324         ast_mutex_unlock(&p->lock);
1325
1326         ast_setstate(chan, AST_STATE_RING);
1327         if (!p->jointcapability) {
1328                 ast_log(LOG_WARNING, "Capabilities don't match : us - %s, peer - %s, combined - %s \n", ast_getformatname_multiple(s1, BUFSIZ, p->capability),
1329                         ast_getformatname_multiple(s2, BUFSIZ, p->peercapability),
1330                         ast_getformatname_multiple(s3, BUFSIZ, p->jointcapability));
1331                 /* close session if capabilities don't match */
1332                 gtalk_action(client, p, "reject");
1333                 p->alreadygone = 1;
1334                 gtalk_hangup(chan);
1335                 ast_channel_release(chan);
1336                 return -1;
1337         }
1338
1339         res = ast_pbx_start(chan);
1340
1341         switch (res) {
1342         case AST_PBX_FAILED:
1343                 ast_log(LOG_WARNING, "Failed to start PBX :(\n");
1344                 gtalk_response(client, from, pak, "service-unavailable", NULL);
1345                 break;
1346         case AST_PBX_CALL_LIMIT:
1347                 ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
1348                 gtalk_response(client, from, pak, "service-unavailable", NULL);
1349                 break;
1350         case AST_PBX_SUCCESS:
1351                 gtalk_response(client, from, pak, NULL, NULL);
1352                 if (p->ctype == AJI_CLIENT_GTALK) {
1353                         gtalk_invite_response(p, p->them, p->us,p->sid, 0);
1354                 }
1355                 gtalk_create_candidates(client, p, p->sid, p->them, p->us);
1356                 /* nothing to do */
1357                 break;
1358         }
1359
1360         return 1;
1361 }
1362
1363 static int gtalk_update_externip(void)
1364 {
1365         int sock;
1366         char *newaddr;
1367         struct sockaddr_in answer = { 0, };
1368         struct sockaddr_in *dst;
1369         struct ast_sockaddr tmp_dst;
1370
1371         if (!stunaddr.sin_addr.s_addr) {
1372                 return -1;
1373         }
1374         dst = &stunaddr;
1375
1376         sock = socket(AF_INET, SOCK_DGRAM, 0);
1377         if (sock < 0) {
1378                 ast_log(LOG_WARNING, "Unable to create STUN socket: %s\n", strerror(errno));
1379                 return -1;
1380         }
1381
1382         ast_sockaddr_from_sin(&tmp_dst, dst);
1383         if (ast_connect(sock, &tmp_dst) != 0) {
1384                 ast_log(LOG_WARNING, "STUN Failed to connect to %s\n", ast_sockaddr_stringify(&tmp_dst));
1385                 close(sock);
1386                 return -1;
1387         }
1388
1389         if ((ast_stun_request(sock, &stunaddr, NULL, &answer))) {
1390                 close(sock);
1391                 return -1;
1392         }
1393
1394         newaddr = ast_strdupa(ast_inet_ntoa(answer.sin_addr));
1395         memcpy(externip, newaddr, sizeof(externip));
1396
1397         close(sock);
1398         return 0;
1399
1400 }
1401
1402 static int gtalk_update_stun(struct gtalk *client, struct gtalk_pvt *p)
1403 {
1404         struct gtalk_candidate *tmp;
1405         struct hostent *hp;
1406         struct ast_hostent ahp;
1407         struct sockaddr_in sin = { 0, };
1408         struct sockaddr_in aux = { 0, };
1409         struct ast_sockaddr sin_tmp;
1410         struct ast_sockaddr aux_tmp;
1411
1412         if (time(NULL) == p->laststun)
1413                 return 0;
1414
1415         tmp = p->theircandidates;
1416         p->laststun = time(NULL);
1417         while (tmp) {
1418                 char username[256];
1419
1420                 /* Find the IP address of the host */
1421                 if (!(hp = ast_gethostbyname(tmp->ip, &ahp))) {
1422                         ast_log(LOG_WARNING, "Could not get host by name for %s\n", tmp->ip);
1423                         tmp = tmp->next;
1424                         continue;
1425                 }
1426                 sin.sin_family = AF_INET;
1427                 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
1428                 sin.sin_port = htons(tmp->port);
1429                 snprintf(username, sizeof(username), "%s%s", tmp->username, p->ourcandidates->username);
1430
1431                 /* Find out the result of the STUN */
1432                 ast_rtp_instance_get_remote_address(p->rtp, &aux_tmp);
1433                 ast_sockaddr_to_sin(&aux_tmp, &aux);
1434
1435                 /* If the STUN result is different from the IP of the hostname,
1436                  * lock on the stun IP of the hostname advertised by the
1437                  * remote client */
1438                 if (aux.sin_addr.s_addr && (aux.sin_addr.s_addr != sin.sin_addr.s_addr)) {
1439                         ast_rtp_instance_stun_request(p->rtp, &aux_tmp, username);
1440                 } else {
1441                         ast_sockaddr_from_sin(&sin_tmp, &sin);
1442                         ast_rtp_instance_stun_request(p->rtp, &sin_tmp, username);
1443                 }
1444                 if (aux.sin_addr.s_addr) {
1445                         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);
1446                         ast_debug(4, "Sending STUN request to %s\n", tmp->ip);
1447                 }
1448
1449                 tmp = tmp->next;
1450         }
1451         return 1;
1452 }
1453
1454 static int gtalk_add_candidate(struct gtalk *client, ikspak *pak)
1455 {
1456         struct gtalk_pvt *p = NULL, *tmp = NULL;
1457         struct aji_client *c = client->connection;
1458         struct gtalk_candidate *newcandidate = NULL;
1459         iks *traversenodes = NULL, *receipt = NULL;
1460         char *from;
1461
1462         from = iks_find_attrib(pak->x,"to");
1463         if (!from) {
1464                 from = c->jid->full;
1465         }
1466
1467         for (tmp = client->p; tmp; tmp = tmp->next) {
1468                 if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid) ||
1469                         (iks_find_attrib(pak->query, "id") && !strcmp(iks_find_attrib(pak->query, "id"), tmp->sid))) {
1470                         p = tmp;
1471                         break;
1472                 }
1473         }
1474
1475         if (!p) {
1476                 return -1;
1477         }
1478         traversenodes = pak->query;
1479         while(traversenodes) {
1480                 if(!strcasecmp(iks_name(traversenodes), "session")) {
1481                         traversenodes = iks_first_tag(traversenodes);
1482                         continue;
1483                 }
1484                 if(!strcasecmp(iks_name(traversenodes), "ses:session")) {
1485                         traversenodes = iks_child(traversenodes);
1486                         continue;
1487                 }
1488                 if(!strcasecmp(iks_name(traversenodes), "candidate") || !strcasecmp(iks_name(traversenodes), "ses:candidate")) {
1489                         newcandidate = ast_calloc(1, sizeof(*newcandidate));
1490                         if (!newcandidate)
1491                                 return 0;
1492                         ast_copy_string(newcandidate->name,
1493                                 S_OR(iks_find_attrib(traversenodes, "name"), ""),
1494                                 sizeof(newcandidate->name));
1495                         ast_copy_string(newcandidate->ip,
1496                                 S_OR(iks_find_attrib(traversenodes, "address"), ""),
1497                                 sizeof(newcandidate->ip));
1498                         newcandidate->port = atoi(iks_find_attrib(traversenodes, "port"));
1499                         ast_copy_string(newcandidate->username,
1500                                 S_OR(iks_find_attrib(traversenodes, "username"), ""),
1501                                 sizeof(newcandidate->username));
1502                         ast_copy_string(newcandidate->password,
1503                                 S_OR(iks_find_attrib(traversenodes, "password"), ""),
1504                                 sizeof(newcandidate->password));
1505                         newcandidate->preference = atof(iks_find_attrib(traversenodes, "preference"));
1506                         if (!strcasecmp(S_OR(iks_find_attrib(traversenodes, "protocol"), ""), "udp"))
1507                                 newcandidate->protocol = AJI_PROTOCOL_UDP;
1508                         if (!strcasecmp(S_OR(iks_find_attrib(traversenodes, "protocol"), ""), "ssltcp"))
1509                                 newcandidate->protocol = AJI_PROTOCOL_SSLTCP;
1510
1511                         if (!strcasecmp(S_OR(iks_find_attrib(traversenodes, "type"), ""), "stun"))
1512                                 newcandidate->type = AJI_CONNECT_STUN;
1513                         if (!strcasecmp(S_OR(iks_find_attrib(traversenodes, "type"), ""), "local"))
1514                                 newcandidate->type = AJI_CONNECT_LOCAL;
1515                         if (!strcasecmp(S_OR(iks_find_attrib(traversenodes, "type"), ""), "relay"))
1516                                 newcandidate->type = AJI_CONNECT_RELAY;
1517                         ast_copy_string(newcandidate->network,
1518                                 S_OR(iks_find_attrib(traversenodes, "network"), ""),
1519                                 sizeof(newcandidate->network));
1520                         newcandidate->generation = atoi(S_OR(iks_find_attrib(traversenodes, "generation"), "0"));
1521                         newcandidate->next = NULL;
1522
1523                         newcandidate->next = p->theircandidates;
1524                         p->theircandidates = newcandidate;
1525                         p->laststun = 0;
1526                         gtalk_update_stun(p->parent, p);
1527                         newcandidate = NULL;
1528                 }
1529                 traversenodes = iks_next_tag(traversenodes);
1530         }
1531
1532         receipt = iks_new("iq");
1533         iks_insert_attrib(receipt, "type", "result");
1534         iks_insert_attrib(receipt, "from", from);
1535         iks_insert_attrib(receipt, "to", S_OR(iks_find_attrib(pak->x, "from"), ""));
1536         iks_insert_attrib(receipt, "id", S_OR(iks_find_attrib(pak->x, "id"), ""));
1537         ast_aji_send(c, receipt);
1538
1539         iks_delete(receipt);
1540
1541         return 1;
1542 }
1543
1544 static struct ast_frame *gtalk_rtp_read(struct ast_channel *ast, struct gtalk_pvt *p)
1545 {
1546         struct ast_frame *f;
1547
1548         if (!p->rtp) {
1549                 return &ast_null_frame;
1550         }
1551         f = ast_rtp_instance_read(p->rtp, 0);
1552         gtalk_update_stun(p->parent, p);
1553         if (p->owner) {
1554                 /* We already hold the channel lock */
1555                 if (f->frametype == AST_FRAME_VOICE) {
1556                         if (f->subclass.codec != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
1557                                 ast_debug(1, "Oooh, format changed to %s\n", ast_getformatname(f->subclass.codec));
1558                                 p->owner->nativeformats =
1559                                         (p->owner->nativeformats & AST_FORMAT_VIDEO_MASK) | f->subclass.codec;
1560                                 ast_set_read_format(p->owner, p->owner->readformat);
1561                                 ast_set_write_format(p->owner, p->owner->writeformat);
1562                         }
1563                         /* if ((ast_test_flag(p, SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
1564                                 f = ast_dsp_process(p->owner, p->vad, f);
1565                                 if (option_debug && f && (f->frametype == AST_FRAME_DTMF))
1566                                         ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass);
1567                 } */
1568                 }
1569         }
1570         return f;
1571 }
1572
1573 static struct ast_frame *gtalk_read(struct ast_channel *ast)
1574 {
1575         struct ast_frame *fr;
1576         struct gtalk_pvt *p = ast->tech_pvt;
1577
1578         ast_mutex_lock(&p->lock);
1579         fr = gtalk_rtp_read(ast, p);
1580         ast_mutex_unlock(&p->lock);
1581         return fr;
1582 }
1583
1584 /*! \brief Send frame to media channel (rtp) */
1585 static int gtalk_write(struct ast_channel *ast, struct ast_frame *frame)
1586 {
1587         struct gtalk_pvt *p = ast->tech_pvt;
1588         int res = 0;
1589         char buf[256];
1590
1591         switch (frame->frametype) {
1592         case AST_FRAME_VOICE:
1593                 if (!(frame->subclass.codec & ast->nativeformats)) {
1594                         ast_log(LOG_WARNING,
1595                                         "Asked to transmit frame type %s, while native formats is %s (read/write = %s/%s)\n",
1596                                         ast_getformatname(frame->subclass.codec),
1597                                         ast_getformatname_multiple(buf, sizeof(buf), ast->nativeformats),
1598                                         ast_getformatname(ast->readformat),
1599                                         ast_getformatname(ast->writeformat));
1600                         return 0;
1601                 }
1602                 if (p) {
1603                         ast_mutex_lock(&p->lock);
1604                         if (p->rtp) {
1605                                 res = ast_rtp_instance_write(p->rtp, frame);
1606                         }
1607                         ast_mutex_unlock(&p->lock);
1608                 }
1609                 break;
1610         case AST_FRAME_VIDEO:
1611                 if (p) {
1612                         ast_mutex_lock(&p->lock);
1613                         if (p->vrtp) {
1614                                 res = ast_rtp_instance_write(p->vrtp, frame);
1615                         }
1616                         ast_mutex_unlock(&p->lock);
1617                 }
1618                 break;
1619         case AST_FRAME_IMAGE:
1620                 return 0;
1621                 break;
1622         default:
1623                 ast_log(LOG_WARNING, "Can't send %d type frames with Gtalk write\n",
1624                                 frame->frametype);
1625                 return 0;
1626         }
1627
1628         return res;
1629 }
1630
1631 static int gtalk_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1632 {
1633         struct gtalk_pvt *p = newchan->tech_pvt;
1634         ast_mutex_lock(&p->lock);
1635
1636         if ((p->owner != oldchan)) {
1637                 ast_mutex_unlock(&p->lock);
1638                 return -1;
1639         }
1640         if (p->owner == oldchan)
1641                 p->owner = newchan;
1642         ast_mutex_unlock(&p->lock);
1643         return 0;
1644 }
1645
1646 static int gtalk_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
1647 {
1648         int res = 0;
1649
1650         switch (condition) {
1651         case AST_CONTROL_HOLD:
1652                 ast_moh_start(ast, data, NULL);
1653                 break;
1654         case AST_CONTROL_UNHOLD:
1655                 ast_moh_stop(ast);
1656                 break;
1657         default:
1658                 ast_log(LOG_NOTICE, "Don't know how to indicate condition '%d'\n", condition);
1659                 res = -1;
1660         }
1661
1662         return res;
1663 }
1664
1665 static int gtalk_sendtext(struct ast_channel *chan, const char *text)
1666 {
1667         int res = 0;
1668         struct aji_client *client = NULL;
1669         struct gtalk_pvt *p = chan->tech_pvt;
1670
1671         if (!p->parent) {
1672                 ast_log(LOG_ERROR, "Parent channel not found\n");
1673                 return -1;
1674         }
1675         if (!p->parent->connection) {
1676                 ast_log(LOG_ERROR, "XMPP client not found\n");
1677                 return -1;
1678         }
1679         client = p->parent->connection;
1680         res = ast_aji_send_chat(client, p->them, text);
1681         return res;
1682 }
1683
1684 static int gtalk_digit_begin(struct ast_channel *chan, char digit)
1685 {
1686         struct gtalk_pvt *p = chan->tech_pvt;
1687         int res = 0;
1688
1689         ast_mutex_lock(&p->lock);
1690         if (p->rtp) {
1691                 ast_rtp_instance_dtmf_begin(p->rtp, digit);
1692         } else {
1693                 res = -1;
1694         }
1695         ast_mutex_unlock(&p->lock);
1696
1697         return res;
1698 }
1699
1700 static int gtalk_digit_end(struct ast_channel *chan, char digit, unsigned int duration)
1701 {
1702         struct gtalk_pvt *p = chan->tech_pvt;
1703         int res = 0;
1704
1705         ast_mutex_lock(&p->lock);
1706         if (p->rtp) {
1707                 ast_rtp_instance_dtmf_end_with_duration(p->rtp, digit, duration);
1708         } else {
1709                 res = -1;
1710         }
1711         ast_mutex_unlock(&p->lock);
1712
1713         return res;
1714 }
1715
1716 /* This function is of not in use at the moment, but I am choosing to leave this
1717  * within the code base as a reference to how DTMF is possible through
1718  * jingle signaling.  However, google currently does DTMF through the RTP. */
1719 #if 0
1720 static int gtalk_digit(struct ast_channel *ast, char digit, unsigned int duration)
1721 {
1722         struct gtalk_pvt *p = ast->tech_pvt;
1723         struct gtalk *client = p->parent;
1724         iks *iq, *gtalk, *dtmf;
1725         char buffer[2] = {digit, '\0'};
1726         char *lowerthem = NULL;
1727         iq = iks_new("iq");
1728         gtalk = iks_new("gtalk");
1729         dtmf = iks_new("dtmf");
1730         if(!iq || !gtalk || !dtmf) {
1731                 iks_delete(iq);
1732                 iks_delete(gtalk);
1733                 iks_delete(dtmf);
1734                 ast_log(LOG_ERROR, "Did not send dtmf do to memory issue\n");
1735                 return -1;
1736         }
1737
1738         iks_insert_attrib(iq, "type", "set");
1739         iks_insert_attrib(iq, "to", p->them);
1740         iks_insert_attrib(iq, "from", p->us);
1741         iks_insert_attrib(iq, "id", client->connection->mid);
1742         ast_aji_increment_mid(client->connection->mid);
1743         iks_insert_attrib(gtalk, "xmlns", "http://jabber.org/protocol/gtalk");
1744         iks_insert_attrib(gtalk, "action", "session-info");
1745         // put the initiator attribute to lower case if we receive the call
1746         // otherwise GoogleTalk won't establish the session
1747         if (!p->initiator) {
1748                 char c;
1749                 char *t = lowerthem = ast_strdupa(p->them);
1750                 while (((c = *t) != '/') && (*t++ = tolower(c)));
1751         }
1752         iks_insert_attrib(gtalk, "initiator", p->initiator ? p->us: lowerthem);
1753         iks_insert_attrib(gtalk, "sid", p->sid);
1754         iks_insert_attrib(dtmf, "xmlns", "http://jabber.org/protocol/gtalk/info/dtmf");
1755         iks_insert_attrib(dtmf, "code", buffer);
1756         iks_insert_node(iq, gtalk);
1757         iks_insert_node(gtalk, dtmf);
1758
1759         ast_mutex_lock(&p->lock);
1760         if (ast->dtmff.frametype == AST_FRAME_DTMF_BEGIN || duration == 0) {
1761                 iks_insert_attrib(dtmf, "action", "button-down");
1762         } else if (ast->dtmff.frametype == AST_FRAME_DTMF_END || duration != 0) {
1763                 iks_insert_attrib(dtmf, "action", "button-up");
1764         }
1765         ast_aji_send(client->connection, iq);
1766
1767         iks_delete(iq);
1768         iks_delete(gtalk);
1769         iks_delete(dtmf);
1770         ast_mutex_unlock(&p->lock);
1771         return 0;
1772 }
1773 #endif
1774
1775 static int gtalk_sendhtml(struct ast_channel *ast, int subclass, const char *data, int datalen)
1776 {
1777         ast_log(LOG_NOTICE, "XXX Implement gtalk sendhtml XXX\n");
1778
1779         return -1;
1780 }
1781
1782 /* Not in use right now.
1783 static int gtalk_auto_congest(void *nothing)
1784 {
1785         struct gtalk_pvt *p = nothing;
1786
1787         ast_mutex_lock(&p->lock);
1788         if (p->owner) {
1789                 if (!ast_channel_trylock(p->owner)) {
1790                         ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
1791                         ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
1792                         ast_channel_unlock(p->owner);
1793                 }
1794         }
1795         ast_mutex_unlock(&p->lock);
1796         return 0;
1797 }
1798 */
1799
1800 /*!\brief Initiate new call, part of PBX interface
1801  * dest is the dial string */
1802 static int gtalk_call(struct ast_channel *ast, char *dest, int timeout)
1803 {
1804         struct gtalk_pvt *p = ast->tech_pvt;
1805
1806         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
1807                 ast_log(LOG_WARNING, "gtalk_call called on %s, neither down nor reserved\n", ast->name);
1808                 return -1;
1809         }
1810
1811         ast_setstate(ast, AST_STATE_RING);
1812         if (!p->ringrule) {
1813                 ast_copy_string(p->ring, p->parent->connection->mid, sizeof(p->ring));
1814                 p->ringrule = iks_filter_add_rule(p->parent->connection->f, gtalk_ringing_ack, p,
1815                                                         IKS_RULE_ID, p->ring, IKS_RULE_DONE);
1816         } else
1817                 ast_log(LOG_WARNING, "Whoa, already have a ring rule!\n");
1818
1819         gtalk_invite(p, p->them, p->us, p->sid, 1);
1820         gtalk_create_candidates(p->parent, p, p->sid, p->them, p->us);
1821
1822         return 0;
1823 }
1824
1825 /*! \brief Hangup a call through the gtalk proxy channel */
1826 static int gtalk_hangup(struct ast_channel *ast)
1827 {
1828         struct gtalk_pvt *p = ast->tech_pvt;
1829         struct gtalk *client;
1830
1831         ast_mutex_lock(&p->lock);
1832         client = p->parent;
1833         p->owner = NULL;
1834         ast->tech_pvt = NULL;
1835         if (!p->alreadygone) {
1836                 gtalk_action(client, p, "terminate");
1837         }
1838         ast_mutex_unlock(&p->lock);
1839
1840         gtalk_free_pvt(client, p);
1841         ast_module_unref(ast_module_info->self);
1842
1843         return 0;
1844 }
1845
1846 /*!\brief Part of PBX interface */
1847 static struct ast_channel *gtalk_request(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause)
1848 {
1849         struct gtalk_pvt *p = NULL;
1850         struct gtalk *client = NULL;
1851         char *sender = NULL, *to = NULL, *s = NULL;
1852         struct ast_channel *chan = NULL;
1853
1854         if (data) {
1855                 s = ast_strdupa(data);
1856                 if (s) {
1857                         sender = strsep(&s, "/");
1858                         if (sender && (sender[0] != '\0'))
1859                                 to = strsep(&s, "/");
1860                         if (!to) {
1861                                 ast_log(LOG_ERROR, "Bad arguments in Gtalk Dialstring: %s\n", (char*) data);
1862                                 return NULL;
1863                         }
1864                 }
1865         }
1866
1867         client = find_gtalk(to, sender);
1868         if (!client) {
1869                 ast_log(LOG_WARNING, "Could not find recipient.\n");
1870                 return NULL;
1871         }
1872         if (!strcasecmp(client->name, "guest")){
1873                 /* the guest account is not tied to any configured XMPP client,
1874                    let's set it now */
1875                 client->connection = ast_aji_get_client(sender);
1876                 if (!client->connection) {
1877                         ast_log(LOG_ERROR, "No XMPP client to talk to, us (partial JID) : %s\n", sender);
1878                         ASTOBJ_UNREF(client, gtalk_member_destroy);
1879                         return NULL;
1880                 }
1881         }
1882
1883         ASTOBJ_WRLOCK(client);
1884         p = gtalk_alloc(client, strchr(sender, '@') ? sender : client->connection->jid->full, strchr(to, '@') ? to : client->user, NULL);
1885         if (p) {
1886                 chan = gtalk_new(client, p, AST_STATE_DOWN, to, requestor ? requestor->linkedid : NULL);
1887         }
1888         ASTOBJ_UNLOCK(client);
1889         return chan;
1890 }
1891
1892 /*! \brief CLI command "gtalk show channels" */
1893 static char *gtalk_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1894 {
1895 #define FORMAT  "%-30.30s  %-30.30s  %-15.15s  %-5.5s %-5.5s \n"
1896         struct gtalk_pvt *p;
1897         struct ast_channel *chan;
1898         int numchans = 0;
1899         char them[AJI_MAX_JIDLEN];
1900         char *jid = NULL;
1901         char *resource = NULL;
1902
1903         switch (cmd) {
1904         case CLI_INIT:
1905                 e->command = "gtalk show channels";
1906                 e->usage =
1907                         "Usage: gtalk show channels\n"
1908                         "       Shows current state of the Gtalk channels.\n";
1909                 return NULL;
1910         case CLI_GENERATE:
1911                 return NULL;
1912         }
1913
1914         if (a->argc != 3)
1915                 return CLI_SHOWUSAGE;
1916
1917         ast_mutex_lock(&gtalklock);
1918         ast_cli(a->fd, FORMAT, "Channel", "Jabber ID", "Resource", "Read", "Write");
1919         ASTOBJ_CONTAINER_TRAVERSE(&gtalk_list, 1, {
1920                 ASTOBJ_WRLOCK(iterator);
1921                 p = iterator->p;
1922                 while(p) {
1923                         chan = p->owner;
1924                         ast_copy_string(them, p->them, sizeof(them));
1925                         jid = them;
1926                         resource = strchr(them, '/');
1927                         if (!resource)
1928                                 resource = "None";
1929                         else {
1930                                 *resource = '\0';
1931                                 resource ++;
1932                         }
1933                         if (chan)
1934                                 ast_cli(a->fd, FORMAT,
1935                                         chan->name,
1936                                         jid,
1937                                         resource,
1938                                         ast_getformatname(chan->readformat),
1939                                         ast_getformatname(chan->writeformat)
1940                                         );
1941                         else
1942                                 ast_log(LOG_WARNING, "No available channel\n");
1943                         numchans ++;
1944                         p = p->next;
1945                 }
1946                 ASTOBJ_UNLOCK(iterator);
1947         });
1948
1949         ast_mutex_unlock(&gtalklock);
1950
1951         ast_cli(a->fd, "%d active gtalk channel%s\n", numchans, (numchans != 1) ? "s" : "");
1952         return CLI_SUCCESS;
1953 #undef FORMAT
1954 }
1955
1956 /*! \brief CLI command "gtalk reload"
1957  *  \todo XXX TODO make this work. */
1958 #if 0
1959 static char *gtalk_do_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1960 {
1961         switch (cmd) {
1962         case CLI_INIT:
1963                 e->command = "gtalk reload";
1964                 e->usage =
1965                         "Usage: gtalk reload\n"
1966                         "       Reload gtalk channel driver.\n";
1967                 return NULL;
1968         case CLI_GENERATE:
1969                 return NULL;
1970         }
1971
1972         ast_verbose("IT DOES WORK!\n");
1973         return CLI_SUCCESS;
1974 }
1975 #endif
1976
1977 static int gtalk_parser(void *data, ikspak *pak)
1978 {
1979         struct gtalk *client = ASTOBJ_REF((struct gtalk *) data);
1980         int res;
1981
1982         if (!strcmp(S_OR(iks_find_attrib(pak->x, "type"), ""), "error")) {
1983                 ast_log(LOG_NOTICE, "Remote peer reported an error, trying to establish the call anyway\n");
1984         }
1985
1986         if (ast_strlen_zero(iks_find_attrib(pak->query, "type"))) {
1987                 ast_log(LOG_NOTICE, "No attribute \"type\" found.  Ignoring message.\n");
1988         } else if (!strcmp(iks_find_attrib(pak->query, "type"), "initiate")) {
1989                 /* New call */
1990                 gtalk_newcall(client, pak);
1991         } else if (!strcmp(iks_find_attrib(pak->query, "type"), "candidates") || !strcmp(iks_find_attrib(pak->query, "type"), "transport-info")) {
1992                 ast_debug(3, "About to add candidate!\n");
1993                 res = gtalk_add_candidate(client, pak);
1994                 if (!res) {
1995                         ast_log(LOG_WARNING, "Could not add any candidate\n");
1996                 } else {
1997                         ast_debug(3, "Candidate Added!\n");
1998                 }
1999         } else if (!strcmp(iks_find_attrib(pak->query, "type"), "accept")) {
2000                 gtalk_is_answered(client, pak);
2001         } else if (!strcmp(iks_find_attrib(pak->query, "type"), "transport-accept")) {
2002                 gtalk_is_accepted(client, pak);
2003         } else if (!strcmp(iks_find_attrib(pak->query, "type"), "content-info") || iks_find_with_attrib(pak->x, "gtalk", "action", "session-info")) {
2004                 gtalk_handle_dtmf(client, pak);
2005         } else if (!strcmp(iks_find_attrib(pak->query, "type"), "terminate")) {
2006                 gtalk_hangup_farend(client, pak);
2007         } else if (!strcmp(iks_find_attrib(pak->query, "type"), "reject")) {
2008                 gtalk_hangup_farend(client, pak);
2009         }
2010         ASTOBJ_UNREF(client, gtalk_member_destroy);
2011         return IKS_FILTER_EAT;
2012 }
2013
2014 static int gtalk_create_member(char *label, struct ast_variable *var, int allowguest,
2015                                                                 struct ast_codec_pref prefs, char *context,
2016                                                                 struct gtalk *member)
2017 {
2018         struct aji_client *client;
2019
2020         if (!member)
2021                 ast_log(LOG_WARNING, "Out of memory.\n");
2022
2023         ast_copy_string(member->name, label, sizeof(member->name));
2024         ast_copy_string(member->user, label, sizeof(member->user));
2025         ast_copy_string(member->context, context, sizeof(member->context));
2026         member->allowguest = allowguest;
2027         member->prefs = prefs;
2028         while (var) {
2029                 if (!strcasecmp(var->name, "username"))
2030                         ast_copy_string(member->user, var->value, sizeof(member->user));
2031                 else if (!strcasecmp(var->name, "disallow"))
2032                         ast_parse_allow_disallow(&member->prefs, &member->capability, var->value, 0);
2033                 else if (!strcasecmp(var->name, "allow"))
2034                         ast_parse_allow_disallow(&member->prefs, &member->capability, var->value, 1);
2035                 else if (!strcasecmp(var->name, "context"))
2036                         ast_copy_string(member->context, var->value, sizeof(member->context));
2037                 else if (!strcasecmp(var->name, "parkinglot"))
2038                         ast_copy_string(member->parkinglot, var->value, sizeof(member->parkinglot));
2039                 else if (!strcasecmp(var->name, "connection")) {
2040                         if ((client = ast_aji_get_client(var->value))) {
2041                                 member->connection = client;
2042                                 iks_filter_add_rule(client->f, gtalk_parser, member,
2043                                                     IKS_RULE_TYPE, IKS_PAK_IQ,
2044                                                     IKS_RULE_FROM_PARTIAL, member->user,
2045                                                     IKS_RULE_NS, GOOGLE_NS,
2046                                                     IKS_RULE_DONE);
2047                         } else {
2048                                 ast_log(LOG_ERROR, "connection referenced not found!\n");
2049                                 return 0;
2050                         }
2051                 }
2052                 var = var->next;
2053         }
2054         if (member->connection && member->user)
2055                 member->buddy = ASTOBJ_CONTAINER_FIND(&member->connection->buddies, member->user);
2056         else {
2057                 ast_log(LOG_ERROR, "No Connection or Username!\n");
2058         }
2059         return 1;
2060 }
2061
2062 static int gtalk_load_config(void)
2063 {
2064         char *cat = NULL;
2065         struct ast_config *cfg = NULL;
2066         char context[AST_MAX_CONTEXT];
2067         char parkinglot[AST_MAX_CONTEXT];
2068         int allowguest = 1;
2069         struct ast_variable *var;
2070         struct gtalk *member;
2071         struct ast_codec_pref prefs;
2072         struct aji_client_container *clients;
2073         struct gtalk_candidate *global_candidates = NULL;
2074         struct hostent *hp;
2075         struct ast_hostent ahp;
2076         struct ast_flags config_flags = { 0 };
2077
2078         cfg = ast_config_load(GOOGLE_CONFIG, config_flags);
2079         if (!cfg) {
2080                 return 0;
2081         } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2082                 ast_log(LOG_ERROR, "Config file %s is in an invalid format.  Aborting.\n", GOOGLE_CONFIG);
2083                 return 0;
2084         }
2085
2086         /* Copy the default jb config over global_jbconf */
2087         memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
2088
2089         /* set defaults */
2090         memset(&stunaddr, 0, sizeof(stunaddr));
2091
2092         cat = ast_category_browse(cfg, NULL);
2093         for (var = ast_variable_browse(cfg, "general"); var; var = var->next) {
2094                 /* handle jb conf */
2095                 if (!ast_jb_read_conf(&global_jbconf, var->name, var->value))
2096                         continue;
2097
2098                 if (!strcasecmp(var->name, "allowguest")) {
2099                         allowguest = (ast_true(ast_variable_retrieve(cfg, "general", "allowguest"))) ? 1 : 0;
2100                 } else if (!strcasecmp(var->name, "disallow")) {
2101                         ast_parse_allow_disallow(&prefs, &global_capability, var->value, 0);
2102                 } else if (!strcasecmp(var->name, "allow")) {
2103                         ast_parse_allow_disallow(&prefs, &global_capability, var->value, 1);
2104                 } else if (!strcasecmp(var->name, "context")) {
2105                         ast_copy_string(context, var->value, sizeof(context));
2106                 } else if (!strcasecmp(var->name, "externip")) {
2107                         ast_copy_string(externip, var->value, sizeof(externip));
2108                 } else if (!strcasecmp(var->name, "parkinglot")) {
2109                         ast_copy_string(parkinglot, var->value, sizeof(parkinglot));
2110                 } else if (!strcasecmp(var->name, "bindaddr")) {
2111                         if (!(hp = ast_gethostbyname(var->value, &ahp))) {
2112                                 ast_log(LOG_WARNING, "Invalid address: %s\n", var->value);
2113                         } else {
2114                                 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
2115                         }
2116                 } else if (!strcasecmp(var->name, "stunaddr")) {
2117                         stunaddr.sin_port = htons(STANDARD_STUN_PORT);
2118                         if (ast_parse_arg(var->value, PARSE_INADDR, &stunaddr)) {
2119                                 ast_log(LOG_WARNING, "Invalid STUN server address: %s\n", var->value);
2120                         }
2121                 }
2122         }
2123         while (cat) {
2124                 if (strcasecmp(cat, "general")) {
2125                         var = ast_variable_browse(cfg, cat);
2126                         member = ast_calloc(1, sizeof(*member));
2127                         ASTOBJ_INIT(member);
2128                         ASTOBJ_WRLOCK(member);
2129                         if (!strcasecmp(cat, "guest")) {
2130                                 ast_copy_string(member->name, "guest", sizeof(member->name));
2131                                 ast_copy_string(member->user, "guest", sizeof(member->user));
2132                                 ast_copy_string(member->context, context, sizeof(member->context));
2133                                 ast_copy_string(member->parkinglot, parkinglot, sizeof(member->parkinglot));
2134                                 member->allowguest = allowguest;
2135                                 member->prefs = prefs;
2136                                 while (var) {
2137                                         if (!strcasecmp(var->name, "disallow")) {
2138                                                 ast_parse_allow_disallow(&member->prefs, &member->capability,
2139                                                                                                  var->value, 0);
2140                                         } else if (!strcasecmp(var->name, "allow")) {
2141                                                 ast_parse_allow_disallow(&member->prefs, &member->capability,
2142                                                                                                  var->value, 1);
2143                                         } else if (!strcasecmp(var->name, "context")) {
2144                                                 ast_copy_string(member->context, var->value,
2145                                                                                 sizeof(member->context));
2146                                         } else if (!strcasecmp(var->name, "parkinglot")) {
2147                                                 ast_copy_string(member->parkinglot, var->value,
2148                                                                                 sizeof(member->parkinglot));
2149                                         }
2150                                         var = var->next;
2151                                 }
2152                                 ASTOBJ_UNLOCK(member);
2153                                 clients = ast_aji_get_clients();
2154                                 if (clients) {
2155                                         ASTOBJ_CONTAINER_TRAVERSE(clients, 1, {
2156                                                 ASTOBJ_WRLOCK(iterator);
2157                                                 ASTOBJ_WRLOCK(member);
2158                                                 member->connection = NULL;
2159                                                 iks_filter_add_rule(iterator->f, gtalk_parser, member, IKS_RULE_TYPE, IKS_PAK_IQ, IKS_RULE_NS, GOOGLE_NS, IKS_RULE_DONE);
2160                                                 iks_filter_add_rule(iterator->f, gtalk_parser, member, IKS_RULE_TYPE, IKS_PAK_IQ, IKS_RULE_NS, "http://jabber.org/protocol/gtalk", IKS_RULE_DONE);
2161                                                 ASTOBJ_UNLOCK(member);
2162                                                 ASTOBJ_UNLOCK(iterator);
2163                                         });
2164                                         ASTOBJ_CONTAINER_LINK(&gtalk_list, member);
2165                                         ASTOBJ_UNREF(member, gtalk_member_destroy);
2166                                 } else {
2167                                         ASTOBJ_UNLOCK(member);
2168                                         ASTOBJ_UNREF(member, gtalk_member_destroy);
2169                                 }
2170                         } else {
2171                                 ASTOBJ_UNLOCK(member);
2172                                 if (gtalk_create_member(cat, var, allowguest, prefs, context, member))
2173                                         ASTOBJ_CONTAINER_LINK(&gtalk_list, member);
2174                                 ASTOBJ_UNREF(member, gtalk_member_destroy);
2175                         }
2176                 }
2177                 cat = ast_category_browse(cfg, cat);
2178         }
2179
2180         gtalk_update_externip();
2181         gtalk_free_candidates(global_candidates);
2182         return 1;
2183 }
2184
2185 /*! \brief Load module into PBX, register channel */
2186 static int load_module(void)
2187 {
2188         struct ast_sockaddr bindaddr_tmp;
2189         struct ast_sockaddr ourip_tmp;
2190
2191         char *jabber_loaded = ast_module_helper("", "res_jabber.so", 0, 0, 0, 0);
2192         free(jabber_loaded);
2193         if (!jabber_loaded) {
2194                 /* If embedded, check for a different module name */
2195                 jabber_loaded = ast_module_helper("", "res_jabber", 0, 0, 0, 0);
2196                 free(jabber_loaded);
2197                 if (!jabber_loaded) {
2198                         ast_log(LOG_ERROR, "chan_gtalk.so depends upon res_jabber.so\n");
2199                         return AST_MODULE_LOAD_DECLINE;
2200                 }
2201         }
2202
2203         ASTOBJ_CONTAINER_INIT(&gtalk_list);
2204         if (!gtalk_load_config()) {
2205                 ast_log(LOG_ERROR, "Unable to read config file %s. Not loading module.\n", GOOGLE_CONFIG);
2206                 return 0;
2207         }
2208
2209         sched = sched_context_create();
2210         if (!sched) {
2211                 ast_log(LOG_WARNING, "Unable to create schedule context\n");
2212         }
2213
2214         io = io_context_create();
2215         if (!io) {
2216                 ast_log(LOG_WARNING, "Unable to create I/O context\n");
2217         }
2218
2219         ast_sockaddr_from_sin(&bindaddr_tmp, &bindaddr);
2220         if (ast_find_ourip(&ourip_tmp, &bindaddr_tmp)) {
2221                 ast_log(LOG_WARNING, "Unable to get own IP address, Gtalk disabled\n");
2222                 return 0;
2223         }
2224         __ourip.s_addr = htonl(ast_sockaddr_ipv4(&ourip_tmp));
2225
2226         ast_rtp_glue_register(&gtalk_rtp_glue);
2227         ast_cli_register_multiple(gtalk_cli, ARRAY_LEN(gtalk_cli));
2228
2229         /* Make sure we can register our channel type */
2230         if (ast_channel_register(&gtalk_tech)) {
2231                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", gtalk_tech.type);
2232                 return -1;
2233         }
2234         return 0;
2235 }
2236
2237 /*! \brief Reload module
2238  *  \todo XXX TODO make this work. */
2239 #if 0
2240 static int reload(void)
2241 {
2242         return 0;
2243 }
2244 #endif
2245 /*! \brief Unload the gtalk channel from Asterisk */
2246 static int unload_module(void)
2247 {
2248         struct gtalk_pvt *privates = NULL;
2249         ast_cli_unregister_multiple(gtalk_cli, ARRAY_LEN(gtalk_cli));
2250         /* First, take us out of the channel loop */
2251         ast_channel_unregister(&gtalk_tech);
2252         ast_rtp_glue_unregister(&gtalk_rtp_glue);
2253
2254         if (!ast_mutex_lock(&gtalklock)) {
2255                 /* Hangup all interfaces if they have an owner */
2256                 ASTOBJ_CONTAINER_TRAVERSE(&gtalk_list, 1, {
2257                         ASTOBJ_WRLOCK(iterator);
2258                         privates = iterator->p;
2259                         while(privates) {
2260                                 if (privates->owner)
2261                                         ast_softhangup(privates->owner, AST_SOFTHANGUP_APPUNLOAD);
2262                                 privates = privates->next;
2263                         }
2264                         iterator->p = NULL;
2265                         ASTOBJ_UNLOCK(iterator);
2266                 });
2267                 ast_mutex_unlock(&gtalklock);
2268         } else {
2269                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
2270                 return -1;
2271         }
2272         ASTOBJ_CONTAINER_DESTROYALL(&gtalk_list, gtalk_member_destroy);
2273         ASTOBJ_CONTAINER_DESTROY(&gtalk_list);
2274         return 0;
2275 }
2276
2277 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Gtalk Channel Driver",
2278                 .load = load_module,
2279                 .unload = unload_module,
2280                 /* .reload = reload, */
2281                 .load_pri = AST_MODPRI_CHANNEL_DRIVER,
2282                );