Allow Asterisk to compile under GCC 4.10
[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  * Iksemel http://iksemel.jabberstudio.org/
26  * 
27  * \ingroup channel_drivers
28  */
29
30 /*! \li \ref chan_jingle.c uses the configuration file \ref jingle.conf
31  * \addtogroup configuration_file
32  */
33
34 /*! \page jingle.conf jingle.conf
35  * \verbinclude jingle.conf.sample
36  */
37
38 /*** MODULEINFO
39         <depend>iksemel</depend>
40         <depend>res_jabber</depend>
41         <use type="external">openssl</use>
42         <defaultenabled>no</defaultenabled>
43         <support_level>deprecated</support_level>
44         <replacement>chan_motif</replacement>
45  ***/
46
47 #include "asterisk.h"
48
49 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
50
51 #include <sys/socket.h>
52 #include <fcntl.h>
53 #include <netdb.h>
54 #include <netinet/in.h>
55 #include <arpa/inet.h>
56 #include <sys/signal.h>
57 #include <iksemel.h>
58 #include <pthread.h>
59
60 #include "asterisk/lock.h"
61 #include "asterisk/channel.h"
62 #include "asterisk/config.h"
63 #include "asterisk/module.h"
64 #include "asterisk/pbx.h"
65 #include "asterisk/sched.h"
66 #include "asterisk/io.h"
67 #include "asterisk/rtp_engine.h"
68 #include "asterisk/acl.h"
69 #include "asterisk/callerid.h"
70 #include "asterisk/file.h"
71 #include "asterisk/cli.h"
72 #include "asterisk/app.h"
73 #include "asterisk/musiconhold.h"
74 #include "asterisk/manager.h"
75 #include "asterisk/stringfields.h"
76 #include "asterisk/utils.h"
77 #include "asterisk/causes.h"
78 #include "asterisk/astobj.h"
79 #include "asterisk/abstract_jb.h"
80 #include "asterisk/jabber.h"
81 #include "asterisk/jingle.h"
82 #include "asterisk/stasis_channels.h"
83
84 #define JINGLE_CONFIG "jingle.conf"
85
86 /*! Global jitterbuffer configuration - by default, jb is disabled */
87 static struct ast_jb_conf default_jbconf =
88 {
89         .flags = 0,
90         .max_size = -1,
91         .resync_threshold = -1,
92         .impl = "",
93         .target_extra = -1,
94 };
95 static struct ast_jb_conf global_jbconf;
96
97 enum jingle_protocol {
98         AJI_PROTOCOL_UDP,
99         AJI_PROTOCOL_SSLTCP,
100 };
101
102 enum jingle_connect_type {
103         AJI_CONNECT_HOST,
104         AJI_CONNECT_PRFLX,
105         AJI_CONNECT_RELAY,
106         AJI_CONNECT_SRFLX,
107 };
108
109 struct jingle_pvt {
110         ast_mutex_t lock;                /*!< Channel private lock */
111         time_t laststun;
112         struct jingle *parent;           /*!< Parent client */
113         char sid[100];
114         char them[AJI_MAX_JIDLEN];
115         char ring[10];                   /*!< Message ID of ring */
116         iksrule *ringrule;               /*!< Rule for matching RING request */
117         int initiator;                   /*!< If we're the initiator */
118         int alreadygone;
119         struct ast_codec_pref prefs;
120         struct jingle_candidate *theircandidates;
121         struct jingle_candidate *ourcandidates;
122         char cid_num[80];                /*!< Caller ID num */
123         char cid_name[80];               /*!< Caller ID name */
124         char exten[80];                  /*!< Called extension */
125         struct ast_channel *owner;       /*!< Master Channel */
126         char audio_content_name[100];    /*!< name attribute of content tag */
127         struct ast_rtp_instance *rtp;             /*!< RTP audio session */
128         char video_content_name[100];    /*!< name attribute of content tag */
129         struct ast_rtp_instance *vrtp;            /*!< RTP video session */
130         struct ast_format_cap *cap;
131         struct ast_format_cap *jointcap;             /*!< Supported capability at both ends (codecs ) */
132         struct ast_format_cap *peercap;
133         struct jingle_pvt *next;        /* Next entity */
134 };
135
136 struct jingle_candidate {
137         unsigned int component;          /*!< ex. : 1 for RTP, 2 for RTCP */
138         unsigned int foundation;         /*!< Function of IP, protocol, type */
139         unsigned int generation;
140         char ip[16];
141         unsigned int network;
142         unsigned int port;
143         unsigned int priority;
144         enum jingle_protocol protocol;
145         char password[100];
146         enum jingle_connect_type type;
147         char ufrag[100];
148         unsigned int preference;
149         struct jingle_candidate *next;
150 };
151
152 struct jingle {
153         ASTOBJ_COMPONENTS(struct jingle);
154         struct aji_client *connection;
155         struct aji_buddy *buddy;
156         struct jingle_pvt *p;
157         struct ast_codec_pref prefs;
158         int amaflags;                   /*!< AMA Flags */
159         char user[100];
160         char context[100];
161         char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */
162         struct ast_format_cap *cap;
163         ast_group_t callgroup;  /*!< Call group */
164         ast_group_t pickupgroup;        /*!< Pickup group */
165         int callingpres;                /*!< Calling presentation */
166         int allowguest;
167         char language[MAX_LANGUAGE];    /*!<  Default language for prompts */
168         char musicclass[MAX_MUSICCLASS];        /*!<  Music on Hold class */
169         char parkinglot[AST_MAX_CONTEXT];   /*!< Parkinglot */
170 };
171
172 struct jingle_container {
173         ASTOBJ_CONTAINER_COMPONENTS(struct jingle);
174 };
175
176 static const char desc[] = "Jingle Channel";
177 static const char channel_type[] = "Jingle";
178
179 static struct ast_format_cap *global_capability;
180
181 AST_MUTEX_DEFINE_STATIC(jinglelock); /*!< Protect the interface list (of jingle_pvt's) */
182
183 /* Forward declarations */
184 static struct ast_channel *jingle_request(const char *type, struct ast_format_cap *cap, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *data, int *cause);
185 static int jingle_sendtext(struct ast_channel *ast, const char *text);
186 static int jingle_digit_begin(struct ast_channel *ast, char digit);
187 static int jingle_digit_end(struct ast_channel *ast, char digit, unsigned int duration);
188 static int jingle_call(struct ast_channel *ast, const char *dest, int timeout);
189 static int jingle_hangup(struct ast_channel *ast);
190 static int jingle_answer(struct ast_channel *ast);
191 static int jingle_newcall(struct jingle *client, ikspak *pak);
192 static struct ast_frame *jingle_read(struct ast_channel *ast);
193 static int jingle_write(struct ast_channel *ast, struct ast_frame *f);
194 static int jingle_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
195 static int jingle_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
196 static int jingle_sendhtml(struct ast_channel *ast, int subclass, const char *data, int datalen);
197 static struct jingle_pvt *jingle_alloc(struct jingle *client, const char *from, const char *sid);
198 static char *jingle_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
199 static char *jingle_do_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
200 static void jingle_set_owner(struct jingle_pvt *pvt, struct ast_channel *chan);
201
202 /*! \brief PBX interface structure for channel registration */
203 static struct ast_channel_tech jingle_tech = {
204         .type = "Jingle",
205         .description = "Jingle Channel Driver",
206         .requester = jingle_request,
207         .send_text = jingle_sendtext,
208         .send_digit_begin = jingle_digit_begin,
209         .send_digit_end = jingle_digit_end,
210         .call = jingle_call,
211         .hangup = jingle_hangup,
212         .answer = jingle_answer,
213         .read = jingle_read,
214         .write = jingle_write,
215         .exception = jingle_read,
216         .indicate = jingle_indicate,
217         .fixup = jingle_fixup,
218         .send_html = jingle_sendhtml,
219         .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER
220 };
221
222 static struct sockaddr_in bindaddr = { 0, };    /*!< The address we bind to */
223
224 static struct ast_sched_context *sched; /*!< The scheduling context */
225 static struct io_context *io;   /*!< The IO context */
226 static struct in_addr __ourip;
227
228 static struct ast_cli_entry jingle_cli[] = {
229         AST_CLI_DEFINE(jingle_do_reload, "Reload Jingle configuration"),
230         AST_CLI_DEFINE(jingle_show_channels, "Show Jingle channels"),
231 };
232
233
234 static char externip[16];
235
236 static struct jingle_container jingle_list;
237
238 static void jingle_member_destroy(struct jingle *obj)
239 {
240         obj->cap = ast_format_cap_destroy(obj->cap);
241         if (obj->connection) {
242                 ASTOBJ_UNREF(obj->connection, ast_aji_client_destroy);
243         }
244         if (obj->buddy) {
245                 ASTOBJ_UNREF(obj->buddy, ast_aji_buddy_destroy);
246         }
247         ast_free(obj);
248 }
249
250 /* XXX This could be a source of reference leaks given that the CONTAINER_FIND
251  * macros bump the refcount while the traversal does not. */
252 static struct jingle *find_jingle(char *name, char *connection)
253 {
254         struct jingle *jingle = NULL;
255
256         jingle = ASTOBJ_CONTAINER_FIND(&jingle_list, name);
257         if (!jingle && strchr(name, '@'))
258                 jingle = ASTOBJ_CONTAINER_FIND_FULL(&jingle_list, name, user,,, strcasecmp);
259
260         if (!jingle) {                          
261                 /* guest call */
262                 ASTOBJ_CONTAINER_TRAVERSE(&jingle_list, 1, {
263                         ASTOBJ_RDLOCK(iterator);
264                         if (!strcasecmp(iterator->name, "guest")) {
265                                 jingle = iterator;
266                         }
267                         ASTOBJ_UNLOCK(iterator);
268
269                         if (jingle)
270                                 break;
271                 });
272
273         }
274         return jingle;
275 }
276
277
278 static void add_codec_to_answer(const struct jingle_pvt *p, struct ast_format *codec, iks *dcodecs)
279 {
280         const char *format = ast_getformatname(codec);
281
282         if (!strcasecmp("ulaw", format)) {
283                 iks *payload_eg711u, *payload_pcmu;
284                 payload_pcmu = iks_new("payload-type");
285                 iks_insert_attrib(payload_pcmu, "id", "0");
286                 iks_insert_attrib(payload_pcmu, "name", "PCMU");
287                 payload_eg711u = iks_new("payload-type");
288                 iks_insert_attrib(payload_eg711u, "id", "100");
289                 iks_insert_attrib(payload_eg711u, "name", "EG711U");
290                 iks_insert_node(dcodecs, payload_pcmu);
291                 iks_insert_node(dcodecs, payload_eg711u);
292         }
293         if (!strcasecmp("alaw", format)) {
294                 iks *payload_eg711a;
295                 iks *payload_pcma = iks_new("payload-type");
296                 iks_insert_attrib(payload_pcma, "id", "8");
297                 iks_insert_attrib(payload_pcma, "name", "PCMA");
298                 payload_eg711a = iks_new("payload-type");
299                 iks_insert_attrib(payload_eg711a, "id", "101");
300                 iks_insert_attrib(payload_eg711a, "name", "EG711A");
301                 iks_insert_node(dcodecs, payload_pcma);
302                 iks_insert_node(dcodecs, payload_eg711a);
303         }
304         if (!strcasecmp("ilbc", format)) {
305                 iks *payload_ilbc = iks_new("payload-type");
306                 iks_insert_attrib(payload_ilbc, "id", "97");
307                 iks_insert_attrib(payload_ilbc, "name", "iLBC");
308                 iks_insert_node(dcodecs, payload_ilbc);
309         }
310         if (!strcasecmp("g723", format)) {
311                 iks *payload_g723 = iks_new("payload-type");
312                 iks_insert_attrib(payload_g723, "id", "4");
313                 iks_insert_attrib(payload_g723, "name", "G723");
314                 iks_insert_node(dcodecs, payload_g723);
315         }
316 }
317
318 static int jingle_accept_call(struct jingle *client, struct jingle_pvt *p)
319 {
320         struct jingle_pvt *tmp = client->p;
321         struct aji_client *c = client->connection;
322         iks *iq, *jingle, *dcodecs, *payload_red, *payload_audio, *payload_cn;
323         int x;
324         struct ast_format pref_codec;
325         struct ast_format_cap *alreadysent = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_NOLOCK);
326
327         if (p->initiator || !alreadysent)
328                 return 1;
329
330         iq = iks_new("iq");
331         jingle = iks_new(JINGLE_NODE);
332         dcodecs = iks_new("description");
333         if (iq && jingle && dcodecs) {
334                 iks_insert_attrib(dcodecs, "xmlns", JINGLE_AUDIO_RTP_NS);
335
336                 for (x = 0; x < AST_CODEC_PREF_SIZE; x++) {
337                         if (!(ast_codec_pref_index(&client->prefs, x, &pref_codec)))
338                                 break;
339                         if (!(ast_format_cap_iscompatible(client->cap, &pref_codec)))
340                                 continue;
341                         if ((ast_format_cap_iscompatible(alreadysent, &pref_codec)))
342                                 continue;
343                         add_codec_to_answer(p, &pref_codec, dcodecs);
344                         ast_format_cap_add(alreadysent, &pref_codec);
345                 }
346                 payload_red = iks_new("payload-type");
347                 iks_insert_attrib(payload_red, "id", "117");
348                 iks_insert_attrib(payload_red, "name", "red");
349                 payload_audio = iks_new("payload-type");
350                 iks_insert_attrib(payload_audio, "id", "106");
351                 iks_insert_attrib(payload_audio, "name", "audio/telephone-event");
352                 payload_cn = iks_new("payload-type");
353                 iks_insert_attrib(payload_cn, "id", "13");
354                 iks_insert_attrib(payload_cn, "name", "CN");
355
356
357                 iks_insert_attrib(iq, "type", "set");
358                 iks_insert_attrib(iq, "to", (p->them) ? p->them : client->user);
359                 iks_insert_attrib(iq, "id", client->connection->mid);
360                 ast_aji_increment_mid(client->connection->mid);
361
362                 iks_insert_attrib(jingle, "xmlns", JINGLE_NS);
363                 iks_insert_attrib(jingle, "action", JINGLE_ACCEPT);
364                 iks_insert_attrib(jingle, "initiator", p->initiator ? client->connection->jid->full : p->them);
365                 iks_insert_attrib(jingle, JINGLE_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                 ast_aji_send(c, iq);
373
374                 iks_delete(payload_red);
375                 iks_delete(payload_audio);
376                 iks_delete(payload_cn);
377                 iks_delete(dcodecs);
378                 iks_delete(jingle);
379                 iks_delete(iq);
380         }
381         alreadysent = ast_format_cap_destroy(alreadysent);
382         return 1;
383 }
384
385 static int jingle_ringing_ack(void *data, ikspak *pak)
386 {
387         struct jingle_pvt *p = data;
388
389         if (p->ringrule)
390                 iks_filter_remove_rule(p->parent->connection->f, p->ringrule);
391         p->ringrule = NULL;
392         if (p->owner)
393                 ast_queue_control(p->owner, AST_CONTROL_RINGING);
394         return IKS_FILTER_EAT;
395 }
396
397 static int jingle_answer(struct ast_channel *ast)
398 {
399         struct jingle_pvt *p = ast_channel_tech_pvt(ast);
400         struct jingle *client = p->parent;
401         int res = 0;
402
403         ast_debug(1, "Answer!\n");
404         ast_mutex_lock(&p->lock);
405         jingle_accept_call(client, p);
406         ast_mutex_unlock(&p->lock);
407         return res;
408 }
409
410 static enum ast_rtp_glue_result jingle_get_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
411 {
412         struct jingle_pvt *p = ast_channel_tech_pvt(chan);
413         enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_FORBID;
414
415         if (!p)
416                 return res;
417
418         ast_mutex_lock(&p->lock);
419         if (p->rtp) {
420                 ao2_ref(p->rtp, +1);
421                 *instance = p->rtp;
422                 res = AST_RTP_GLUE_RESULT_LOCAL;
423         }
424         ast_mutex_unlock(&p->lock);
425
426         return res;
427 }
428
429 static void jingle_get_codec(struct ast_channel *chan, struct ast_format_cap *result)
430 {
431         struct jingle_pvt *p = ast_channel_tech_pvt(chan);
432         ast_mutex_lock(&p->lock);
433         ast_format_cap_copy(result, p->peercap);
434         ast_mutex_unlock(&p->lock);
435 }
436
437 static int jingle_set_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance *rtp, struct ast_rtp_instance *vrtp, struct ast_rtp_instance *tpeer, const struct ast_format_cap *cap, int nat_active)
438 {
439         struct jingle_pvt *p;
440
441         p = ast_channel_tech_pvt(chan);
442         if (!p)
443                 return -1;
444         ast_mutex_lock(&p->lock);
445
446 /*      if (rtp)
447                 ast_rtp_get_peer(rtp, &p->redirip);
448         else
449                 memset(&p->redirip, 0, sizeof(p->redirip));
450         p->redircodecs = codecs; */
451
452         /* Reset lastrtprx timer */
453         ast_mutex_unlock(&p->lock);
454         return 0;
455 }
456
457 static struct ast_rtp_glue jingle_rtp_glue = {
458         .type = "Jingle",
459         .get_rtp_info = jingle_get_rtp_peer,
460         .get_codec = jingle_get_codec,
461         .update_peer = jingle_set_rtp_peer,
462 };
463
464 static int jingle_response(struct jingle *client, ikspak *pak, const char *reasonstr, const char *reasonstr2)
465 {
466         iks *response = NULL, *error = NULL, *reason = NULL;
467         int res = -1;
468
469         response = iks_new("iq");
470         if (response) {
471                 iks_insert_attrib(response, "type", "result");
472                 iks_insert_attrib(response, "from", client->connection->jid->full);
473                 iks_insert_attrib(response, "to", iks_find_attrib(pak->x, "from"));
474                 iks_insert_attrib(response, "id", iks_find_attrib(pak->x, "id"));
475                 if (reasonstr) {
476                         error = iks_new("error");
477                         if (error) {
478                                 iks_insert_attrib(error, "type", "cancel");
479                                 reason = iks_new(reasonstr);
480                                 if (reason)
481                                         iks_insert_node(error, reason);
482                                 iks_insert_node(response, error);
483                         }
484                 }
485                 ast_aji_send(client->connection, response);
486                 res = 0;
487         }
488         
489         iks_delete(reason);
490         iks_delete(error);
491         iks_delete(response);
492
493         return res;
494 }
495
496 static int jingle_is_answered(struct jingle *client, ikspak *pak)
497 {
498         struct jingle_pvt *tmp;
499
500         ast_debug(1, "The client is %s\n", client->name);
501         /* Make sure our new call doesn't exist yet */
502         for (tmp = client->p; tmp; tmp = tmp->next) {
503                 if (iks_find_with_attrib(pak->x, JINGLE_NODE, JINGLE_SID, tmp->sid))
504                         break;
505         }
506
507         if (tmp) {
508                 if (tmp->owner)
509                         ast_queue_control(tmp->owner, AST_CONTROL_ANSWER);
510         } else
511                 ast_log(LOG_NOTICE, "Whoa, didn't find call!\n");
512         jingle_response(client, pak, NULL, NULL);
513         return 1;
514 }
515
516 static int jingle_handle_dtmf(struct jingle *client, ikspak *pak)
517 {
518         struct jingle_pvt *tmp;
519         iks *dtmfnode = NULL, *dtmfchild = NULL;
520         char *dtmf;
521         /* Make sure our new call doesn't exist yet */
522         for (tmp = client->p; tmp; tmp = tmp->next) {
523                 if (iks_find_with_attrib(pak->x, JINGLE_NODE, JINGLE_SID, tmp->sid))
524                         break;
525         }
526
527         if (tmp) {
528                 if(iks_find_with_attrib(pak->x, "dtmf-method", "method", "rtp")) {
529                         jingle_response(client,pak,
530                                         "feature-not-implemented xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'",
531                                         "unsupported-dtmf-method xmlns='http://www.xmpp.org/extensions/xep-0181.html#ns-errors'");
532                         return -1;
533                 }
534                 if ((dtmfnode = iks_find(pak->x, "dtmf"))) {
535                         if((dtmf = iks_find_attrib(dtmfnode, "code"))) {
536                                 if(iks_find_with_attrib(pak->x, "dtmf", "action", "button-up")) {
537                                         struct ast_frame f = {AST_FRAME_DTMF_BEGIN, };
538                                         f.subclass.integer = dtmf[0];
539                                         ast_queue_frame(tmp->owner, &f);
540                                         ast_verbose("JINGLE! DTMF-relay event received: %c\n", f.subclass.integer);
541                                 } else if(iks_find_with_attrib(pak->x, "dtmf", "action", "button-down")) {
542                                         struct ast_frame f = {AST_FRAME_DTMF_END, };
543                                         f.subclass.integer = dtmf[0];
544                                         ast_queue_frame(tmp->owner, &f);
545                                         ast_verbose("JINGLE! DTMF-relay event received: %c\n", f.subclass.integer);
546                                 } else if(iks_find_attrib(pak->x, "dtmf")) { /* 250 millasecond default */
547                                         struct ast_frame f = {AST_FRAME_DTMF, };
548                                         f.subclass.integer = dtmf[0];
549                                         ast_queue_frame(tmp->owner, &f);
550                                         ast_verbose("JINGLE! DTMF-relay event received: %c\n", f.subclass.integer);
551                                 }
552                         }
553                 } else if ((dtmfnode = iks_find_with_attrib(pak->x, JINGLE_NODE, "action", "session-info"))) {
554                         if((dtmfchild = iks_find(dtmfnode, "dtmf"))) {
555                                 if((dtmf = iks_find_attrib(dtmfchild, "code"))) {
556                                         if(iks_find_with_attrib(dtmfnode, "dtmf", "action", "button-up")) {
557                                                 struct ast_frame f = {AST_FRAME_DTMF_END, };
558                                                 f.subclass.integer = dtmf[0];
559                                                 ast_queue_frame(tmp->owner, &f);
560                                                 ast_verbose("JINGLE! DTMF-relay event received: %c\n", f.subclass.integer);
561                                         } else if(iks_find_with_attrib(dtmfnode, "dtmf", "action", "button-down")) {
562                                                 struct ast_frame f = {AST_FRAME_DTMF_BEGIN, };
563                                                 f.subclass.integer = dtmf[0];
564                                                 ast_queue_frame(tmp->owner, &f);
565                                                 ast_verbose("JINGLE! DTMF-relay event received: %c\n", f.subclass.integer);
566                                         }
567                                 }
568                         }
569                 }
570                 jingle_response(client, pak, NULL, NULL);
571                 return 1;
572         } else
573                 ast_log(LOG_NOTICE, "Whoa, didn't find call!\n");
574
575         jingle_response(client, pak, NULL, NULL);
576         return 1;
577 }
578
579
580 static int jingle_hangup_farend(struct jingle *client, ikspak *pak)
581 {
582         struct jingle_pvt *tmp;
583
584         ast_debug(1, "The client is %s\n", client->name);
585         /* Make sure our new call doesn't exist yet */
586         for (tmp = client->p; tmp; tmp = tmp->next) {
587                 if (iks_find_with_attrib(pak->x, JINGLE_NODE, JINGLE_SID, tmp->sid))
588                         break;
589         }
590
591         if (tmp) {
592                 tmp->alreadygone = 1;
593                 if (tmp->owner)
594                         ast_queue_hangup(tmp->owner);
595         } else
596                 ast_log(LOG_NOTICE, "Whoa, didn't find call!\n");
597         jingle_response(client, pak, NULL, NULL);
598         return 1;
599 }
600
601 static int jingle_create_candidates(struct jingle *client, struct jingle_pvt *p, char *sid, char *from)
602 {
603         struct jingle_candidate *tmp;
604         struct aji_client *c = client->connection;
605         struct jingle_candidate *ours1 = NULL, *ours2 = NULL;
606         struct sockaddr_in sin = { 0, };
607         struct ast_sockaddr sin_tmp;
608         struct ast_sockaddr us_tmp;
609         struct ast_sockaddr bindaddr_tmp;
610         struct in_addr us;
611         struct in_addr externaddr;
612         iks *iq, *jingle, *content, *transport, *candidate;
613         char component[16], foundation[16], generation[16], network[16], pass[16], port[7], priority[16], user[16];
614
615
616         iq = iks_new("iq");
617         jingle = iks_new(JINGLE_NODE);
618         content = iks_new("content");
619         transport = iks_new("transport");
620         candidate = iks_new("candidate");
621         if (!iq || !jingle || !content || !transport || !candidate) {
622                 ast_log(LOG_ERROR, "Memory allocation error\n");
623                 goto safeout;
624         }
625         ours1 = ast_calloc(1, sizeof(*ours1));
626         ours2 = ast_calloc(1, sizeof(*ours2));
627         if (!ours1 || !ours2)
628                 goto safeout;
629
630         iks_insert_node(iq, jingle);
631         iks_insert_node(jingle, content);
632         iks_insert_node(content, transport);
633         iks_insert_node(transport, candidate);
634
635         for (; p; p = p->next) {
636                 if (!strcasecmp(p->sid, sid))
637                         break;
638         }
639
640         if (!p) {
641                 ast_log(LOG_NOTICE, "No matching jingle session - SID %s!\n", sid);
642                 goto safeout;
643         }
644
645         ast_rtp_instance_get_local_address(p->rtp, &sin_tmp);
646         ast_sockaddr_to_sin(&sin_tmp, &sin);
647         ast_sockaddr_from_sin(&bindaddr_tmp, &bindaddr);
648         ast_find_ourip(&us_tmp, &bindaddr_tmp, AF_INET);
649         us.s_addr = htonl(ast_sockaddr_ipv4(&us_tmp));
650
651         /* Setup our first jingle candidate */
652         ours1->component = 1;
653         ours1->foundation = (unsigned int)bindaddr.sin_addr.s_addr | AJI_CONNECT_HOST | AJI_PROTOCOL_UDP;
654         ours1->generation = 0;
655         ast_copy_string(ours1->ip, ast_inet_ntoa(us), sizeof(ours1->ip));
656         ours1->network = 0;
657         ours1->port = ntohs(sin.sin_port);
658         ours1->priority = 1678246398;
659         ours1->protocol = AJI_PROTOCOL_UDP;
660         snprintf(pass, sizeof(pass), "%08lx%08lx", (unsigned long)ast_random(), (unsigned long)ast_random());
661         ast_copy_string(ours1->password, pass, sizeof(ours1->password));
662         ours1->type = AJI_CONNECT_HOST;
663         snprintf(user, sizeof(user), "%08lx%08lx", (unsigned long)ast_random(), (unsigned long)ast_random());
664         ast_copy_string(ours1->ufrag, user, sizeof(ours1->ufrag));
665         p->ourcandidates = ours1;
666
667         if (!ast_strlen_zero(externip)) {
668                 /* XXX We should really stun for this one not just go with externip XXX */
669                 if (inet_aton(externip, &externaddr))
670                         ast_log(LOG_WARNING, "Invalid extern IP : %s\n", externip);
671
672                 ours2->component = 1;
673                 ours2->foundation = (unsigned int)externaddr.s_addr | AJI_CONNECT_PRFLX | AJI_PROTOCOL_UDP;
674                 ours2->generation = 0;
675                 ast_copy_string(ours2->ip, externip, sizeof(ours2->ip));
676                 ours2->network = 0;
677                 ours2->port = ntohs(sin.sin_port);
678                 ours2->priority = 1678246397;
679                 ours2->protocol = AJI_PROTOCOL_UDP;
680                 snprintf(pass, sizeof(pass), "%08lx%08lx", (unsigned long)ast_random(), (unsigned long)ast_random());
681                 ast_copy_string(ours2->password, pass, sizeof(ours2->password));
682                 ours2->type = AJI_CONNECT_PRFLX;
683
684                 snprintf(user, sizeof(user), "%08lx%08lx", (unsigned long)ast_random(), (unsigned long)ast_random());
685                 ast_copy_string(ours2->ufrag, user, sizeof(ours2->ufrag));
686                 ours1->next = ours2;
687                 ours2 = NULL;
688         }
689         ours1 = NULL;
690
691         for (tmp = p->ourcandidates; tmp; tmp = tmp->next) {
692                 snprintf(component, sizeof(component), "%u", tmp->component);
693                 snprintf(foundation, sizeof(foundation), "%u", tmp->foundation);
694                 snprintf(generation, sizeof(generation), "%u", tmp->generation);
695                 snprintf(network, sizeof(network), "%u", tmp->network);
696                 snprintf(port, sizeof(port), "%u", tmp->port);
697                 snprintf(priority, sizeof(priority), "%u", tmp->priority);
698
699                 iks_insert_attrib(iq, "from", c->jid->full);
700                 iks_insert_attrib(iq, "to", from);
701                 iks_insert_attrib(iq, "type", "set");
702                 iks_insert_attrib(iq, "id", c->mid);
703                 ast_aji_increment_mid(c->mid);
704                 iks_insert_attrib(jingle, "action", JINGLE_NEGOTIATE);
705                 iks_insert_attrib(jingle, JINGLE_SID, sid);
706                 iks_insert_attrib(jingle, "initiator", (p->initiator) ? c->jid->full : from);
707                 iks_insert_attrib(jingle, "xmlns", JINGLE_NS);
708                 iks_insert_attrib(content, "creator", p->initiator ? "initiator" : "responder");
709                 iks_insert_attrib(content, "name", "asterisk-audio-content");
710                 iks_insert_attrib(transport, "xmlns", JINGLE_ICE_UDP_NS);
711                 iks_insert_attrib(candidate, "component", component);
712                 iks_insert_attrib(candidate, "foundation", foundation);
713                 iks_insert_attrib(candidate, "generation", generation);
714                 iks_insert_attrib(candidate, "ip", tmp->ip);
715                 iks_insert_attrib(candidate, "network", network);
716                 iks_insert_attrib(candidate, "port", port);
717                 iks_insert_attrib(candidate, "priority", priority);
718                 switch (tmp->protocol) {
719                 case AJI_PROTOCOL_UDP:
720                         iks_insert_attrib(candidate, "protocol", "udp");
721                         break;
722                 case AJI_PROTOCOL_SSLTCP:
723                         iks_insert_attrib(candidate, "protocol", "ssltcp");
724                         break;
725                 }
726                 iks_insert_attrib(candidate, "pwd", tmp->password);
727                 switch (tmp->type) {
728                 case AJI_CONNECT_HOST:
729                         iks_insert_attrib(candidate, "type", "host");
730                         break;
731                 case AJI_CONNECT_PRFLX:
732                         iks_insert_attrib(candidate, "type", "prflx");
733                         break;
734                 case AJI_CONNECT_RELAY:
735                         iks_insert_attrib(candidate, "type", "relay");
736                         break;
737                 case AJI_CONNECT_SRFLX:
738                         iks_insert_attrib(candidate, "type", "srflx");
739                         break;
740                 }
741                 iks_insert_attrib(candidate, "ufrag", tmp->ufrag);
742
743                 ast_aji_send(c, iq);
744         }
745         p->laststun = 0;
746
747 safeout:
748         if (ours1)
749                 ast_free(ours1);
750         if (ours2)
751                 ast_free(ours2);
752         iks_delete(iq);
753         iks_delete(jingle);
754         iks_delete(content);
755         iks_delete(transport);
756         iks_delete(candidate);
757
758         return 1;
759 }
760
761 static struct jingle_pvt *jingle_alloc(struct jingle *client, const char *from, const char *sid)
762 {
763         struct jingle_pvt *tmp = NULL;
764         struct aji_resource *resources = NULL;
765         struct aji_buddy *buddy = NULL;
766         char idroster[200];
767         struct ast_sockaddr bindaddr_tmp;
768
769         ast_debug(1, "The client is %s for alloc\n", client->name);
770         if (!sid && !strchr(from, '/')) {       /* I started call! */
771                 if (!strcasecmp(client->name, "guest")) {
772                         buddy = ASTOBJ_CONTAINER_FIND(&client->connection->buddies, from);
773                         if (buddy) {
774                                 resources = buddy->resources;
775                         }
776                 } else if (client->buddy)
777                         resources = client->buddy->resources;
778                 while (resources) {
779                         if (resources->cap->jingle) {
780                                 break;
781                         }
782                         resources = resources->next;
783                 }
784                 if (resources)
785                         snprintf(idroster, sizeof(idroster), "%s/%s", from, resources->resource);
786                 else {
787                         ast_log(LOG_ERROR, "no jingle capable clients to talk to.\n");
788                         if (buddy) {
789                                 ASTOBJ_UNREF(buddy, ast_aji_buddy_destroy);
790                         }
791                         return NULL;
792                 }
793                 if (buddy) {
794                         ASTOBJ_UNREF(buddy, ast_aji_buddy_destroy);
795                 }
796         }
797         if (!(tmp = ast_calloc(1, sizeof(*tmp)))) {
798                 return NULL;
799         }
800
801         tmp->cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_NOLOCK);
802         tmp->jointcap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_NOLOCK);
803         tmp->peercap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_NOLOCK);
804         if (!tmp->cap || !tmp->jointcap || !tmp->peercap) {
805                 tmp->cap = ast_format_cap_destroy(tmp->cap);
806                 tmp->jointcap = ast_format_cap_destroy(tmp->jointcap);
807                 tmp->peercap = ast_format_cap_destroy(tmp->peercap);
808                 ast_free(tmp);
809                 return NULL;
810         }
811         memcpy(&tmp->prefs, &client->prefs, sizeof(tmp->prefs));
812
813         if (sid) {
814                 ast_copy_string(tmp->sid, sid, sizeof(tmp->sid));
815                 ast_copy_string(tmp->them, from, sizeof(tmp->them));
816         } else {
817                 snprintf(tmp->sid, sizeof(tmp->sid), "%08lx%08lx", (unsigned long)ast_random(), (unsigned long)ast_random());
818                 ast_copy_string(tmp->them, idroster, sizeof(tmp->them));
819                 tmp->initiator = 1;
820         }
821         ast_sockaddr_from_sin(&bindaddr_tmp, &bindaddr);
822         tmp->rtp = ast_rtp_instance_new("asterisk", sched, &bindaddr_tmp, NULL);
823         tmp->parent = client;
824         if (!tmp->rtp) {
825                 ast_log(LOG_WARNING, "Out of RTP sessions?\n");
826                 ast_free(tmp);
827                 return NULL;
828         }
829         ast_copy_string(tmp->exten, "s", sizeof(tmp->exten));
830         ast_mutex_init(&tmp->lock);
831         ast_mutex_lock(&jinglelock);
832         tmp->next = client->p;
833         client->p = tmp;
834         ast_mutex_unlock(&jinglelock);
835         return tmp;
836 }
837
838 static void jingle_set_owner(struct jingle_pvt *pvt, struct ast_channel *chan)
839 {
840         pvt->owner = chan;
841         if (pvt->rtp) {
842                 ast_rtp_instance_set_channel_id(pvt->rtp, pvt->owner ? ast_channel_uniqueid(pvt->owner) : "");
843         }
844         if (pvt->vrtp) {
845                 ast_rtp_instance_set_channel_id(pvt->vrtp, pvt->owner ? ast_channel_uniqueid(pvt->owner) : "");
846         }
847 }
848
849 /*! \brief Start new jingle channel */
850 static struct ast_channel *jingle_new(struct jingle *client, struct jingle_pvt *i, int state, const char *title, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor)
851 {
852         struct ast_channel *tmp;
853         struct ast_format_cap *what;  /* SHALLOW COPY DO NOT DESTROY */
854         struct ast_format tmpfmt;
855         const char *str;
856
857         if (title)
858                 str = title;
859         else
860                 str = i->them;
861         tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, "", "", "", assignedids, requestor, 0, "Jingle/%s-%04lx", str, ast_random() & 0xffff);
862         if (!tmp) {
863                 ast_log(LOG_WARNING, "Unable to allocate Jingle channel structure!\n");
864                 return NULL;
865         }
866
867         ast_channel_stage_snapshot(tmp);
868
869         ast_channel_tech_set(tmp, &jingle_tech);
870
871         /* Select our native format based on codec preference until we receive
872            something from another device to the contrary. */
873         if (!ast_format_cap_is_empty(i->jointcap))
874                 what = i->jointcap;
875         else if (!(ast_format_cap_is_empty(i->cap)))
876                 what = i->cap;
877         else
878                 what = global_capability;
879
880         /* Set Frame packetization */
881         if (i->rtp)
882                 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(i->rtp), i->rtp, &i->prefs);
883
884         ast_codec_choose(&i->prefs, what, 1, &tmpfmt);
885         ast_format_cap_add(ast_channel_nativeformats(tmp), &tmpfmt);
886
887         ast_format_cap_iter_start(i->jointcap);
888         while (!(ast_format_cap_iter_next(i->jointcap, &tmpfmt))) {
889                 if (AST_FORMAT_GET_TYPE(tmpfmt.id) == AST_FORMAT_TYPE_VIDEO) {
890                         ast_format_cap_add(ast_channel_nativeformats(tmp), &tmpfmt);
891                 }
892         }
893         ast_format_cap_iter_end(i->jointcap);
894
895         if (i->rtp) {
896                 ast_channel_set_fd(tmp, 0, ast_rtp_instance_fd(i->rtp, 0));
897                 ast_channel_set_fd(tmp, 1, ast_rtp_instance_fd(i->rtp, 1));
898         }
899         if (i->vrtp) {
900                 ast_channel_set_fd(tmp, 2, ast_rtp_instance_fd(i->vrtp, 0));
901                 ast_channel_set_fd(tmp, 3, ast_rtp_instance_fd(i->vrtp, 1));
902         }
903         if (state == AST_STATE_RING)
904                 ast_channel_rings_set(tmp, 1);
905         ast_channel_adsicpe_set(tmp, AST_ADSI_UNAVAILABLE);
906
907
908         ast_best_codec(ast_channel_nativeformats(tmp), &tmpfmt);
909         ast_format_copy(ast_channel_writeformat(tmp), &tmpfmt);
910         ast_format_copy(ast_channel_rawwriteformat(tmp), &tmpfmt);
911         ast_format_copy(ast_channel_readformat(tmp), &tmpfmt);
912         ast_format_copy(ast_channel_rawreadformat(tmp), &tmpfmt);
913         ast_channel_tech_pvt_set(tmp, i);
914
915         ast_channel_callgroup_set(tmp, client->callgroup);
916         ast_channel_pickupgroup_set(tmp, client->pickupgroup);
917         ast_channel_caller(tmp)->id.name.presentation = client->callingpres;
918         ast_channel_caller(tmp)->id.number.presentation = client->callingpres;
919         if (!ast_strlen_zero(client->accountcode))
920                 ast_channel_accountcode_set(tmp, client->accountcode);
921         if (client->amaflags)
922                 ast_channel_amaflags_set(tmp, client->amaflags);
923         if (!ast_strlen_zero(client->language))
924                 ast_channel_language_set(tmp, client->language);
925         if (!ast_strlen_zero(client->musicclass))
926                 ast_channel_musicclass_set(tmp, client->musicclass);
927         jingle_set_owner(i, tmp);
928         ast_channel_context_set(tmp, client->context);
929         ast_channel_exten_set(tmp, i->exten);
930         /* Don't use ast_set_callerid() here because it will
931          * generate an unnecessary NewCallerID event  */
932         if (!ast_strlen_zero(i->cid_num)) {
933                 ast_channel_caller(tmp)->ani.number.valid = 1;
934                 ast_channel_caller(tmp)->ani.number.str = ast_strdup(i->cid_num);
935         }
936         if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s")) {
937                 ast_channel_dialed(tmp)->number.str = ast_strdup(i->exten);
938         }
939         ast_channel_priority_set(tmp, 1);
940         if (i->rtp)
941                 ast_jb_configure(tmp, &global_jbconf);
942
943         ast_channel_stage_snapshot_done(tmp);
944         ast_channel_unlock(tmp);
945
946         if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
947                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", ast_channel_name(tmp));
948                 ast_channel_hangupcause_set(tmp, AST_CAUSE_SWITCH_CONGESTION);
949                 ast_hangup(tmp);
950                 tmp = NULL;
951         }
952
953         return tmp;
954 }
955
956 static int jingle_action(struct jingle *client, struct jingle_pvt *p, const char *action)
957 {
958         iks *iq, *jingle = NULL;
959         int res = -1;
960
961         iq = iks_new("iq");
962         jingle = iks_new("jingle");
963         
964         if (iq) {
965                 iks_insert_attrib(iq, "type", "set");
966                 iks_insert_attrib(iq, "from", client->connection->jid->full);
967                 iks_insert_attrib(iq, "to", p->them);
968                 iks_insert_attrib(iq, "id", client->connection->mid);
969                 ast_aji_increment_mid(client->connection->mid);
970                 if (jingle) {
971                         iks_insert_attrib(jingle, "action", action);
972                         iks_insert_attrib(jingle, JINGLE_SID, p->sid);
973                         iks_insert_attrib(jingle, "initiator", p->initiator ? client->connection->jid->full : p->them);
974                         iks_insert_attrib(jingle, "xmlns", JINGLE_NS);
975
976                         iks_insert_node(iq, jingle);
977
978                         ast_aji_send(client->connection, iq);
979                         res = 0;
980                 }
981         }
982         
983         iks_delete(jingle);
984         iks_delete(iq);
985         
986         return res;
987 }
988
989 static void jingle_free_candidates(struct jingle_candidate *candidate)
990 {
991         struct jingle_candidate *last;
992         while (candidate) {
993                 last = candidate;
994                 candidate = candidate->next;
995                 ast_free(last);
996         }
997 }
998
999 static void jingle_free_pvt(struct jingle *client, struct jingle_pvt *p)
1000 {
1001         struct jingle_pvt *cur, *prev = NULL;
1002         cur = client->p;
1003         while (cur) {
1004                 if (cur == p) {
1005                         if (prev)
1006                                 prev->next = p->next;
1007                         else
1008                                 client->p = p->next;
1009                         break;
1010                 }
1011                 prev = cur;
1012                 cur = cur->next;
1013         }
1014         if (p->ringrule)
1015                 iks_filter_remove_rule(p->parent->connection->f, p->ringrule);
1016         if (p->owner)
1017                 ast_log(LOG_WARNING, "Uh oh, there's an owner, this is going to be messy.\n");
1018         if (p->rtp)
1019                 ast_rtp_instance_destroy(p->rtp);
1020         if (p->vrtp)
1021                 ast_rtp_instance_destroy(p->vrtp);
1022         jingle_free_candidates(p->theircandidates);
1023         p->cap = ast_format_cap_destroy(p->cap);
1024         p->jointcap = ast_format_cap_destroy(p->jointcap);
1025         p->peercap = ast_format_cap_destroy(p->peercap);
1026
1027         ast_free(p);
1028 }
1029
1030
1031 static int jingle_newcall(struct jingle *client, ikspak *pak)
1032 {
1033         struct jingle_pvt *p, *tmp = client->p;
1034         struct ast_channel *chan;
1035         int res;
1036         iks *codec, *content, *description;
1037         char *from = NULL;
1038
1039         /* Make sure our new call doesn't exist yet */
1040         from = iks_find_attrib(pak->x,"to");
1041         if(!from)
1042                 from = client->connection->jid->full;
1043
1044         while (tmp) {
1045                 if (iks_find_with_attrib(pak->x, JINGLE_NODE, JINGLE_SID, tmp->sid)) {
1046                         ast_log(LOG_NOTICE, "Ignoring duplicate call setup on SID %s\n", tmp->sid);
1047                         jingle_response(client, pak, "out-of-order", NULL);
1048                         return -1;
1049                 }
1050                 tmp = tmp->next;
1051         }
1052
1053         if (!strcasecmp(client->name, "guest")){
1054                 /* the guest account is not tied to any configured XMPP client,
1055                    let's set it now */
1056                 if (client->connection) {
1057                         ASTOBJ_UNREF(client->connection, ast_aji_client_destroy);
1058                 }
1059                 client->connection = ast_aji_get_client(from);
1060                 if (!client->connection) {
1061                         ast_log(LOG_ERROR, "No XMPP client to talk to, us (partial JID) : %s\n", from);
1062                         return -1;
1063                 }
1064         }
1065
1066         p = jingle_alloc(client, pak->from->partial, iks_find_attrib(pak->query, JINGLE_SID));
1067         if (!p) {
1068                 ast_log(LOG_WARNING, "Unable to allocate jingle structure!\n");
1069                 return -1;
1070         }
1071         chan = jingle_new(client, p, AST_STATE_DOWN, pak->from->user, NULL, NULL);
1072         if (!chan) {
1073                 jingle_free_pvt(client, p);
1074                 return -1;
1075         }
1076         ast_mutex_lock(&p->lock);
1077         ast_copy_string(p->them, pak->from->full, sizeof(p->them));
1078         if (iks_find_attrib(pak->query, JINGLE_SID)) {
1079                 ast_copy_string(p->sid, iks_find_attrib(pak->query, JINGLE_SID),
1080                                 sizeof(p->sid));
1081         }
1082         
1083         /* content points to the first <content/> tag */        
1084         content = iks_child(iks_child(pak->x));
1085         while (content) {
1086                 description = iks_find_with_attrib(content, "description", "xmlns", JINGLE_AUDIO_RTP_NS);
1087                 if (description) {
1088                         /* audio content found */
1089                         codec = iks_child(iks_child(content));
1090                         ast_copy_string(p->audio_content_name, iks_find_attrib(content, "name"), sizeof(p->audio_content_name));
1091
1092                         while (codec) {
1093                                 ast_rtp_codecs_payloads_set_m_type(ast_rtp_instance_get_codecs(p->rtp), p->rtp, atoi(iks_find_attrib(codec, "id")));
1094                                 ast_rtp_codecs_payloads_set_rtpmap_type(ast_rtp_instance_get_codecs(p->rtp), p->rtp, atoi(iks_find_attrib(codec, "id")), "audio", iks_find_attrib(codec, "name"), 0);
1095                                 codec = iks_next(codec);
1096                         }
1097                 }
1098                 
1099                 description = NULL;
1100                 codec = NULL;
1101
1102                 description = iks_find_with_attrib(content, "description", "xmlns", JINGLE_VIDEO_RTP_NS);
1103                 if (description) {
1104                         /* video content found */
1105                         codec = iks_child(iks_child(content));
1106                         ast_copy_string(p->video_content_name, iks_find_attrib(content, "name"), sizeof(p->video_content_name));
1107
1108                         while (codec) {
1109                                 ast_rtp_codecs_payloads_set_m_type(ast_rtp_instance_get_codecs(p->rtp), p->rtp, atoi(iks_find_attrib(codec, "id")));
1110                                 ast_rtp_codecs_payloads_set_rtpmap_type(ast_rtp_instance_get_codecs(p->rtp), p->rtp, atoi(iks_find_attrib(codec, "id")), "audio", iks_find_attrib(codec, "name"), 0);
1111                                 codec = iks_next(codec);
1112                         }
1113                 }
1114                 
1115                 content = iks_next(content);
1116         }
1117
1118         ast_mutex_unlock(&p->lock);
1119         ast_channel_lock(chan);
1120         ast_setstate(chan, AST_STATE_RING);
1121         ast_channel_unlock(chan);
1122         res = ast_pbx_start(chan);
1123         
1124         switch (res) {
1125         case AST_PBX_FAILED:
1126                 ast_log(LOG_WARNING, "Failed to start PBX :(\n");
1127                 jingle_response(client, pak, "service-unavailable", NULL);
1128                 break;
1129         case AST_PBX_CALL_LIMIT:
1130                 ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
1131                 jingle_response(client, pak, "service-unavailable", NULL);
1132                 break;
1133         case AST_PBX_SUCCESS:
1134                 jingle_response(client, pak, NULL, NULL);
1135                 jingle_create_candidates(client, p,
1136                                          iks_find_attrib(pak->query, JINGLE_SID),
1137                                          iks_find_attrib(pak->x, "from"));
1138                 /* nothing to do */
1139                 break;
1140         }
1141
1142         return 1;
1143 }
1144
1145 static int jingle_update_stun(struct jingle *client, struct jingle_pvt *p)
1146 {
1147         struct jingle_candidate *tmp;
1148         struct hostent *hp;
1149         struct ast_hostent ahp;
1150         struct sockaddr_in sin;
1151         struct ast_sockaddr sin_tmp;
1152
1153         if (time(NULL) == p->laststun)
1154                 return 0;
1155
1156         tmp = p->theircandidates;
1157         p->laststun = time(NULL);
1158         while (tmp) {
1159                 char username[256];
1160                 hp = ast_gethostbyname(tmp->ip, &ahp);
1161                 sin.sin_family = AF_INET;
1162                 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
1163                 sin.sin_port = htons(tmp->port);
1164                 snprintf(username, sizeof(username), "%s:%s", tmp->ufrag, p->ourcandidates->ufrag);
1165
1166                 ast_sockaddr_from_sin(&sin_tmp, &sin);
1167                 ast_rtp_instance_stun_request(p->rtp, &sin_tmp, username);
1168                 tmp = tmp->next;
1169         }
1170         return 1;
1171 }
1172
1173 static int jingle_add_candidate(struct jingle *client, ikspak *pak)
1174 {
1175         struct jingle_pvt *p = NULL, *tmp = NULL;
1176         struct aji_client *c = client->connection;
1177         struct jingle_candidate *newcandidate = NULL;
1178         iks *traversenodes = NULL, *receipt = NULL;
1179
1180         for (tmp = client->p; tmp; tmp = tmp->next) {
1181                 if (iks_find_with_attrib(pak->x, JINGLE_NODE, JINGLE_SID, tmp->sid)) {
1182                         p = tmp;
1183                         break;
1184                 }
1185         }
1186
1187         if (!p)
1188                 return -1;
1189
1190         traversenodes = pak->query;
1191         while(traversenodes) {
1192                 if(!strcasecmp(iks_name(traversenodes), "jingle")) {
1193                         traversenodes = iks_child(traversenodes);
1194                         continue;
1195                 }
1196                 if(!strcasecmp(iks_name(traversenodes), "content")) {
1197                         traversenodes = iks_child(traversenodes);
1198                         continue;
1199                 }
1200                 if(!strcasecmp(iks_name(traversenodes), "transport")) {
1201                         traversenodes = iks_child(traversenodes);
1202                         continue;
1203                 }
1204
1205                 if(!strcasecmp(iks_name(traversenodes), "candidate")) {
1206                         newcandidate = ast_calloc(1, sizeof(*newcandidate));
1207                         if (!newcandidate)
1208                                 return 0;
1209                         ast_copy_string(newcandidate->ip, iks_find_attrib(traversenodes, "ip"), sizeof(newcandidate->ip));
1210                         newcandidate->port = atoi(iks_find_attrib(traversenodes, "port"));
1211                         ast_copy_string(newcandidate->password, iks_find_attrib(traversenodes, "pwd"), sizeof(newcandidate->password));
1212                         if (!strcasecmp(iks_find_attrib(traversenodes, "protocol"), "udp"))
1213                                 newcandidate->protocol = AJI_PROTOCOL_UDP;
1214                         else if (!strcasecmp(iks_find_attrib(traversenodes, "protocol"), "ssltcp"))
1215                                 newcandidate->protocol = AJI_PROTOCOL_SSLTCP;
1216                         
1217                         if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "host"))
1218                                 newcandidate->type = AJI_CONNECT_HOST;
1219                         else if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "prflx"))
1220                                 newcandidate->type = AJI_CONNECT_PRFLX;
1221                         else if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "relay"))
1222                                 newcandidate->type = AJI_CONNECT_RELAY;
1223                         else if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "srflx"))
1224                                 newcandidate->type = AJI_CONNECT_SRFLX;
1225
1226                         newcandidate->network = atoi(iks_find_attrib(traversenodes, "network"));
1227                         newcandidate->generation = atoi(iks_find_attrib(traversenodes, "generation"));
1228                         newcandidate->next = NULL;
1229                 
1230                         newcandidate->next = p->theircandidates;
1231                         p->theircandidates = newcandidate;
1232                         p->laststun = 0;
1233                         jingle_update_stun(p->parent, p);
1234                         newcandidate = NULL;
1235                 }
1236                 traversenodes = iks_next(traversenodes);
1237         }
1238         
1239         receipt = iks_new("iq");
1240         iks_insert_attrib(receipt, "type", "result");
1241         iks_insert_attrib(receipt, "from", c->jid->full);
1242         iks_insert_attrib(receipt, "to", iks_find_attrib(pak->x, "from"));
1243         iks_insert_attrib(receipt, "id", iks_find_attrib(pak->x, "id"));
1244         ast_aji_send(c, receipt);
1245
1246         iks_delete(receipt);
1247
1248         return 1;
1249 }
1250
1251 static struct ast_frame *jingle_rtp_read(struct ast_channel *ast, struct jingle_pvt *p)
1252 {
1253         struct ast_frame *f;
1254
1255         if (!p->rtp)
1256                 return &ast_null_frame;
1257         f = ast_rtp_instance_read(p->rtp, 0);
1258         jingle_update_stun(p->parent, p);
1259         if (p->owner) {
1260                 /* We already hold the channel lock */
1261                 if (f->frametype == AST_FRAME_VOICE) {
1262                         if (!(ast_format_cap_iscompatible(ast_channel_nativeformats(p->owner), &f->subclass.format))) {
1263                                 ast_debug(1, "Oooh, format changed to %s\n", ast_getformatname(&f->subclass.format));
1264                                 ast_format_cap_remove_bytype(ast_channel_nativeformats(p->owner), AST_FORMAT_TYPE_AUDIO);
1265                                 ast_format_cap_add(ast_channel_nativeformats(p->owner), &f->subclass.format);
1266                                 ast_set_read_format(p->owner, ast_channel_readformat(p->owner));
1267                                 ast_set_write_format(p->owner, ast_channel_writeformat(p->owner));
1268                         }
1269 /*                      if ((ast_test_flag(p, SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
1270                                 f = ast_dsp_process(p->owner, p->vad, f);
1271                                 if (f && (f->frametype == AST_FRAME_DTMF))
1272                                         ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass.codec);
1273                         } */
1274                 }
1275         }
1276         return f;
1277 }
1278
1279 static struct ast_frame *jingle_read(struct ast_channel *ast)
1280 {
1281         struct ast_frame *fr;
1282         struct jingle_pvt *p = ast_channel_tech_pvt(ast);
1283
1284         ast_mutex_lock(&p->lock);
1285         fr = jingle_rtp_read(ast, p);
1286         ast_mutex_unlock(&p->lock);
1287         return fr;
1288 }
1289
1290 /*! \brief Send frame to media channel (rtp) */
1291 static int jingle_write(struct ast_channel *ast, struct ast_frame *frame)
1292 {
1293         struct jingle_pvt *p = ast_channel_tech_pvt(ast);
1294         int res = 0;
1295         char buf[256];
1296
1297         switch (frame->frametype) {
1298         case AST_FRAME_VOICE:
1299                 if (!(ast_format_cap_iscompatible(ast_channel_nativeformats(ast), &frame->subclass.format))) {
1300                         ast_log(LOG_WARNING,
1301                                         "Asked to transmit frame type %s, while native formats is %s (read/write = %s/%s)\n",
1302                                         ast_getformatname(&frame->subclass.format),
1303                                         ast_getformatname_multiple(buf, sizeof(buf), ast_channel_nativeformats(ast)),
1304                                         ast_getformatname(ast_channel_readformat(ast)),
1305                                         ast_getformatname(ast_channel_writeformat(ast)));
1306                         return 0;
1307                 }
1308                 if (p) {
1309                         ast_mutex_lock(&p->lock);
1310                         if (p->rtp) {
1311                                 res = ast_rtp_instance_write(p->rtp, frame);
1312                         }
1313                         ast_mutex_unlock(&p->lock);
1314                 }
1315                 break;
1316         case AST_FRAME_VIDEO:
1317                 if (p) {
1318                         ast_mutex_lock(&p->lock);
1319                         if (p->vrtp) {
1320                                 res = ast_rtp_instance_write(p->vrtp, frame);
1321                         }
1322                         ast_mutex_unlock(&p->lock);
1323                 }
1324                 break;
1325         case AST_FRAME_IMAGE:
1326                 return 0;
1327                 break;
1328         default:
1329                 ast_log(LOG_WARNING, "Can't send %u type frames with Jingle write\n",
1330                                 frame->frametype);
1331                 return 0;
1332         }
1333
1334         return res;
1335 }
1336
1337 static int jingle_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1338 {
1339         struct jingle_pvt *p = ast_channel_tech_pvt(newchan);
1340         ast_mutex_lock(&p->lock);
1341
1342         if ((p->owner != oldchan)) {
1343                 ast_mutex_unlock(&p->lock);
1344                 return -1;
1345         }
1346         if (p->owner == oldchan) {
1347                 jingle_set_owner(p, newchan);
1348         }
1349         ast_mutex_unlock(&p->lock);
1350         return 0;
1351 }
1352
1353 static int jingle_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
1354 {
1355         int res = 0;
1356
1357         switch (condition) {
1358         case AST_CONTROL_HOLD:
1359                 ast_moh_start(ast, data, NULL);
1360                 break;
1361         case AST_CONTROL_UNHOLD:
1362                 ast_moh_stop(ast);
1363                 break;
1364         default:
1365                 ast_log(LOG_NOTICE, "Don't know how to indicate condition '%d'\n", condition);
1366                 /* fallthrough */
1367         case AST_CONTROL_PVT_CAUSE_CODE:
1368                 res = -1;
1369         }
1370
1371         return res;
1372 }
1373
1374 static int jingle_sendtext(struct ast_channel *chan, const char *text)
1375 {
1376         int res = 0;
1377         struct aji_client *client = NULL;
1378         struct jingle_pvt *p = ast_channel_tech_pvt(chan);
1379
1380
1381         if (!p->parent) {
1382                 ast_log(LOG_ERROR, "Parent channel not found\n");
1383                 return -1;
1384         }
1385         if (!p->parent->connection) {
1386                 ast_log(LOG_ERROR, "XMPP client not found\n");
1387                 return -1;
1388         }
1389         client = p->parent->connection;
1390         res = ast_aji_send_chat(client, p->them, text);
1391         return res;
1392 }
1393
1394 static int jingle_digit(struct ast_channel *ast, char digit, unsigned int duration)
1395 {
1396         struct jingle_pvt *p = ast_channel_tech_pvt(ast);
1397         struct jingle *client = p->parent;
1398         iks *iq, *jingle, *dtmf;
1399         char buffer[2] = {digit, '\0'};
1400         iq = iks_new("iq");
1401         jingle = iks_new("jingle");
1402         dtmf = iks_new("dtmf");
1403         if(!iq || !jingle || !dtmf) {
1404                 iks_delete(iq);
1405                 iks_delete(jingle);
1406                 iks_delete(dtmf);
1407                 ast_log(LOG_ERROR, "Did not send dtmf do to memory issue\n");
1408                 return -1;
1409         }
1410
1411         iks_insert_attrib(iq, "type", "set");
1412         iks_insert_attrib(iq, "to", p->them);
1413         iks_insert_attrib(iq, "from", client->connection->jid->full);
1414         iks_insert_attrib(iq, "id", client->connection->mid);
1415         ast_aji_increment_mid(client->connection->mid);
1416         iks_insert_attrib(jingle, "xmlns", JINGLE_NS);
1417         iks_insert_attrib(jingle, "action", "session-info");
1418         iks_insert_attrib(jingle, "initiator", p->initiator ? client->connection->jid->full : p->them);
1419         iks_insert_attrib(jingle, "sid", p->sid);
1420         iks_insert_attrib(dtmf, "xmlns", JINGLE_DTMF_NS);
1421         iks_insert_attrib(dtmf, "code", buffer);
1422         iks_insert_node(iq, jingle);
1423         iks_insert_node(jingle, dtmf);
1424
1425         ast_mutex_lock(&p->lock);
1426         if (ast_channel_dtmff(ast)->frametype == AST_FRAME_DTMF_BEGIN || duration == 0) {
1427                 iks_insert_attrib(dtmf, "action", "button-down");
1428         } else if (ast_channel_dtmff(ast)->frametype == AST_FRAME_DTMF_END || duration != 0) {
1429                 iks_insert_attrib(dtmf, "action", "button-up");
1430         }
1431         ast_aji_send(client->connection, iq);
1432
1433         iks_delete(iq);
1434         iks_delete(jingle);
1435         iks_delete(dtmf);
1436         ast_mutex_unlock(&p->lock);
1437         return 0;
1438 }
1439
1440 static int jingle_digit_begin(struct ast_channel *chan, char digit)
1441 {
1442         return jingle_digit(chan, digit, 0);
1443 }
1444
1445 static int jingle_digit_end(struct ast_channel *ast, char digit, unsigned int duration)
1446 {
1447         return jingle_digit(ast, digit, duration);
1448 }
1449
1450 static int jingle_sendhtml(struct ast_channel *ast, int subclass, const char *data, int datalen)
1451 {
1452         ast_log(LOG_NOTICE, "XXX Implement jingle sendhtml XXX\n");
1453
1454         return -1;
1455 }
1456 static int jingle_transmit_invite(struct jingle_pvt *p)
1457 {
1458         struct jingle *aux = NULL;
1459         struct aji_client *client = NULL;
1460         iks *iq, *jingle, *content, *description, *transport;
1461         iks *payload_eg711u, *payload_pcmu;
1462
1463         aux = p->parent;
1464         client = aux->connection;
1465         iq = iks_new("iq");
1466         jingle = iks_new(JINGLE_NODE);
1467         content = iks_new("content");
1468         description = iks_new("description");
1469         transport = iks_new("transport");
1470         payload_pcmu = iks_new("payload-type");
1471         payload_eg711u = iks_new("payload-type");
1472
1473         ast_copy_string(p->audio_content_name, "asterisk-audio-content", sizeof(p->audio_content_name));
1474
1475         iks_insert_attrib(iq, "type", "set");
1476         iks_insert_attrib(iq, "to", p->them);
1477         iks_insert_attrib(iq, "from", client->jid->full);
1478         iks_insert_attrib(iq, "id", client->mid);
1479         ast_aji_increment_mid(client->mid);
1480         iks_insert_attrib(jingle, "action", JINGLE_INITIATE);
1481         iks_insert_attrib(jingle, JINGLE_SID, p->sid);
1482         iks_insert_attrib(jingle, "initiator", client->jid->full);
1483         iks_insert_attrib(jingle, "xmlns", JINGLE_NS);
1484
1485         /* For now, we only send one audio based content */
1486         iks_insert_attrib(content, "creator", "initiator");
1487         iks_insert_attrib(content, "name", p->audio_content_name);
1488         iks_insert_attrib(content, "profile", "RTP/AVP");
1489         iks_insert_attrib(description, "xmlns", JINGLE_AUDIO_RTP_NS);
1490         iks_insert_attrib(transport, "xmlns", JINGLE_ICE_UDP_NS);
1491         iks_insert_attrib(payload_pcmu, "id", "0");
1492         iks_insert_attrib(payload_pcmu, "name", "PCMU");
1493         iks_insert_attrib(payload_eg711u, "id", "100");
1494         iks_insert_attrib(payload_eg711u, "name", "EG711U");
1495         iks_insert_node(description, payload_pcmu);
1496         iks_insert_node(description, payload_eg711u);
1497         iks_insert_node(content, description);
1498         iks_insert_node(content, transport);
1499         iks_insert_node(jingle, content);
1500         iks_insert_node(iq, jingle);
1501
1502         ast_aji_send(client, iq);
1503
1504         iks_delete(iq);
1505         iks_delete(jingle);
1506         iks_delete(content);
1507         iks_delete(description);
1508         iks_delete(transport);
1509         iks_delete(payload_eg711u);
1510         iks_delete(payload_pcmu);
1511         return 0;
1512 }
1513
1514 /* Not in use right now.
1515 static int jingle_auto_congest(void *nothing)
1516 {
1517         struct jingle_pvt *p = nothing;
1518
1519         ast_mutex_lock(&p->lock);
1520         if (p->owner) {
1521                 if (!ast_channel_trylock(p->owner)) {
1522                         ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
1523                         ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
1524                         ast_channel_unlock(p->owner);
1525                 }
1526         }
1527         ast_mutex_unlock(&p->lock);
1528         return 0;
1529 }
1530 */
1531
1532 /*! \brief Initiate new call, part of PBX interface 
1533  *      dest is the dial string */
1534 static int jingle_call(struct ast_channel *ast, const char *dest, int timeout)
1535 {
1536         struct jingle_pvt *p = ast_channel_tech_pvt(ast);
1537
1538         if ((ast_channel_state(ast) != AST_STATE_DOWN) && (ast_channel_state(ast) != AST_STATE_RESERVED)) {
1539                 ast_log(LOG_WARNING, "jingle_call called on %s, neither down nor reserved\n", ast_channel_name(ast));
1540                 return -1;
1541         }
1542
1543         ast_setstate(ast, AST_STATE_RING);
1544         ast_format_cap_copy(p->jointcap, p->cap);
1545         if (!p->ringrule) {
1546                 ast_copy_string(p->ring, p->parent->connection->mid, sizeof(p->ring));
1547                 p->ringrule = iks_filter_add_rule(p->parent->connection->f, jingle_ringing_ack, p,
1548                                                         IKS_RULE_ID, p->ring, IKS_RULE_DONE);
1549         } else
1550                 ast_log(LOG_WARNING, "Whoa, already have a ring rule!\n");
1551
1552         jingle_transmit_invite(p);
1553         jingle_create_candidates(p->parent, p, p->sid, p->them);
1554
1555         return 0;
1556 }
1557
1558 /*! \brief Hangup a call through the jingle proxy channel */
1559 static int jingle_hangup(struct ast_channel *ast)
1560 {
1561         struct jingle_pvt *p = ast_channel_tech_pvt(ast);
1562         struct jingle *client;
1563
1564         ast_mutex_lock(&p->lock);
1565         client = p->parent;
1566         jingle_set_owner(p, NULL);
1567         ast_channel_tech_pvt_set(ast, NULL);
1568         if (!p->alreadygone)
1569                 jingle_action(client, p, JINGLE_TERMINATE);
1570         ast_mutex_unlock(&p->lock);
1571
1572         jingle_free_pvt(client, p);
1573
1574         return 0;
1575 }
1576
1577 /*! \brief Part of PBX interface */
1578 static struct ast_channel *jingle_request(const char *type, struct ast_format_cap *cap, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *data, int *cause)
1579 {
1580         struct jingle_pvt *p = NULL;
1581         struct jingle *client = NULL;
1582         char *sender = NULL, *to = NULL, *s = NULL;
1583         struct ast_channel *chan = NULL;
1584
1585         if (data) {
1586                 s = ast_strdupa(data);
1587                 sender = strsep(&s, "/");
1588                 if (sender && (sender[0] != '\0'))
1589                         to = strsep(&s, "/");
1590                 if (!to) {
1591                         ast_log(LOG_ERROR, "Bad arguments in Jingle Dialstring: %s\n", data);
1592                         return NULL;
1593                 }
1594                 if (!to) {
1595                         ast_log(LOG_ERROR, "Bad arguments in Jingle Dialstring: %s\n", (char*) data);
1596                         return NULL;
1597                 }
1598         }
1599
1600         client = find_jingle(to, sender);
1601         if (!client) {
1602                 ast_log(LOG_WARNING, "Could not find recipient.\n");
1603                 return NULL;
1604         }
1605         if (!strcasecmp(client->name, "guest")){
1606                 /* the guest account is not tied to any configured XMPP client,
1607                    let's set it now */
1608                 if (client->connection) {
1609                         ASTOBJ_UNREF(client->connection, ast_aji_client_destroy);
1610                 }
1611                 client->connection = ast_aji_get_client(sender);
1612                 if (!client->connection) {
1613                         ast_log(LOG_ERROR, "No XMPP client to talk to, us (partial JID) : %s\n", sender);
1614                         return NULL;
1615                 }
1616         }
1617        
1618         ASTOBJ_WRLOCK(client);
1619         p = jingle_alloc(client, to, NULL);
1620         if (p)
1621                 chan = jingle_new(client, p, AST_STATE_DOWN, to, assignedids, requestor);
1622         ASTOBJ_UNLOCK(client);
1623
1624         return chan;
1625 }
1626
1627 /*! \brief CLI command "jingle show channels" */
1628 static char *jingle_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1629 {
1630 #define FORMAT  "%-30.30s  %-30.30s  %-15.15s  %-5.5s %-5.5s \n"
1631         struct jingle_pvt *p;
1632         struct ast_channel *chan;
1633         int numchans = 0;
1634         char them[AJI_MAX_JIDLEN];
1635         char *jid = NULL;
1636         char *resource = NULL;
1637
1638         switch (cmd) {
1639         case CLI_INIT:
1640                 e->command = "jingle show channels";
1641                 e->usage =
1642                         "Usage: jingle show channels\n"
1643                         "       Shows current state of the Jingle channels.\n";
1644                 return NULL;
1645         case CLI_GENERATE:
1646                 return NULL;
1647         }
1648
1649         if (a->argc != 3)
1650                 return CLI_SHOWUSAGE;
1651
1652         ast_mutex_lock(&jinglelock);
1653         ast_cli(a->fd, FORMAT, "Channel", "Jabber ID", "Resource", "Read", "Write");
1654         ASTOBJ_CONTAINER_TRAVERSE(&jingle_list, 1, {
1655                 ASTOBJ_WRLOCK(iterator);
1656                 p = iterator->p;
1657                 while(p) {
1658                         chan = p->owner;
1659                         ast_copy_string(them, p->them, sizeof(them));
1660                         jid = them;
1661                         resource = strchr(them, '/');
1662                         if (!resource)
1663                                 resource = "None";
1664                         else {
1665                                 *resource = '\0';
1666                                 resource ++;
1667                         }
1668                         if (chan)
1669                                 ast_cli(a->fd, FORMAT, 
1670                                         ast_channel_name(chan),
1671                                         jid,
1672                                         resource,
1673                                         ast_getformatname(ast_channel_readformat(chan)),
1674                                         ast_getformatname(ast_channel_writeformat(chan))
1675                                         );
1676                         else 
1677                                 ast_log(LOG_WARNING, "No available channel\n");
1678                         numchans ++;
1679                         p = p->next;
1680                 }
1681                 ASTOBJ_UNLOCK(iterator);
1682         });
1683
1684         ast_mutex_unlock(&jinglelock);
1685
1686         ast_cli(a->fd, "%d active jingle channel%s\n", numchans, (numchans != 1) ? "s" : "");
1687         return CLI_SUCCESS;
1688 #undef FORMAT
1689 }
1690
1691 /*! \brief CLI command "jingle reload" */
1692 static char *jingle_do_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1693 {
1694         switch (cmd) {
1695         case CLI_INIT:
1696                 e->command = "jingle reload";
1697                 e->usage =
1698                         "Usage: jingle reload\n"
1699                         "       Reload jingle channel driver.\n";
1700                 return NULL;
1701         case CLI_GENERATE:
1702                 return NULL;
1703         }       
1704         
1705         return CLI_SUCCESS;
1706 }
1707
1708 static int jingle_parser(void *data, ikspak *pak)
1709 {
1710         struct jingle *client = ASTOBJ_REF((struct jingle *) data);
1711         ast_log(LOG_NOTICE, "Filter matched\n");
1712
1713         if (iks_find_with_attrib(pak->x, JINGLE_NODE, "action", JINGLE_INITIATE)) {
1714                 /* New call */
1715                 jingle_newcall(client, pak);
1716         } else if (iks_find_with_attrib(pak->x, JINGLE_NODE, "action", JINGLE_NEGOTIATE)) {
1717                 ast_debug(3, "About to add candidate!\n");
1718                 jingle_add_candidate(client, pak);
1719                 ast_debug(3, "Candidate Added!\n");
1720         } else if (iks_find_with_attrib(pak->x, JINGLE_NODE, "action", JINGLE_ACCEPT)) {
1721                 jingle_is_answered(client, pak);
1722         } else if (iks_find_with_attrib(pak->x, JINGLE_NODE, "action", JINGLE_INFO)) {
1723                 jingle_handle_dtmf(client, pak);
1724         } else if (iks_find_with_attrib(pak->x, JINGLE_NODE, "action", JINGLE_TERMINATE)) {
1725                 jingle_hangup_farend(client, pak);
1726         } else if (iks_find_with_attrib(pak->x, JINGLE_NODE, "action", "reject")) {
1727                 jingle_hangup_farend(client, pak);
1728         }
1729         ASTOBJ_UNREF(client, jingle_member_destroy);
1730         return IKS_FILTER_EAT;
1731 }
1732 /* Not using this anymore probably take out soon 
1733 static struct jingle_candidate *jingle_create_candidate(char *args)
1734 {
1735         char *name, *type, *preference, *protocol;
1736         struct jingle_candidate *res;
1737         res = ast_calloc(1, sizeof(*res));
1738         if (args)
1739                 name = args;
1740         if ((args = strchr(args, ','))) {
1741                 *args = '\0';
1742                 args++;
1743                 preference = args;
1744         }
1745         if ((args = strchr(args, ','))) {
1746                 *args = '\0';
1747                 args++;
1748                 protocol = args;
1749         }
1750         if ((args = strchr(args, ','))) {
1751                 *args = '\0';
1752                 args++;
1753                 type = args;
1754         }
1755         if (name)
1756                 ast_copy_string(res->name, name, sizeof(res->name));
1757         if (preference) {
1758                 res->preference = atof(preference);
1759         }
1760         if (protocol) {
1761                 if (!strcasecmp("udp", protocol))
1762                         res->protocol = AJI_PROTOCOL_UDP;
1763                 if (!strcasecmp("ssltcp", protocol))
1764                         res->protocol = AJI_PROTOCOL_SSLTCP;
1765         }
1766         if (type) {
1767                 if (!strcasecmp("host", type))
1768                         res->type = AJI_CONNECT_HOST;
1769                 if (!strcasecmp("prflx", type))
1770                         res->type = AJI_CONNECT_PRFLX;
1771                 if (!strcasecmp("relay", type))
1772                         res->type = AJI_CONNECT_RELAY;
1773                 if (!strcasecmp("srflx", type))
1774                         res->type = AJI_CONNECT_SRFLX;
1775         }
1776
1777         return res;
1778 }
1779 */
1780
1781 static int jingle_create_member(char *label, struct ast_variable *var, int allowguest,
1782                                                                 struct ast_codec_pref prefs, char *context,
1783                                                                 struct jingle *member)
1784 {
1785         struct aji_client *client;
1786
1787         if (!member)
1788                 ast_log(LOG_WARNING, "Out of memory.\n");
1789
1790         ast_copy_string(member->name, label, sizeof(member->name));
1791         ast_copy_string(member->user, label, sizeof(member->user));
1792         ast_copy_string(member->context, context, sizeof(member->context));
1793         member->allowguest = allowguest;
1794         member->prefs = prefs;
1795         while (var) {
1796 #if 0
1797                 struct jingle_candidate *candidate = NULL;
1798 #endif
1799                 if (!strcasecmp(var->name, "username"))
1800                         ast_copy_string(member->user, var->value, sizeof(member->user));
1801                 else if (!strcasecmp(var->name, "disallow"))
1802                         ast_parse_allow_disallow(&member->prefs, member->cap, var->value, 0);
1803                 else if (!strcasecmp(var->name, "allow"))
1804                         ast_parse_allow_disallow(&member->prefs, member->cap, var->value, 1);
1805                 else if (!strcasecmp(var->name, "context"))
1806                         ast_copy_string(member->context, var->value, sizeof(member->context));
1807 #if 0
1808                 else if (!strcasecmp(var->name, "candidate")) {
1809                         candidate = jingle_create_candidate(var->value);
1810                         if (candidate) {
1811                                 candidate->next = member->ourcandidates;
1812                                 member->ourcandidates = candidate;
1813                         }
1814                 }
1815 #endif
1816                 else if (!strcasecmp(var->name, "connection")) {
1817                         if ((client = ast_aji_get_client(var->value))) {
1818                                 member->connection = client;
1819                                 iks_filter_add_rule(client->f, jingle_parser, member,
1820                                                     IKS_RULE_TYPE, IKS_PAK_IQ,
1821                                                     IKS_RULE_FROM_PARTIAL, member->user,
1822                                                     IKS_RULE_NS, JINGLE_NS,
1823                                                     IKS_RULE_DONE);
1824                         } else {
1825                                 ast_log(LOG_ERROR, "connection referenced not found!\n");
1826                                 return 0;
1827                         }
1828                 }
1829                 var = var->next;
1830         }
1831         if (member->connection && member->user)
1832                 member->buddy = ASTOBJ_CONTAINER_FIND(&member->connection->buddies, member->user);
1833         else {
1834                 ast_log(LOG_ERROR, "No Connection or Username!\n");
1835         }
1836         return 1;
1837 }
1838
1839 static int jingle_load_config(void)
1840 {
1841         char *cat = NULL;
1842         struct ast_config *cfg = NULL;
1843         char context[100];
1844         int allowguest = 1;
1845         struct ast_variable *var;
1846         struct jingle *member;
1847         struct hostent *hp;
1848         struct ast_hostent ahp;
1849         struct ast_codec_pref prefs;
1850         struct aji_client_container *clients;
1851         struct jingle_candidate *global_candidates = NULL;
1852         struct ast_flags config_flags = { 0 };
1853
1854         cfg = ast_config_load(JINGLE_CONFIG, config_flags);
1855         if (!cfg || cfg == CONFIG_STATUS_FILEINVALID) {
1856                 return 0;
1857         }
1858
1859         /* Copy the default jb config over global_jbconf */
1860         memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
1861
1862         cat = ast_category_browse(cfg, NULL);
1863         for (var = ast_variable_browse(cfg, "general"); var; var = var->next) {
1864                 /* handle jb conf */
1865                 if (!ast_jb_read_conf(&global_jbconf, var->name, var->value))
1866                         continue;
1867
1868                 if (!strcasecmp(var->name, "allowguest"))
1869                         allowguest =
1870                                 (ast_true(ast_variable_retrieve(cfg, "general", "allowguest"))) ? 1 : 0;
1871                 else if (!strcasecmp(var->name, "disallow"))
1872                         ast_parse_allow_disallow(&prefs, global_capability, var->value, 0);
1873                 else if (!strcasecmp(var->name, "allow"))
1874                         ast_parse_allow_disallow(&prefs, global_capability, var->value, 1);
1875                 else if (!strcasecmp(var->name, "context"))
1876                         ast_copy_string(context, var->value, sizeof(context));
1877                 else if (!strcasecmp(var->name, "externip"))
1878                         ast_copy_string(externip, var->value, sizeof(externip));
1879                 else if (!strcasecmp(var->name, "bindaddr")) {
1880                         if (!(hp = ast_gethostbyname(var->value, &ahp))) {
1881                                 ast_log(LOG_WARNING, "Invalid address: %s\n", var->value);
1882                         } else {
1883                                 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
1884                         }
1885                 }
1886 /*  Idea to allow for custom candidates  */
1887 /*
1888                 else if (!strcasecmp(var->name, "candidate")) {
1889                         candidate = jingle_create_candidate(var->value);
1890                         if (candidate) {
1891                                 candidate->next = global_candidates;
1892                                 global_candidates = candidate;
1893                         }
1894                 }
1895 */
1896         }
1897         while (cat) {
1898                 if (strcasecmp(cat, "general")) {
1899                         var = ast_variable_browse(cfg, cat);
1900                         member = ast_calloc(1, sizeof(*member));
1901                         ASTOBJ_INIT(member);
1902                         ASTOBJ_WRLOCK(member);
1903                         member->cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_NOLOCK);
1904                         if (!strcasecmp(cat, "guest")) {
1905                                 ast_copy_string(member->name, "guest", sizeof(member->name));
1906                                 ast_copy_string(member->user, "guest", sizeof(member->user));
1907                                 ast_copy_string(member->context, context, sizeof(member->context));
1908                                 member->allowguest = allowguest;
1909                                 member->prefs = prefs;
1910                                 while (var) {
1911                                         if (!strcasecmp(var->name, "disallow"))
1912                                                 ast_parse_allow_disallow(&member->prefs, member->cap,
1913                                                                                                  var->value, 0);
1914                                         else if (!strcasecmp(var->name, "allow"))
1915                                                 ast_parse_allow_disallow(&member->prefs, member->cap,
1916                                                                                                  var->value, 1);
1917                                         else if (!strcasecmp(var->name, "context"))
1918                                                 ast_copy_string(member->context, var->value,
1919                                                                                 sizeof(member->context));
1920                                         else if (!strcasecmp(var->name, "parkinglot"))
1921                                                 ast_copy_string(member->parkinglot, var->value,
1922                                                                                 sizeof(member->parkinglot));
1923 /*  Idea to allow for custom candidates  */
1924 /*
1925                                         else if (!strcasecmp(var->name, "candidate")) {
1926                                                 candidate = jingle_create_candidate(var->value);
1927                                                 if (candidate) {
1928                                                         candidate->next = member->ourcandidates;
1929                                                         member->ourcandidates = candidate;
1930                                                 }
1931                                         }
1932 */
1933                                         var = var->next;
1934                                 }
1935                                 ASTOBJ_UNLOCK(member);
1936                                 clients = ast_aji_get_clients();
1937                                 if (clients) {
1938                                         ASTOBJ_CONTAINER_TRAVERSE(clients, 1, {
1939                                                 ASTOBJ_WRLOCK(iterator);
1940                                                 ASTOBJ_WRLOCK(member);
1941                                                 if (member->connection) {
1942                                                         ASTOBJ_UNREF(member->connection, ast_aji_client_destroy);
1943                                                 }
1944                                                 member->connection = NULL;
1945                                                 iks_filter_add_rule(iterator->f, jingle_parser, member, IKS_RULE_TYPE, IKS_PAK_IQ, IKS_RULE_NS, JINGLE_NS, IKS_RULE_DONE);
1946                                                 iks_filter_add_rule(iterator->f, jingle_parser, member, IKS_RULE_TYPE, IKS_PAK_IQ, IKS_RULE_NS, JINGLE_DTMF_NS, IKS_RULE_DONE);
1947                                                 ASTOBJ_UNLOCK(member);
1948                                                 ASTOBJ_UNLOCK(iterator);
1949                                         });
1950                                         ASTOBJ_CONTAINER_LINK(&jingle_list, member);
1951                                 } else {
1952                                         ASTOBJ_UNLOCK(member);
1953                                         ASTOBJ_UNREF(member, jingle_member_destroy);
1954                                 }
1955                         } else {
1956                                 ASTOBJ_UNLOCK(member);
1957                                 if (jingle_create_member(cat, var, allowguest, prefs, context, member))
1958                                         ASTOBJ_CONTAINER_LINK(&jingle_list, member);
1959                                 ASTOBJ_UNREF(member, jingle_member_destroy);
1960                         }
1961                 }
1962                 cat = ast_category_browse(cfg, cat);
1963         }
1964         ast_config_destroy(cfg);
1965         jingle_free_candidates(global_candidates);
1966         return 1;
1967 }
1968
1969 /*!
1970  * \brief Load the module
1971  *
1972  * Module loading including tests for configuration or dependencies.
1973  * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
1974  * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
1975  * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the 
1976  * configuration file or other non-critical problem return 
1977  * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
1978  */
1979 static int load_module(void)
1980 {
1981         struct ast_sockaddr ourip_tmp;
1982         struct ast_sockaddr bindaddr_tmp;
1983         struct ast_format tmpfmt;
1984
1985         char *jabber_loaded = ast_module_helper("", "res_jabber.so", 0, 0, 0, 0);
1986
1987         if (!(jingle_tech.capabilities = ast_format_cap_alloc(0))) {
1988                 return AST_MODULE_LOAD_DECLINE;
1989         }
1990
1991         ast_format_cap_add_all_by_type(jingle_tech.capabilities, AST_FORMAT_TYPE_AUDIO);
1992         if (!(global_capability = ast_format_cap_alloc(0))) {
1993                 return AST_MODULE_LOAD_DECLINE;
1994         }
1995         ast_format_cap_add(global_capability, ast_format_set(&tmpfmt, AST_FORMAT_ULAW, 0));
1996         ast_format_cap_add(global_capability, ast_format_set(&tmpfmt, AST_FORMAT_GSM, 0));
1997         ast_format_cap_add(global_capability, ast_format_set(&tmpfmt, AST_FORMAT_ALAW, 0));
1998         ast_format_cap_add(global_capability, ast_format_set(&tmpfmt, AST_FORMAT_H263, 0));
1999
2000         free(jabber_loaded);
2001         if (!jabber_loaded) {
2002                 /* Dependency module has a different name, if embedded */
2003                 jabber_loaded = ast_module_helper("", "res_jabber", 0, 0, 0, 0);
2004                 free(jabber_loaded);
2005                 if (!jabber_loaded) {
2006                         ast_log(LOG_ERROR, "chan_jingle.so depends upon res_jabber.so\n");
2007                         return AST_MODULE_LOAD_DECLINE;
2008                 }
2009         }
2010
2011         ASTOBJ_CONTAINER_INIT(&jingle_list);
2012         if (!jingle_load_config()) {
2013                 ast_log(LOG_ERROR, "Unable to read config file %s. Not loading module.\n", JINGLE_CONFIG);
2014                 return AST_MODULE_LOAD_DECLINE;
2015         }
2016
2017         sched = ast_sched_context_create();
2018         if (!sched) {
2019                 ast_log(LOG_WARNING, "Unable to create schedule context\n");
2020         }
2021
2022         io = io_context_create();
2023         if (!io) {
2024                 ast_log(LOG_WARNING, "Unable to create I/O context\n");
2025         }
2026
2027         bindaddr.sin_family = AF_INET;
2028         ast_sockaddr_from_sin(&bindaddr_tmp, &bindaddr);
2029         if (ast_find_ourip(&ourip_tmp, &bindaddr_tmp, AF_INET)) {
2030                 ast_log(LOG_WARNING, "Unable to get own IP address, Jingle disabled\n");
2031                 return 0;
2032         }
2033         __ourip.s_addr = htonl(ast_sockaddr_ipv4(&ourip_tmp));
2034
2035         ast_rtp_glue_register(&jingle_rtp_glue);
2036         ast_cli_register_multiple(jingle_cli, ARRAY_LEN(jingle_cli));
2037         /* Make sure we can register our channel type */
2038         if (ast_channel_register(&jingle_tech)) {
2039                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", channel_type);
2040                 return -1;
2041         }
2042         return 0;
2043 }
2044
2045 /*! \brief Reload module */
2046 static int reload(void)
2047 {
2048         return 0;
2049 }
2050
2051 /*! \brief Unload the jingle channel from Asterisk */
2052 static int unload_module(void)
2053 {
2054         struct jingle_pvt *privates = NULL;
2055         ast_cli_unregister_multiple(jingle_cli, ARRAY_LEN(jingle_cli));
2056         /* First, take us out of the channel loop */
2057         ast_channel_unregister(&jingle_tech);
2058         ast_rtp_glue_unregister(&jingle_rtp_glue);
2059
2060         if (!ast_mutex_lock(&jinglelock)) {
2061                 /* Hangup all interfaces if they have an owner */
2062                 ASTOBJ_CONTAINER_TRAVERSE(&jingle_list, 1, {
2063                         ASTOBJ_WRLOCK(iterator);
2064                         privates = iterator->p;
2065                         while(privates) {
2066                                 if (privates->owner)
2067                                         ast_softhangup(privates->owner, AST_SOFTHANGUP_APPUNLOAD);
2068                                 privates = privates->next;
2069                         }
2070                         iterator->p = NULL;
2071                         ASTOBJ_UNLOCK(iterator);
2072                 });
2073                 ast_mutex_unlock(&jinglelock);
2074         } else {
2075                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
2076                 return -1;
2077         }
2078         ASTOBJ_CONTAINER_DESTROYALL(&jingle_list, jingle_member_destroy);
2079         ASTOBJ_CONTAINER_DESTROY(&jingle_list);
2080
2081         global_capability = ast_format_cap_destroy(global_capability);
2082         return 0;
2083 }
2084
2085 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Jingle Channel Driver",
2086                 .load = load_module,
2087                 .unload = unload_module,
2088                 .reload = reload,
2089                 .load_pri = AST_MODPRI_CHANNEL_DRIVER,
2090                );