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