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