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