bfa79e454749325f63c7745b3855100f3fa9a96f
[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 (i->rtp)
817                 ast_jb_configure(tmp, &global_jbconf);
818         if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
819                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
820                 tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
821                 ast_hangup(tmp);
822                 tmp = NULL;
823         }
824
825         return tmp;
826 }
827
828 static int jingle_action(struct jingle *client, struct jingle_pvt *p, const char *action)
829 {
830         iks *request, *session = NULL;
831         int res = -1;
832
833         request = iks_new("iq");
834         if (request) {
835                 iks_insert_attrib(request, "type", "set");
836                 iks_insert_attrib(request, "from", client->connection->jid->full);
837                 iks_insert_attrib(request, "to", p->from);
838                 iks_insert_attrib(request, "id", client->connection->mid);
839                 ast_aji_increment_mid(client->connection->mid);
840                 session = iks_new("session");
841                 if (session) {
842                         iks_insert_attrib(session, "type", action);
843                         iks_insert_attrib(session, "id", p->sid);
844                         iks_insert_attrib(session, "initiator",
845                                                           p->initiator ? client->connection->jid->full : p->from);
846                         iks_insert_attrib(session, "xmlns", "http://www.google.com/session");
847                         iks_insert_node(request, session);
848                         iks_send(client->connection->p, request);
849                         iks_delete(session);
850                         res = 0;
851                 }
852                 iks_delete(request);
853         }
854         return res;
855 }
856
857 static void jingle_free_candidates(struct jingle_candidate *candidate)
858 {
859         struct jingle_candidate *last;
860         while (candidate) {
861                 last = candidate;
862                 candidate = candidate->next;
863                 free(last);
864         }
865 }
866
867 static void jingle_free_pvt(struct jingle *client, struct jingle_pvt *p)
868 {
869         struct jingle_pvt *cur, *prev = NULL;
870         cur = client->p;
871         while (cur) {
872                 if (cur == p) {
873                         if (prev)
874                                 prev->next = p->next;
875                         else
876                                 client->p = p->next;
877                         break;
878                 }
879                 prev = cur;
880                 cur = cur->next;
881         }
882         if (p->ringrule)
883                 iks_filter_remove_rule(p->parent->connection->f, p->ringrule);
884         if (p->owner)
885                 ast_log(LOG_WARNING, "Uh oh, there's an owner, this is going to be messy.\n");
886         if (p->rtp)
887                 ast_rtp_destroy(p->rtp);
888         if (p->vrtp)
889                 ast_rtp_destroy(p->vrtp);
890         jingle_free_candidates(p->theircandidates);
891         free(p);
892 }
893
894
895 static int jingle_newcall(struct jingle *client, ikspak *pak)
896 {
897         struct jingle_pvt *p, *tmp = client->p;
898         struct ast_channel *chan;
899         int res;
900         iks *codec;
901
902         /* Make sure our new call doesn't exist yet */
903         while (tmp) {
904                 if (iks_find_with_attrib(pak->x, GOOGLE_NODE, GOOGLE_SID, tmp->sid)) {
905                         ast_log(LOG_NOTICE, "Ignoring duplicate call setup on SID %s\n", tmp->sid);
906                         jingle_response(client, pak, "out-of-order", NULL);
907                         return -1;
908                 }
909                 tmp = tmp->next;
910         }
911
912         p = jingle_alloc(client, pak->from->partial, iks_find_attrib(pak->query, GOOGLE_SID));
913         if (!p) {
914                 ast_log(LOG_WARNING, "Unable to allocate jingle structure!\n");
915                 return -1;
916         }
917         chan = jingle_new(client, p, AST_STATE_DOWN, pak->from->user);
918         if (chan) {
919                 ast_mutex_lock(&p->lock);
920                 ast_copy_string(p->from, pak->from->full, sizeof(p->from));
921                 if (iks_find_attrib(pak->query, GOOGLE_SID)) {
922                         ast_copy_string(p->sid, iks_find_attrib(pak->query, GOOGLE_SID),
923                                                         sizeof(p->sid));
924                 }
925
926                 codec = iks_child(iks_child(iks_child(pak->x)));
927                 while (codec) {
928                         ast_rtp_set_m_type(p->rtp, atoi(iks_find_attrib(codec, "id")));
929                         ast_rtp_set_rtpmap_type(p->rtp, atoi(iks_find_attrib(codec, "id")), "audio",
930                                                 iks_find_attrib(codec, "name"), 0);
931                         codec = iks_next(codec);
932                 }
933                 
934                 ast_mutex_unlock(&p->lock);
935                 ast_setstate(chan, AST_STATE_RING);
936                 res = ast_pbx_start(chan);
937
938                 switch (res) {
939                 case AST_PBX_FAILED:
940                         ast_log(LOG_WARNING, "Failed to start PBX :(\n");
941                         jingle_response(client, pak, "service-unavailable", NULL);
942                         break;
943                 case AST_PBX_CALL_LIMIT:
944                         ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
945                         jingle_response(client, pak, "service-unavailable", NULL);
946                         break;
947                 case AST_PBX_SUCCESS:
948                         jingle_response(client, pak, NULL, NULL);
949                         jingle_create_candidates(client, p,
950                                         iks_find_attrib(pak->query, GOOGLE_SID),
951                                         iks_find_attrib(pak->x, "from"));
952                         /* nothing to do */
953                         break;
954                 }
955         } else {
956                 jingle_free_pvt(client, p);
957         }
958         return 1;
959 }
960
961 static int jingle_update_stun(struct jingle *client, struct jingle_pvt *p)
962 {
963         struct jingle_candidate *tmp;
964         struct hostent *hp;
965         struct ast_hostent ahp;
966         struct sockaddr_in sin;
967
968         if (time(NULL) == p->laststun)
969                 return 0;
970
971         tmp = p->theircandidates;
972         p->laststun = time(NULL);
973         while (tmp) {
974                 char username[256];
975                 hp = ast_gethostbyname(tmp->ip, &ahp);
976                 sin.sin_family = AF_INET;
977                 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
978                 sin.sin_port = htons(tmp->port);
979                 snprintf(username, sizeof(username), "%s%s", tmp->username,
980                                  p->ourcandidates->username);
981
982                 ast_rtp_stun_request(p->rtp, &sin, username);
983                 tmp = tmp->next;
984         }
985         return 1;
986 }
987
988 static int jingle_add_candidate(struct jingle *client, ikspak *pak)
989 {
990         struct jingle_pvt *p = NULL, *tmp = NULL;
991         struct aji_client *c = client->connection;
992         struct jingle_candidate *newcandidate = NULL;
993         iks  *traversenodes = NULL, *receipt = NULL;
994         newcandidate = ast_calloc(1, sizeof(*newcandidate));
995         if (!newcandidate)
996                 return 0;
997         for (tmp = client->p; tmp; tmp = tmp->next) {
998                 if (iks_find_with_attrib(pak->x, GOOGLE_NODE, GOOGLE_SID, tmp->sid)) {
999                         p = tmp;
1000                         break;
1001                 }
1002         }
1003
1004         if (!p)
1005                 return -1;
1006
1007         traversenodes = pak->query;
1008         while(traversenodes) {
1009                 if(!strcasecmp(iks_name(traversenodes), "session")) {
1010                         traversenodes = iks_child(traversenodes);
1011                         continue;
1012                 }
1013                 if(!strcasecmp(iks_name(traversenodes), "candidate")) {
1014                         newcandidate = ast_calloc(1, sizeof(*newcandidate));
1015                         if (!newcandidate)
1016                                 return 0;
1017                         ast_copy_string(newcandidate->name, iks_find_attrib(traversenodes, "name"),
1018                                                         sizeof(newcandidate->name));
1019                         ast_copy_string(newcandidate->ip, iks_find_attrib(traversenodes, "address"),
1020                                                         sizeof(newcandidate->ip));
1021                         newcandidate->port = atoi(iks_find_attrib(traversenodes, "port"));
1022                         ast_copy_string(newcandidate->username, iks_find_attrib(traversenodes, "username"),
1023                                                         sizeof(newcandidate->username));
1024                         ast_copy_string(newcandidate->password, iks_find_attrib(traversenodes, "password"),
1025                                                         sizeof(newcandidate->password));
1026                         newcandidate->preference = atof(iks_find_attrib(traversenodes, "preference"));
1027                         if (!strcasecmp(iks_find_attrib(traversenodes, "protocol"), "udp"))
1028                                 newcandidate->protocol = AJI_PROTOCOL_UDP;
1029                         if (!strcasecmp(iks_find_attrib(traversenodes, "protocol"), "ssltcp"))
1030                                 newcandidate->protocol = AJI_PROTOCOL_SSLTCP;
1031                 
1032                         if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "stun"))
1033                                 newcandidate->type = AJI_CONNECT_STUN;
1034                         if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "local"))
1035                                 newcandidate->type = AJI_CONNECT_LOCAL;
1036                         if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "relay"))
1037                                 newcandidate->type = AJI_CONNECT_RELAY;
1038                         ast_copy_string(newcandidate->network, iks_find_attrib(traversenodes, "network"),
1039                                                         sizeof(newcandidate->network));
1040                         newcandidate->generation = atoi(iks_find_attrib(traversenodes, "generation"));
1041                         newcandidate->next = NULL;
1042                 
1043                         newcandidate->next = p->theircandidates;
1044                         p->theircandidates = newcandidate;
1045                         p->laststun = 0;
1046                         jingle_update_stun(p->parent, p);
1047                         newcandidate = NULL;
1048                 }
1049                 traversenodes = iks_next(traversenodes);
1050         }
1051         
1052         receipt = iks_new("iq");
1053         iks_insert_attrib(receipt, "type", "result");
1054         iks_insert_attrib(receipt, "from", c->jid->full);
1055         iks_insert_attrib(receipt, "to", iks_find_attrib(pak->x, "from"));
1056         iks_insert_attrib(receipt, "id", iks_find_attrib(pak->x, "id"));
1057         iks_send(c->p, receipt);
1058         iks_delete(receipt);
1059
1060         return 1;
1061 }
1062
1063 static struct ast_frame *jingle_rtp_read(struct ast_channel *ast, struct jingle_pvt *p)
1064 {
1065         struct ast_frame *f;
1066
1067         if (!p->rtp)
1068                 return &ast_null_frame;
1069         f = ast_rtp_read(p->rtp);
1070         jingle_update_stun(p->parent, p);
1071         if (p->owner) {
1072                 /* We already hold the channel lock */
1073                 if (f->frametype == AST_FRAME_VOICE) {
1074                         if (f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
1075                                 if (option_debug)
1076                                         ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
1077                                 p->owner->nativeformats =
1078                                         (p->owner->nativeformats & AST_FORMAT_VIDEO_MASK) | f->subclass;
1079                                 ast_set_read_format(p->owner, p->owner->readformat);
1080                                 ast_set_write_format(p->owner, p->owner->writeformat);
1081                         }
1082 /*                      if ((ast_test_flag(p, SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
1083                                 f = ast_dsp_process(p->owner, p->vad, f);
1084                                 if (option_debug && f && (f->frametype == AST_FRAME_DTMF))
1085                                         ast_log(LOG_DEBUG, "* Detected inband DTMF '%c'\n", f->subclass);
1086                         } */
1087                 }
1088         }
1089         return f;
1090 }
1091
1092 static struct ast_frame *jingle_read(struct ast_channel *ast)
1093 {
1094         struct ast_frame *fr;
1095         struct jingle_pvt *p = ast->tech_pvt;
1096
1097         ast_mutex_lock(&p->lock);
1098         fr = jingle_rtp_read(ast, p);
1099         ast_mutex_unlock(&p->lock);
1100         return fr;
1101 }
1102
1103 /*! \brief Send frame to media channel (rtp) */
1104 static int jingle_write(struct ast_channel *ast, struct ast_frame *frame)
1105 {
1106         struct jingle_pvt *p = ast->tech_pvt;
1107         int res = 0;
1108
1109         switch (frame->frametype) {
1110         case AST_FRAME_VOICE:
1111                 if (!(frame->subclass & ast->nativeformats)) {
1112                         ast_log(LOG_WARNING,
1113                                         "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
1114                                         frame->subclass, ast->nativeformats, ast->readformat,
1115                                         ast->writeformat);
1116                         return 0;
1117                 }
1118                 if (p) {
1119                         ast_mutex_lock(&p->lock);
1120                         if (p->rtp) {
1121                                 res = ast_rtp_write(p->rtp, frame);
1122                         }
1123                         ast_mutex_unlock(&p->lock);
1124                 }
1125                 break;
1126         case AST_FRAME_VIDEO:
1127                 if (p) {
1128                         ast_mutex_lock(&p->lock);
1129                         if (p->vrtp) {
1130                                 res = ast_rtp_write(p->vrtp, frame);
1131                         }
1132                         ast_mutex_unlock(&p->lock);
1133                 }
1134                 break;
1135         case AST_FRAME_IMAGE:
1136                 return 0;
1137                 break;
1138         default:
1139                 ast_log(LOG_WARNING, "Can't send %d type frames with Jingle write\n",
1140                                 frame->frametype);
1141                 return 0;
1142         }
1143
1144         return res;
1145 }
1146
1147 static int jingle_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1148 {
1149         struct jingle_pvt *p = newchan->tech_pvt;
1150         ast_mutex_lock(&p->lock);
1151
1152         if ((p->owner != oldchan)) {
1153                 ast_mutex_unlock(&p->lock);
1154                 return -1;
1155         }
1156         if (p->owner == oldchan)
1157                 p->owner = newchan;
1158         ast_mutex_unlock(&p->lock);
1159         return 0;
1160 }
1161
1162 static int jingle_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
1163 {
1164         int res = 0;
1165
1166         switch (condition) {
1167         case AST_CONTROL_HOLD:
1168                 ast_moh_start(ast, data, NULL);
1169                 break;
1170         case AST_CONTROL_UNHOLD:
1171                 ast_moh_stop(ast);
1172                 break;
1173         default:
1174                 ast_log(LOG_NOTICE, "Don't know how to indicate condition '%d'\n", condition);
1175                 res = -1;
1176         }
1177
1178         return res;
1179 }
1180
1181 static int jingle_digit(struct ast_channel *ast, char digit)
1182 {
1183         struct jingle_pvt *p = ast->tech_pvt;
1184         struct jingle *client = p->parent;
1185         iks *iq, *jingle, *dtmf;
1186         char buffer[2] = {digit, '\0'};
1187         iq = iks_new("iq");
1188         jingle = iks_new("jingle");
1189         dtmf = iks_new("dtmf");
1190         if(!iq || !jingle || !dtmf) {
1191                 if(iq)
1192                         iks_delete(iq);
1193                 if(jingle)
1194                         iks_delete(jingle);
1195                 if(dtmf)
1196                         iks_delete(dtmf);
1197                 ast_log(LOG_ERROR, "Did not send dtmf do to memory issue\n");
1198                 return -1;
1199         }
1200
1201         iks_insert_attrib(iq, "type", "set");
1202         iks_insert_attrib(iq, "to", p->from);
1203         iks_insert_attrib(iq, "from", client->connection->jid->full);
1204         iks_insert_attrib(iq, "id", client->connection->mid);
1205         ast_aji_increment_mid(client->connection->mid);
1206         iks_insert_attrib(jingle, "xmlns", "http://jabber.org/protocol/jingle");
1207         iks_insert_attrib(jingle, "action", "content-info");
1208         iks_insert_attrib(jingle, "initiator", p->initiator ? client->connection->jid->full : p->from);
1209         iks_insert_attrib(jingle, "sid", p->sid);
1210         iks_insert_attrib(dtmf, "xmlns", "http://jabber.org/protocol/jingle/info/dtmf");
1211         iks_insert_attrib(dtmf, "code", buffer);
1212         iks_insert_node(iq, jingle);
1213         iks_insert_node(jingle, dtmf);
1214
1215         ast_mutex_lock(&p->lock);
1216         if(ast->dtmff.frametype == AST_FRAME_DTMF) {
1217                 ast_verbose("Sending 250ms dtmf!\n");
1218         } else if (ast->dtmff.frametype == AST_FRAME_DTMF_BEGIN) {
1219                 iks_insert_attrib(dtmf, "action", "button-down");
1220         } else if (ast->dtmff.frametype == AST_FRAME_DTMF_END) {
1221                 iks_insert_attrib(dtmf, "action", "button-up");
1222         }
1223         iks_send(client->connection->p, iq);
1224         iks_delete(iq);
1225         iks_delete(jingle);
1226         iks_delete(dtmf);
1227         ast_mutex_unlock(&p->lock);
1228         return 0;
1229 }
1230
1231 static int jingle_sendhtml(struct ast_channel *ast, int subclass, const char *data, int datalen)
1232 {
1233         ast_log(LOG_NOTICE, "XXX Implement jingle sendhtml XXX\n");
1234
1235         return -1;
1236 }
1237 static int jingle_transmit_invite(struct jingle_pvt *p)
1238 {
1239         struct jingle *jingle = NULL;
1240         struct aji_client *client = NULL;
1241         iks *iq, *desc, *session;
1242         iks *payload_eg711u, *payload_pcmu;
1243
1244         jingle = p->parent;
1245         client = jingle->connection;
1246         iq = iks_new("iq");
1247         desc = iks_new("description");
1248         session = iks_new("session");
1249         iks_insert_attrib(iq, "type", "set");
1250         iks_insert_attrib(iq, "to", p->from);
1251         iks_insert_attrib(iq, "from", client->jid->full);
1252         iks_insert_attrib(iq, "id", client->mid);
1253         ast_aji_increment_mid(client->mid);
1254         iks_insert_attrib(session, "type", "initiate");
1255         iks_insert_attrib(session, "id", p->sid);
1256         iks_insert_attrib(session, "initiator", client->jid->full);
1257         iks_insert_attrib(session, "xmlns", "http://www.google.com/session");
1258         iks_insert_attrib(desc, "xmlns", "http://www.google.com/session/phone");
1259         payload_pcmu = iks_new("payload-type");
1260         iks_insert_attrib(payload_pcmu, "id", "0");
1261         iks_insert_attrib(payload_pcmu, "name", "PCMU");
1262         payload_eg711u = iks_new("payload-type");
1263         iks_insert_attrib(payload_eg711u, "id", "100");
1264         iks_insert_attrib(payload_eg711u, "name", "EG711U");
1265         iks_insert_node(desc, payload_pcmu);
1266         iks_insert_node(desc, payload_eg711u);
1267         iks_insert_node(iq, session);
1268         iks_insert_node(session, desc);
1269         iks_send(client->p, iq);
1270         iks_delete(iq);
1271         iks_delete(desc);
1272         iks_delete(session);
1273         iks_delete(payload_eg711u);
1274         iks_delete(payload_pcmu);
1275         return 0;
1276 }
1277
1278 /* Not in use right now.
1279 static int jingle_auto_congest(void *nothing)
1280 {
1281         struct jingle_pvt *p = nothing;
1282
1283         ast_mutex_lock(&p->lock);
1284         if (p->owner) {
1285                 if (!ast_channel_trylock(p->owner)) {
1286                         ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
1287                         ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
1288                         ast_channel_unlock(p->owner);
1289                 }
1290         }
1291         ast_mutex_unlock(&p->lock);
1292         return 0;
1293 }
1294 */
1295
1296 /*! \brief Initiate new call, part of PBX interface 
1297  *      dest is the dial string */
1298 static int jingle_call(struct ast_channel *ast, char *dest, int timeout)
1299 {
1300         struct jingle_pvt *p = ast->tech_pvt;
1301
1302         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
1303                 ast_log(LOG_WARNING, "jingle_call called on %s, neither down nor reserved\n", ast->name);
1304                 return -1;
1305         }
1306
1307         ast_setstate(ast, AST_STATE_RING);
1308         p->jointcapability = p->capability;
1309         if (!p->ringrule) {
1310                 ast_copy_string(p->ring, p->parent->connection->mid, sizeof(p->ring));
1311                 p->ringrule = iks_filter_add_rule(p->parent->connection->f, jingle_ringing_ack, p,
1312                                                         IKS_RULE_ID, p->ring, IKS_RULE_DONE);
1313         } else
1314                 ast_log(LOG_WARNING, "Whoa, already have a ring rule!\n");
1315
1316         jingle_transmit_invite(p);
1317         jingle_create_candidates(p->parent, p, p->sid, p->from);
1318
1319         return 0;
1320 }
1321
1322 /*! \brief Hangup a call through the jingle proxy channel */
1323 static int jingle_hangup(struct ast_channel *ast)
1324 {
1325         struct jingle_pvt *p = ast->tech_pvt;
1326         struct jingle *client;
1327
1328         ast_mutex_lock(&p->lock);
1329         client = p->parent;
1330         p->owner = NULL;
1331         ast->tech_pvt = NULL;
1332         if (!p->alreadygone)
1333                 jingle_action(client, p, "terminate");
1334         ast_mutex_unlock(&p->lock);
1335
1336         jingle_free_pvt(client, p);
1337         ast_mutex_lock(&usecnt_lock);
1338         usecnt--;
1339         ast_mutex_unlock(&usecnt_lock);
1340
1341         return 0;
1342 }
1343
1344 /*! \brief Part of PBX interface */
1345 static struct ast_channel *jingle_request(const char *type, int format, void *data, int *cause)
1346 {
1347         struct jingle_pvt *p = NULL;
1348         struct jingle *client = NULL;
1349         char *sender = NULL, *to = NULL, *s = NULL;
1350         struct ast_channel *chan = NULL;
1351
1352         if (data) {
1353                 s = ast_strdupa((char *) data);
1354                 if (s) {
1355                         sender = strsep(&s, "/");
1356                         if (sender && (sender[0] != '\0'))
1357                                 to = strsep(&s, "/");
1358                         if (!to) {
1359                                 ast_log(LOG_ERROR, "Bad arguments in Jingle Dialstring: %s\n", (char*) data);
1360                                 if (s)
1361                                         free(s);
1362                                 return NULL;
1363                         }
1364                 }
1365         }
1366         client = find_jingle(to, sender);
1367         if (!client) {
1368                 ast_log(LOG_WARNING, "Could not find recipient.\n");
1369                 if (s)
1370                         free(s);
1371                 return NULL;
1372         }
1373         p = jingle_alloc(client, to, NULL);
1374         if (p)
1375                 chan = jingle_new(client, p, AST_STATE_DOWN, to);
1376
1377         return chan;
1378 }
1379
1380 #if 0
1381 /*! \brief CLI command "jingle show channels" */
1382 static int jingle_show(int fd, int argc, char **argv)
1383 {
1384         struct jingle_pvt *p = NULL;
1385         struct jingle *peer = NULL;
1386         struct jingle_candidate *tmp;
1387         struct jingle *client = NULL;
1388         client = ast_aji_get_client("asterisk");
1389         if (argc != 3)
1390                 return RESULT_SHOWUSAGE;
1391         ast_mutex_lock(&jinglelock);
1392         if (client)
1393                 p = jingles->p;
1394         while (p) {
1395                 ast_mutex_lock(&p->lock);
1396                 ast_cli(fd, "SID = %s\n", p->sid);
1397                 tmp = p->candidates;
1398                 while (tmp) {
1399                         ast_verbose("port %d\n", tmp->port);
1400                         tmp = tmp->next;
1401                 }
1402                 ast_mutex_unlock(&p->lock);
1403                 p = p->next;
1404         }
1405         if (!jingles->p)
1406                 ast_cli(fd, "No jingle channels in use\n");
1407         ast_mutex_unlock(&jinglelock);
1408         return RESULT_SUCCESS;
1409 }
1410 #endif
1411
1412 static int jingle_parser(void *data, ikspak *pak)
1413 {
1414         struct jingle *client = ASTOBJ_REF((struct jingle *) data);
1415
1416         if (iks_find_with_attrib(pak->x, GOOGLE_NODE, "type", JINGLE_INITIATE)) {
1417                 /* New call */
1418                 jingle_newcall(client, pak);
1419         } else if (iks_find_with_attrib(pak->x, GOOGLE_NODE, "type", GOOGLE_NEGOTIATE)) {
1420                 if (option_debug > 2)
1421                         ast_log(LOG_DEBUG, "About to add candidate!\n");
1422                 jingle_add_candidate(client, pak);
1423                 if (option_debug > 2)
1424                         ast_log(LOG_DEBUG, "Candidate Added!\n");
1425         } else if (iks_find_with_attrib(pak->x, GOOGLE_NODE, "type", GOOGLE_ACCEPT)) {
1426                 jingle_is_answered(client, pak);
1427         } else if (iks_find_with_attrib(pak->x, GOOGLE_NODE, "type", "content-info")) {
1428                 jingle_handle_dtmf(client, pak);
1429         } else if (iks_find_with_attrib(pak->x, GOOGLE_NODE, "type", "terminate")) {
1430                 jingle_hangup_farend(client, pak);
1431         } else if (iks_find_with_attrib(pak->x, GOOGLE_NODE, "type", "reject")) {
1432                 jingle_hangup_farend(client, pak);
1433         }
1434         ASTOBJ_UNREF(client, jingle_member_destroy);
1435         return IKS_FILTER_EAT;
1436 }
1437 /* Not using this anymore probably take out soon 
1438 static struct jingle_candidate *jingle_create_candidate(char *args)
1439 {
1440         char *name, *type, *preference, *protocol;
1441         struct jingle_candidate *res;
1442         res = malloc(sizeof(struct jingle_candidate));
1443         memset(res, 0, sizeof(struct jingle_candidate));
1444         if (args)
1445                 name = args;
1446         if ((args = strchr(args, ','))) {
1447                 *args = '\0';
1448                 args++;
1449                 preference = args;
1450         }
1451         if ((args = strchr(args, ','))) {
1452                 *args = '\0';
1453                 args++;
1454                 protocol = args;
1455         }
1456         if ((args = strchr(args, ','))) {
1457                 *args = '\0';
1458                 args++;
1459                 type = args;
1460         }
1461         if (name)
1462                 ast_copy_string(res->name, name, sizeof(res->name));
1463         if (preference) {
1464                 res->preference = atof(preference);
1465         }
1466         if (protocol) {
1467                 if (!strcasecmp("udp", protocol))
1468                         res->protocol = AJI_PROTOCOL_UDP;
1469                 if (!strcasecmp("ssltcp", protocol))
1470                         res->protocol = AJI_PROTOCOL_SSLTCP;
1471         }
1472         if (type) {
1473                 if (!strcasecmp("stun", type))
1474                         res->type = AJI_CONNECT_STUN;
1475                 if (!strcasecmp("local", type))
1476                         res->type = AJI_CONNECT_LOCAL;
1477                 if (!strcasecmp("relay", type))
1478                         res->type = AJI_CONNECT_RELAY;
1479         }
1480
1481         return res;
1482 }
1483 */
1484
1485 static int jingle_create_member(char *label, struct ast_variable *var, int allowguest,
1486                                                                 struct ast_codec_pref prefs, char *context,
1487                                                                 struct jingle *member)
1488 {
1489         struct aji_client *client;
1490
1491         if (!member)
1492                 ast_log(LOG_WARNING, "Out of memory.\n");
1493
1494         ast_copy_string(member->name, label, sizeof(member->name));
1495         ast_copy_string(member->user, label, sizeof(member->user));
1496         ast_copy_string(member->context, context, sizeof(member->context));
1497         member->allowguest = allowguest;
1498         member->prefs = prefs;
1499         while (var) {
1500 #if 0
1501                 struct jingle_candidate *candidate = NULL;
1502 #endif
1503                 if (!strcasecmp(var->name, "username"))
1504                         ast_copy_string(member->user, var->value, sizeof(member->user));
1505                 else if (!strcasecmp(var->name, "disallow"))
1506                         ast_parse_allow_disallow(&member->prefs, &member->capability, var->value, 0);
1507                 else if (!strcasecmp(var->name, "allow"))
1508                         ast_parse_allow_disallow(&member->prefs, &member->capability, var->value, 1);
1509                 else if (!strcasecmp(var->name, "context"))
1510                         ast_copy_string(member->context, var->value, sizeof(member->context));
1511 #if 0
1512                 else if (!strcasecmp(var->name, "candidate")) {
1513                         candidate = jingle_create_candidate(var->value);
1514                         if (candidate) {
1515                                 candidate->next = member->ourcandidates;
1516                                 member->ourcandidates = candidate;
1517                         }
1518                 }
1519 #endif
1520                 else if (!strcasecmp(var->name, "connection")) {
1521                         if ((client = ast_aji_get_client(var->value))) {
1522                                 member->connection = client;
1523                                 iks_filter_add_rule(client->f, jingle_parser, member, IKS_RULE_TYPE,
1524                                                                         IKS_PAK_IQ, IKS_RULE_FROM_PARTIAL, member->user,
1525                                                                         IKS_RULE_NS, "http://www.google.com/session",
1526                                                                         IKS_RULE_DONE);
1527                         } else {
1528                                 ast_log(LOG_ERROR, "connection referenced not found!\n");
1529                                 return 0;
1530                         }
1531                 }
1532                 var = var->next;
1533         }
1534         if (member->connection && member->user)
1535                 member->buddy = ASTOBJ_CONTAINER_FIND(&member->connection->buddies, member->user);
1536         else {
1537                 ast_log(LOG_ERROR, "No Connection or Username!\n");
1538         }
1539         return 1;
1540 }
1541
1542 static int jingle_load_config(void)
1543 {
1544         char *cat = NULL;
1545         struct ast_config *cfg = NULL;
1546         char context[100];
1547         int allowguest = 1;
1548         struct ast_variable *var;
1549         struct jingle *member;
1550         struct ast_codec_pref prefs;
1551         struct aji_client_container *clients;
1552         struct jingle_candidate *global_candidates = NULL;
1553
1554         cfg = ast_config_load(JINGLE_CONFIG);
1555         if (!cfg)
1556                 return 0;
1557
1558         /* Copy the default jb config over global_jbconf */
1559         memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
1560
1561         cat = ast_category_browse(cfg, NULL);
1562         for (var = ast_variable_browse(cfg, "general"); var; var = var->next) {
1563                 /* handle jb conf */
1564                 if (!ast_jb_read_conf(&global_jbconf, var->name, var->value))
1565                         continue;
1566
1567                 if (!strcasecmp(var->name, "allowguest"))
1568                         allowguest =
1569                                 (ast_true(ast_variable_retrieve(cfg, "general", "allowguest"))) ? 1 : 0;
1570                 else if (!strcasecmp(var->name, "disallow"))
1571                         ast_parse_allow_disallow(&prefs, &global_capability, var->value, 0);
1572                 else if (!strcasecmp(var->name, "allow"))
1573                         ast_parse_allow_disallow(&prefs, &global_capability, var->value, 1);
1574                 else if (!strcasecmp(var->name, "context"))
1575                         ast_copy_string(context, var->value, sizeof(context));
1576                 else if (!strcasecmp(var->name, "externip"))
1577                         ast_copy_string(externip, var->value, sizeof(externip));
1578 /*  Idea to allow for custom candidates  */
1579 /*
1580                 else if (!strcasecmp(var->name, "candidate")) {
1581                         candidate = jingle_create_candidate(var->value);
1582                         if (candidate) {
1583                                 candidate->next = global_candidates;
1584                                 global_candidates = candidate;
1585                         }
1586                 }
1587 */
1588         }
1589         while (cat) {
1590                 if (strcasecmp(cat, "general")) {
1591                         var = ast_variable_browse(cfg, cat);
1592                         member = (struct jingle *) malloc(sizeof(struct jingle));
1593                         memset(member, 0, sizeof(struct jingle));
1594                         ASTOBJ_INIT(member);
1595                         ASTOBJ_WRLOCK(member);
1596                         if (!strcasecmp(cat, "guest")) {
1597                                 ast_copy_string(member->name, "guest", sizeof(member->name));
1598                                 ast_copy_string(member->user, "guest", sizeof(member->user));
1599                                 ast_copy_string(member->context, context, sizeof(member->context));
1600                                 member->allowguest = allowguest;
1601                                 member->prefs = prefs;
1602                                 while (var) {
1603                                         if (!strcasecmp(var->name, "disallow"))
1604                                                 ast_parse_allow_disallow(&member->prefs, &member->capability,
1605                                                                                                  var->value, 0);
1606                                         else if (!strcasecmp(var->name, "allow"))
1607                                                 ast_parse_allow_disallow(&member->prefs, &member->capability,
1608                                                                                                  var->value, 1);
1609                                         else if (!strcasecmp(var->name, "context"))
1610                                                 ast_copy_string(member->context, var->value,
1611                                                                                 sizeof(member->context));
1612 /*  Idea to allow for custom candidates  */
1613 /*
1614                                         else if (!strcasecmp(var->name, "candidate")) {
1615                                                 candidate = jingle_create_candidate(var->value);
1616                                                 if (candidate) {
1617                                                         candidate->next = member->ourcandidates;
1618                                                         member->ourcandidates = candidate;
1619                                                 }
1620                                         }
1621 */
1622                                         var = var->next;
1623                                 }
1624                                 ASTOBJ_UNLOCK(member);
1625                                 clients = ast_aji_get_clients();
1626                                 if (clients) {
1627                                         ASTOBJ_CONTAINER_TRAVERSE(clients, 1, {
1628                                                 ASTOBJ_WRLOCK(iterator);
1629                                                 ASTOBJ_WRLOCK(member);
1630                                                 member->connection = iterator;
1631                                                 iks_filter_add_rule(iterator->f, jingle_parser, member, IKS_RULE_TYPE, IKS_PAK_IQ, IKS_RULE_NS,
1632                                                                                 "http://www.google.com/session", IKS_RULE_DONE);
1633                                                 ASTOBJ_UNLOCK(member);
1634                                                 ASTOBJ_CONTAINER_LINK(&jingles, member);
1635                                                 ASTOBJ_UNLOCK(iterator);
1636                                         });
1637                                 } else {
1638                                         ASTOBJ_UNLOCK(member);
1639                                         ASTOBJ_UNREF(member, jingle_member_destroy);
1640                                 }
1641                         } else {
1642                                 ASTOBJ_UNLOCK(member);
1643                                 if (jingle_create_member(cat, var, allowguest, prefs, context, member))
1644                                         ASTOBJ_CONTAINER_LINK(&jingles, member);
1645                                 ASTOBJ_UNREF(member, jingle_member_destroy);
1646                         }
1647                 }
1648                 cat = ast_category_browse(cfg, cat);
1649         }
1650         jingle_free_candidates(global_candidates);
1651         return 1;
1652 }
1653
1654 /*! \brief Load module into PBX, register channel */
1655 static int load_module(void *mod)
1656 {
1657         ASTOBJ_CONTAINER_INIT(&jingles);
1658         if (!jingle_load_config()) {
1659                 ast_log(LOG_ERROR, "Unable to read config file %s. Not loading module.\n", JINGLE_CONFIG);
1660                 return 0;
1661         }
1662
1663         sched = sched_context_create();
1664         if (!sched) 
1665                 ast_log(LOG_WARNING, "Unable to create schedule context\n");
1666
1667         io = io_context_create();
1668         if (!io) 
1669                 ast_log(LOG_WARNING, "Unable to create I/O context\n");
1670
1671         if (ast_find_ourip(&__ourip, bindaddr)) {
1672                 ast_log(LOG_WARNING, "Unable to get own IP address, Jingle disabled\n");
1673                 return 0;
1674         }
1675
1676         ast_rtp_proto_register(&jingle_rtp);
1677
1678         /* Make sure we can register our channel type */
1679         if (ast_channel_register(&jingle_tech)) {
1680                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
1681                 return -1;
1682         }
1683         return 0;
1684 }
1685
1686 /*! \brief Reload module */
1687 static int reload(void *mod)
1688 {
1689         return 0;
1690 }
1691
1692 /*! \brief Unload the jingle channel from Asterisk */
1693 static int unload_module(void *mod)
1694 {
1695         struct jingle_pvt *privates = NULL;
1696
1697         /* First, take us out of the channel loop */
1698         ast_channel_unregister(&jingle_tech);
1699         ast_rtp_proto_unregister(&jingle_rtp);
1700
1701         if (!ast_mutex_lock(&jinglelock)) {
1702                 /* Hangup all interfaces if they have an owner */
1703                 ASTOBJ_CONTAINER_TRAVERSE(&jingles, 1, {
1704                         ASTOBJ_WRLOCK(iterator);
1705                         privates = iterator->p;
1706                         while(privates) {
1707                             if (privates->owner)
1708                                 ast_softhangup(privates->owner, AST_SOFTHANGUP_APPUNLOAD);
1709                             privates = privates->next;
1710                         }
1711                         iterator->p = NULL;
1712                         ASTOBJ_UNLOCK(iterator);
1713                 });
1714                 ast_mutex_unlock(&jinglelock);
1715         } else {
1716                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
1717                 return -1;
1718         }
1719         ASTOBJ_CONTAINER_DESTROYALL(&jingles, jingle_member_destroy);
1720         ASTOBJ_CONTAINER_DESTROY(&jingles);
1721         return 0;
1722 }
1723
1724 static const char *key(void)
1725 {
1726         return ASTERISK_GPL_KEY;
1727 }
1728
1729 static const char *description(void)
1730 {
1731         return desc;
1732 }
1733
1734 STD_MOD(MOD_1, reload, NULL, NULL);