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