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