e3ef9eb16e065fc3aa9d15f984d0d650e9463b09
[asterisk/asterisk.git] / res / ari / resource_channels.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2012 - 2013, Digium, Inc.
5  *
6  * David M. Lee, II <dlee@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  * \brief Implementation for ARI stubs.
22  *
23  * \author David M. Lee, II <dlee@digium.com>
24  */
25
26 /*** MODULEINFO
27         <depend type="module">res_stasis_app_playback</depend>
28         <support_level>core</support_level>
29  ***/
30
31 #include "asterisk.h"
32
33 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
34
35 #include "asterisk/file.h"
36 #include "asterisk/pbx.h"
37 #include "asterisk/bridge.h"
38 #include "asterisk/callerid.h"
39 #include "asterisk/stasis_app.h"
40 #include "asterisk/stasis_app_playback.h"
41 #include "asterisk/stasis_app_recording.h"
42 #include "asterisk/stasis_app_snoop.h"
43 #include "asterisk/stasis_channels.h"
44 #include "asterisk/causes.h"
45 #include "asterisk/format_cache.h"
46 #include "asterisk/core_local.h"
47 #include "asterisk/dial.h"
48 #include "resource_channels.h"
49
50 #include <limits.h>
51
52 /*!
53  * \brief Finds the control object for a channel, filling the response with an
54  * error, if appropriate.
55  * \param[out] response Response to fill with an error if control is not found.
56  * \param channel_id ID of the channel to lookup.
57  * \return Channel control object.
58  * \return \c NULL if control object does not exist.
59  */
60 static struct stasis_app_control *find_control(
61         struct ast_ari_response *response,
62         const char *channel_id)
63 {
64         RAII_VAR(struct stasis_app_control *, control, NULL, ao2_cleanup);
65
66         ast_assert(response != NULL);
67
68         control = stasis_app_control_find_by_channel_id(channel_id);
69         if (control == NULL) {
70                 /* Distinguish between 404 and 409 errors */
71                 RAII_VAR(struct ast_channel *, chan, NULL, ao2_cleanup);
72                 chan = ast_channel_get_by_name(channel_id);
73                 if (chan == NULL) {
74                         ast_ari_response_error(response, 404, "Not Found",
75                                    "Channel not found");
76                         return NULL;
77                 }
78
79                 ast_ari_response_error(response, 409, "Conflict",
80                            "Channel not in Stasis application");
81                 return NULL;
82         }
83
84         ao2_ref(control, +1);
85         return control;
86 }
87
88 void ast_ari_channels_continue_in_dialplan(
89         struct ast_variable *headers,
90         struct ast_ari_channels_continue_in_dialplan_args *args,
91         struct ast_ari_response *response)
92 {
93         RAII_VAR(struct stasis_app_control *, control, NULL, ao2_cleanup);
94
95         ast_assert(response != NULL);
96
97         control = find_control(response, args->channel_id);
98         if (control == NULL) {
99                 return;
100         }
101
102         if (stasis_app_control_continue(control, args->context, args->extension, args->priority)) {
103                 ast_ari_response_alloc_failed(response);
104                 return;
105         }
106
107         ast_ari_response_no_content(response);
108 }
109
110 void ast_ari_channels_answer(struct ast_variable *headers,
111         struct ast_ari_channels_answer_args *args,
112         struct ast_ari_response *response)
113 {
114         RAII_VAR(struct stasis_app_control *, control, NULL, ao2_cleanup);
115
116         control = find_control(response, args->channel_id);
117         if (control == NULL) {
118                 return;
119         }
120
121         if (stasis_app_control_answer(control) != 0) {
122                 ast_ari_response_error(
123                         response, 500, "Internal Server Error",
124                         "Failed to answer channel");
125                 return;
126         }
127
128         ast_ari_response_no_content(response);
129 }
130
131 void ast_ari_channels_ring(struct ast_variable *headers,
132         struct ast_ari_channels_ring_args *args,
133         struct ast_ari_response *response)
134 {
135         RAII_VAR(struct stasis_app_control *, control, NULL, ao2_cleanup);
136
137         control = find_control(response, args->channel_id);
138         if (control == NULL) {
139                 return;
140         }
141
142         stasis_app_control_ring(control);
143
144         ast_ari_response_no_content(response);
145 }
146
147 void ast_ari_channels_ring_stop(struct ast_variable *headers,
148         struct ast_ari_channels_ring_stop_args *args,
149         struct ast_ari_response *response)
150 {
151         RAII_VAR(struct stasis_app_control *, control, NULL, ao2_cleanup);
152
153         control = find_control(response, args->channel_id);
154         if (control == NULL) {
155                 return;
156         }
157
158         stasis_app_control_ring_stop(control);
159
160         ast_ari_response_no_content(response);
161 }
162
163 void ast_ari_channels_mute(struct ast_variable *headers,
164         struct ast_ari_channels_mute_args *args,
165         struct ast_ari_response *response)
166 {
167         RAII_VAR(struct stasis_app_control *, control, NULL, ao2_cleanup);
168         unsigned int direction = 0;
169         enum ast_frame_type frametype = AST_FRAME_VOICE;
170
171         control = find_control(response, args->channel_id);
172         if (control == NULL) {
173                 return;
174         }
175
176         if (ast_strlen_zero(args->direction)) {
177                 ast_ari_response_error(
178                         response, 400, "Bad Request",
179                         "Direction is required");
180                 return;
181         }
182
183         if (!strcmp(args->direction, "in")) {
184                 direction = AST_MUTE_DIRECTION_READ;
185         } else if (!strcmp(args->direction, "out")) {
186                 direction = AST_MUTE_DIRECTION_WRITE;
187         } else if (!strcmp(args->direction, "both")) {
188                 direction = AST_MUTE_DIRECTION_READ | AST_MUTE_DIRECTION_WRITE;
189         } else {
190                 ast_ari_response_error(
191                         response, 400, "Bad Request",
192                         "Invalid direction specified");
193                 return;
194         }
195
196         stasis_app_control_mute(control, direction, frametype);
197
198         ast_ari_response_no_content(response);
199 }
200
201 void ast_ari_channels_unmute(struct ast_variable *headers,
202         struct ast_ari_channels_unmute_args *args,
203         struct ast_ari_response *response)
204 {
205         RAII_VAR(struct stasis_app_control *, control, NULL, ao2_cleanup);
206         unsigned int direction = 0;
207         enum ast_frame_type frametype = AST_FRAME_VOICE;
208
209         control = find_control(response, args->channel_id);
210         if (control == NULL) {
211                 return;
212         }
213
214         if (ast_strlen_zero(args->direction)) {
215                 ast_ari_response_error(
216                         response, 400, "Bad Request",
217                         "Direction is required");
218                 return;
219         }
220
221         if (!strcmp(args->direction, "in")) {
222                 direction = AST_MUTE_DIRECTION_READ;
223         } else if (!strcmp(args->direction, "out")) {
224                 direction = AST_MUTE_DIRECTION_WRITE;
225         } else if (!strcmp(args->direction, "both")) {
226                 direction = AST_MUTE_DIRECTION_READ | AST_MUTE_DIRECTION_WRITE;
227         } else {
228                 ast_ari_response_error(
229                         response, 400, "Bad Request",
230                         "Invalid direction specified");
231                 return;
232         }
233
234         stasis_app_control_unmute(control, direction, frametype);
235
236         ast_ari_response_no_content(response);
237 }
238
239 void ast_ari_channels_send_dtmf(struct ast_variable *headers,
240         struct ast_ari_channels_send_dtmf_args *args,
241         struct ast_ari_response *response)
242 {
243         RAII_VAR(struct stasis_app_control *, control, NULL, ao2_cleanup);
244
245         control = find_control(response, args->channel_id);
246         if (control == NULL) {
247                 return;
248         }
249
250         if (ast_strlen_zero(args->dtmf)) {
251                 ast_ari_response_error(
252                         response, 400, "Bad Request",
253                         "DTMF is required");
254                 return;
255         }
256
257         stasis_app_control_dtmf(control, args->dtmf, args->before, args->between, args->duration, args->after);
258
259         ast_ari_response_no_content(response);
260 }
261
262 void ast_ari_channels_hold(struct ast_variable *headers,
263         struct ast_ari_channels_hold_args *args,
264         struct ast_ari_response *response)
265 {
266         RAII_VAR(struct stasis_app_control *, control, NULL, ao2_cleanup);
267
268         control = find_control(response, args->channel_id);
269         if (control == NULL) {
270                 /* Response filled in by find_control */
271                 return;
272         }
273
274         stasis_app_control_hold(control);
275
276         ast_ari_response_no_content(response);
277 }
278
279 void ast_ari_channels_unhold(struct ast_variable *headers,
280         struct ast_ari_channels_unhold_args *args,
281         struct ast_ari_response *response)
282 {
283         RAII_VAR(struct stasis_app_control *, control, NULL, ao2_cleanup);
284
285         control = find_control(response, args->channel_id);
286         if (control == NULL) {
287                 /* Response filled in by find_control */
288                 return;
289         }
290
291         stasis_app_control_unhold(control);
292
293         ast_ari_response_no_content(response);
294 }
295
296 void ast_ari_channels_start_moh(struct ast_variable *headers,
297         struct ast_ari_channels_start_moh_args *args,
298         struct ast_ari_response *response)
299 {
300         RAII_VAR(struct stasis_app_control *, control, NULL, ao2_cleanup);
301
302         control = find_control(response, args->channel_id);
303         if (control == NULL) {
304                 /* Response filled in by find_control */
305                 return;
306         }
307
308         stasis_app_control_moh_start(control, args->moh_class);
309         ast_ari_response_no_content(response);
310 }
311
312 void ast_ari_channels_stop_moh(struct ast_variable *headers,
313         struct ast_ari_channels_stop_moh_args *args,
314         struct ast_ari_response *response)
315 {
316         RAII_VAR(struct stasis_app_control *, control, NULL, ao2_cleanup);
317
318         control = find_control(response, args->channel_id);
319         if (control == NULL) {
320                 /* Response filled in by find_control */
321                 return;
322         }
323
324         stasis_app_control_moh_stop(control);
325         ast_ari_response_no_content(response);
326 }
327
328 void ast_ari_channels_start_silence(struct ast_variable *headers,
329         struct ast_ari_channels_start_silence_args *args,
330         struct ast_ari_response *response)
331 {
332         RAII_VAR(struct stasis_app_control *, control, NULL, ao2_cleanup);
333
334         control = find_control(response, args->channel_id);
335         if (control == NULL) {
336                 /* Response filled in by find_control */
337                 return;
338         }
339
340         stasis_app_control_silence_start(control);
341         ast_ari_response_no_content(response);
342 }
343
344 void ast_ari_channels_stop_silence(struct ast_variable *headers,
345         struct ast_ari_channels_stop_silence_args *args,
346         struct ast_ari_response *response)
347 {
348         RAII_VAR(struct stasis_app_control *, control, NULL, ao2_cleanup);
349
350         control = find_control(response, args->channel_id);
351         if (control == NULL) {
352                 /* Response filled in by find_control */
353                 return;
354         }
355
356         stasis_app_control_silence_stop(control);
357         ast_ari_response_no_content(response);
358 }
359
360 static void ari_channels_handle_play(
361         const char *args_channel_id,
362         const char *args_media,
363         const char *args_lang,
364         int args_offsetms,
365         int args_skipms,
366         const char *args_playback_id,
367         struct ast_ari_response *response)
368 {
369         RAII_VAR(struct stasis_app_control *, control, NULL, ao2_cleanup);
370         RAII_VAR(struct ast_channel_snapshot *, snapshot, NULL, ao2_cleanup);
371         RAII_VAR(struct stasis_app_playback *, playback, NULL, ao2_cleanup);
372         RAII_VAR(char *, playback_url, NULL, ast_free);
373         struct ast_json *json;
374         const char *language;
375
376         ast_assert(response != NULL);
377
378         control = find_control(response, args_channel_id);
379         if (control == NULL) {
380                 /* Response filled in by find_control */
381                 return;
382         }
383
384         snapshot = stasis_app_control_get_snapshot(control);
385         if (!snapshot) {
386                 ast_ari_response_error(
387                         response, 404, "Not Found",
388                         "Channel not found");
389                 return;
390         }
391
392         if (args_skipms < 0) {
393                 ast_ari_response_error(
394                         response, 400, "Bad Request",
395                         "skipms cannot be negative");
396                 return;
397         }
398
399         if (args_offsetms < 0) {
400                 ast_ari_response_error(
401                         response, 400, "Bad Request",
402                         "offsetms cannot be negative");
403                 return;
404         }
405
406         language = S_OR(args_lang, snapshot->language);
407
408         playback = stasis_app_control_play_uri(control, args_media, language,
409                 args_channel_id, STASIS_PLAYBACK_TARGET_CHANNEL, args_skipms, args_offsetms, args_playback_id);
410         if (!playback) {
411                 ast_ari_response_error(
412                         response, 500, "Internal Server Error",
413                         "Failed to queue media for playback");
414                 return;
415         }
416
417         if (ast_asprintf(&playback_url, "/playback/%s",
418                         stasis_app_playback_get_id(playback)) == -1) {
419                 playback_url = NULL;
420                 ast_ari_response_error(
421                         response, 500, "Internal Server Error",
422                         "Out of memory");
423                 return;
424         }
425
426         json = stasis_app_playback_to_json(playback);
427         if (!json) {
428                 ast_ari_response_error(
429                         response, 500, "Internal Server Error",
430                         "Out of memory");
431                 return;
432         }
433
434         ast_ari_response_created(response, playback_url, json);
435 }
436
437 void ast_ari_channels_play(struct ast_variable *headers,
438         struct ast_ari_channels_play_args *args,
439         struct ast_ari_response *response)
440 {
441         ari_channels_handle_play(
442                 args->channel_id,
443                 args->media,
444                 args->lang,
445                 args->offsetms,
446                 args->skipms,
447                 args->playback_id,
448                 response);
449 }
450
451 void ast_ari_channels_play_with_id(struct ast_variable *headers,
452         struct ast_ari_channels_play_with_id_args *args,
453         struct ast_ari_response *response)
454 {
455         ari_channels_handle_play(
456                 args->channel_id,
457                 args->media,
458                 args->lang,
459                 args->offsetms,
460                 args->skipms,
461                 args->playback_id,
462                 response);
463 }
464
465 void ast_ari_channels_record(struct ast_variable *headers,
466         struct ast_ari_channels_record_args *args,
467         struct ast_ari_response *response)
468 {
469         RAII_VAR(struct stasis_app_control *, control, NULL, ao2_cleanup);
470         RAII_VAR(struct stasis_app_recording *, recording, NULL, ao2_cleanup);
471         RAII_VAR(char *, recording_url, NULL, ast_free);
472         struct ast_json *json;
473         RAII_VAR(struct stasis_app_recording_options *, options, NULL,
474                 ao2_cleanup);
475         RAII_VAR(char *, uri_encoded_name, NULL, ast_free);
476         size_t uri_name_maxlen;
477
478         ast_assert(response != NULL);
479
480         if (args->max_duration_seconds < 0) {
481                 ast_ari_response_error(
482                         response, 400, "Bad Request",
483                         "max_duration_seconds cannot be negative");
484                 return;
485         }
486
487         if (args->max_silence_seconds < 0) {
488                 ast_ari_response_error(
489                         response, 400, "Bad Request",
490                         "max_silence_seconds cannot be negative");
491                 return;
492         }
493
494         control = find_control(response, args->channel_id);
495         if (control == NULL) {
496                 /* Response filled in by find_control */
497                 return;
498         }
499
500         options = stasis_app_recording_options_create(args->name, args->format);
501         if (options == NULL) {
502                 ast_ari_response_error(
503                         response, 500, "Internal Server Error",
504                         "Out of memory");
505         }
506         ast_string_field_build(options, target, "channel:%s", args->channel_id);
507         options->max_silence_seconds = args->max_silence_seconds;
508         options->max_duration_seconds = args->max_duration_seconds;
509         options->terminate_on =
510                 stasis_app_recording_termination_parse(args->terminate_on);
511         options->if_exists =
512                 stasis_app_recording_if_exists_parse(args->if_exists);
513         options->beep = args->beep;
514
515         if (options->terminate_on == STASIS_APP_RECORDING_TERMINATE_INVALID) {
516                 ast_ari_response_error(
517                         response, 400, "Bad Request",
518                         "terminateOn invalid");
519                 return;
520         }
521
522         if (options->if_exists == -1) {
523                 ast_ari_response_error(
524                         response, 400, "Bad Request",
525                         "ifExists invalid");
526                 return;
527         }
528
529         if (!ast_get_format_for_file_ext(options->format)) {
530                 ast_ari_response_error(
531                         response, 422, "Unprocessable Entity",
532                         "specified format is unknown on this system");
533                 return;
534         }
535
536         recording = stasis_app_control_record(control, options);
537         if (recording == NULL) {
538                 switch(errno) {
539                 case EINVAL:
540                         /* While the arguments are invalid, we should have
541                          * caught them prior to calling record.
542                          */
543                         ast_ari_response_error(
544                                 response, 500, "Internal Server Error",
545                                 "Error parsing request");
546                         break;
547                 case EEXIST:
548                         ast_ari_response_error(response, 409, "Conflict",
549                                 "Recording '%s' already exists and can not be overwritten",
550                                 args->name);
551                         break;
552                 case ENOMEM:
553                         ast_ari_response_error(
554                                 response, 500, "Internal Server Error",
555                                 "Out of memory");
556                         break;
557                 case EPERM:
558                         ast_ari_response_error(
559                                 response, 400, "Bad Request",
560                                 "Recording name invalid");
561                         break;
562                 default:
563                         ast_log(LOG_WARNING,
564                                 "Unrecognized recording error: %s\n",
565                                 strerror(errno));
566                         ast_ari_response_error(
567                                 response, 500, "Internal Server Error",
568                                 "Internal Server Error");
569                         break;
570                 }
571                 return;
572         }
573
574         uri_name_maxlen = strlen(args->name) * 3;
575         uri_encoded_name = ast_malloc(uri_name_maxlen);
576         if (!uri_encoded_name) {
577                 ast_ari_response_error(
578                         response, 500, "Internal Server Error",
579                         "Out of memory");
580                 return;
581         }
582         ast_uri_encode(args->name, uri_encoded_name, uri_name_maxlen,
583                 ast_uri_http);
584
585         if (ast_asprintf(&recording_url, "/recordings/live/%s",
586                         uri_encoded_name) == -1) {
587                 recording_url = NULL;
588                 ast_ari_response_error(
589                         response, 500, "Internal Server Error",
590                         "Out of memory");
591                 return;
592         }
593
594         json = stasis_app_recording_to_json(recording);
595         if (!json) {
596                 ast_ari_response_error(
597                         response, 500, "Internal Server Error",
598                         "Out of memory");
599                 return;
600         }
601
602         ast_ari_response_created(response, recording_url, json);
603 }
604
605 void ast_ari_channels_get(struct ast_variable *headers,
606         struct ast_ari_channels_get_args *args,
607         struct ast_ari_response *response)
608 {
609         RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
610         struct stasis_cache *cache;
611         struct ast_channel_snapshot *snapshot;
612
613         cache = ast_channel_cache();
614         if (!cache) {
615                 ast_ari_response_error(
616                         response, 500, "Internal Server Error",
617                         "Message bus not initialized");
618                 return;
619         }
620
621         msg = stasis_cache_get(cache, ast_channel_snapshot_type(),
622                                    args->channel_id);
623         if (!msg) {
624                 ast_ari_response_error(
625                         response, 404, "Not Found",
626                         "Channel not found");
627                 return;
628         }
629
630         snapshot = stasis_message_data(msg);
631         ast_assert(snapshot != NULL);
632
633         ast_ari_response_ok(response,
634                                 ast_channel_snapshot_to_json(snapshot, NULL));
635 }
636
637 void ast_ari_channels_hangup(struct ast_variable *headers,
638         struct ast_ari_channels_hangup_args *args,
639         struct ast_ari_response *response)
640 {
641         RAII_VAR(struct ast_channel *, chan, NULL, ao2_cleanup);
642         int cause;
643
644         chan = ast_channel_get_by_name(args->channel_id);
645         if (chan == NULL) {
646                 ast_ari_response_error(
647                         response, 404, "Not Found",
648                         "Channel not found");
649                 return;
650         }
651
652         if (ast_strlen_zero(args->reason) || !strcmp(args->reason, "normal")) {
653                 cause = AST_CAUSE_NORMAL;
654         } else if (!strcmp(args->reason, "busy")) {
655                 cause = AST_CAUSE_BUSY;
656         } else if (!strcmp(args->reason, "congestion")) {
657                 cause = AST_CAUSE_CONGESTION;
658         } else {
659                 ast_ari_response_error(
660                         response, 400, "Invalid Reason",
661                         "Invalid reason for hangup provided");
662                 return;
663         }
664
665         ast_channel_hangupcause_set(chan, cause);
666         ast_softhangup(chan, AST_SOFTHANGUP_EXPLICIT);
667
668         ast_ari_response_no_content(response);
669 }
670
671 void ast_ari_channels_list(struct ast_variable *headers,
672         struct ast_ari_channels_list_args *args,
673         struct ast_ari_response *response)
674 {
675         RAII_VAR(struct stasis_cache *, cache, NULL, ao2_cleanup);
676         RAII_VAR(struct ao2_container *, snapshots, NULL, ao2_cleanup);
677         RAII_VAR(struct ast_json *, json, NULL, ast_json_unref);
678         struct ao2_iterator i;
679         void *obj;
680         struct stasis_message_sanitizer *sanitize = stasis_app_get_sanitizer();
681
682         cache = ast_channel_cache();
683         if (!cache) {
684                 ast_ari_response_error(
685                         response, 500, "Internal Server Error",
686                         "Message bus not initialized");
687                 return;
688         }
689         ao2_ref(cache, +1);
690
691         snapshots = stasis_cache_dump(cache, ast_channel_snapshot_type());
692         if (!snapshots) {
693                 ast_ari_response_alloc_failed(response);
694                 return;
695         }
696
697         json = ast_json_array_create();
698         if (!json) {
699                 ast_ari_response_alloc_failed(response);
700                 return;
701         }
702
703         i = ao2_iterator_init(snapshots, 0);
704         while ((obj = ao2_iterator_next(&i))) {
705                 RAII_VAR(struct stasis_message *, msg, obj, ao2_cleanup);
706                 struct ast_channel_snapshot *snapshot = stasis_message_data(msg);
707                 int r;
708
709                 if (sanitize && sanitize->channel_snapshot
710                         && sanitize->channel_snapshot(snapshot)) {
711                         continue;
712                 }
713
714                 r = ast_json_array_append(
715                         json, ast_channel_snapshot_to_json(snapshot, NULL));
716                 if (r != 0) {
717                         ast_ari_response_alloc_failed(response);
718                         ao2_iterator_destroy(&i);
719                         return;
720                 }
721         }
722         ao2_iterator_destroy(&i);
723
724         ast_ari_response_ok(response, ast_json_ref(json));
725 }
726
727 /*! \brief Structure used for origination */
728 struct ari_origination {
729         /*! \brief Dialplan context */
730         char context[AST_MAX_CONTEXT];
731         /*! \brief Dialplan extension */
732         char exten[AST_MAX_EXTENSION];
733         /*! \brief Dialplan priority */
734         int priority;
735         /*! \brief Application data to pass to Stasis application */
736         char appdata[0];
737 };
738
739 /*! \brief Thread which dials and executes upon answer */
740 static void *ari_originate_dial(void *data)
741 {
742         struct ast_dial *dial = data;
743         struct ari_origination *origination = ast_dial_get_user_data(dial);
744         enum ast_dial_result res;
745
746         res = ast_dial_run(dial, NULL, 0);
747         if (res != AST_DIAL_RESULT_ANSWERED) {
748                 goto end;
749         }
750
751         if (!ast_strlen_zero(origination->appdata)) {
752                 struct ast_app *app = pbx_findapp("Stasis");
753
754                 if (app) {
755                         ast_verb(4, "Launching Stasis(%s) on %s\n", origination->appdata,
756                                 ast_channel_name(ast_dial_answered(dial)));
757                         pbx_exec(ast_dial_answered(dial), app, origination->appdata);
758                 } else {
759                         ast_log(LOG_WARNING, "No such application 'Stasis'\n");
760                 }
761         } else {
762                 struct ast_channel *answered = ast_dial_answered(dial);
763
764                 if (!ast_strlen_zero(origination->context)) {
765                         ast_channel_context_set(answered, origination->context);
766                 }
767
768                 if (!ast_strlen_zero(origination->exten)) {
769                         ast_channel_exten_set(answered, origination->exten);
770                 }
771
772                 if (origination->priority > 0) {
773                         ast_channel_priority_set(answered, origination->priority);
774                 }
775
776                 if (ast_pbx_run(answered)) {
777                         ast_log(LOG_ERROR, "Failed to start PBX on %s\n", ast_channel_name(answered));
778                 } else {
779                         /* PBX will have taken care of hanging up, so we steal the answered channel so dial doesn't do it */
780                         ast_dial_answered_steal(dial);
781                 }
782         }
783
784 end:
785         ast_dial_destroy(dial);
786         ast_free(origination);
787         return NULL;
788 }
789
790 static void ari_channels_handle_originate_with_id(const char *args_endpoint,
791         const char *args_extension,
792         const char *args_context,
793         long args_priority,
794         const char *args_app,
795         const char *args_app_args,
796         const char *args_caller_id,
797         int args_timeout,
798         struct ast_variable *variables,
799         const char *args_channel_id,
800         const char *args_other_channel_id,
801         const char *args_originator,
802         struct ast_ari_response *response)
803 {
804         char *dialtech;
805         char dialdevice[AST_CHANNEL_NAME];
806         struct ast_dial *dial;
807         char *caller_id = NULL;
808         char *cid_num = NULL;
809         char *cid_name = NULL;
810         RAII_VAR(struct ast_format_cap *, cap,
811                 ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT), ao2_cleanup);
812         char *stuff;
813         struct ast_channel *other = NULL;
814         struct ast_channel *chan;
815         RAII_VAR(struct ast_channel_snapshot *, snapshot, NULL, ao2_cleanup);
816         struct ast_assigned_ids assignedids = {
817                 .uniqueid = args_channel_id,
818                 .uniqueid2 = args_other_channel_id,
819         };
820         struct ari_origination *origination;
821         pthread_t thread;
822
823         if (!cap) {
824                 ast_ari_response_alloc_failed(response);
825                 return;
826         }
827         ast_format_cap_append(cap, ast_format_slin, 0);
828
829         if ((assignedids.uniqueid && AST_MAX_PUBLIC_UNIQUEID < strlen(assignedids.uniqueid))
830                 || (assignedids.uniqueid2 && AST_MAX_PUBLIC_UNIQUEID < strlen(assignedids.uniqueid2))) {
831                 ast_ari_response_error(response, 400, "Bad Request",
832                         "Uniqueid length exceeds maximum of %d", AST_MAX_PUBLIC_UNIQUEID);
833                 return;
834         }
835
836         if (ast_strlen_zero(args_endpoint)) {
837                 ast_ari_response_error(response, 400, "Bad Request",
838                         "Endpoint must be specified");
839                 return;
840         }
841
842         dialtech = ast_strdupa(args_endpoint);
843         if ((stuff = strchr(dialtech, '/'))) {
844                 *stuff++ = '\0';
845                 ast_copy_string(dialdevice, stuff, sizeof(dialdevice));
846         }
847
848         if (ast_strlen_zero(dialtech) || ast_strlen_zero(dialdevice)) {
849                 ast_ari_response_error(response, 400, "Bad Request",
850                         "Invalid endpoint specified");
851                 return;
852         }
853
854         if (!ast_strlen_zero(args_app)) {
855                 RAII_VAR(struct ast_str *, appdata, ast_str_create(64), ast_free);
856
857                 if (!appdata) {
858                         ast_ari_response_alloc_failed(response);
859                         return;
860                 }
861
862                 ast_str_set(&appdata, 0, "%s", args_app);
863                 if (!ast_strlen_zero(args_app_args)) {
864                         ast_str_append(&appdata, 0, ",%s", args_app_args);
865                 }
866
867                 origination = ast_calloc(1, sizeof(*origination) + ast_str_size(appdata) + 1);
868                 if (!origination) {
869                         ast_ari_response_alloc_failed(response);
870                         return;
871                 }
872
873                 strcpy(origination->appdata, ast_str_buffer(appdata));
874         } else if (!ast_strlen_zero(args_extension)) {
875                 origination = ast_calloc(1, sizeof(*origination) + 1);
876                 if (!origination) {
877                         ast_ari_response_alloc_failed(response);
878                         return;
879                 }
880
881                 ast_copy_string(origination->context, S_OR(args_context, "default"), sizeof(origination->context));
882                 ast_copy_string(origination->exten, args_extension, sizeof(origination->exten));
883                 origination->priority = args_priority ? args_priority : 1;
884                 origination->appdata[0] = '\0';
885         } else {
886                 ast_ari_response_error(response, 400, "Bad Request",
887                         "Application or extension must be specified");
888                 return;
889         }
890
891         dial = ast_dial_create();
892         if (!dial) {
893                 ast_ari_response_alloc_failed(response);
894                 ast_free(origination);
895                 return;
896         }
897         ast_dial_set_user_data(dial, origination);
898
899         if (ast_dial_append(dial, dialtech, dialdevice, &assignedids)) {
900                 ast_ari_response_alloc_failed(response);
901                 ast_dial_destroy(dial);
902                 ast_free(origination);
903                 return;
904         }
905
906         if (args_timeout > 0) {
907                 ast_dial_set_global_timeout(dial, args_timeout * 1000);
908         } else if (args_timeout == -1) {
909                 ast_dial_set_global_timeout(dial, -1);
910         } else {
911                 ast_dial_set_global_timeout(dial, 30000);
912         }
913
914         if (!ast_strlen_zero(args_caller_id)) {
915                 caller_id = ast_strdupa(args_caller_id);
916                 ast_callerid_parse(caller_id, &cid_name, &cid_num);
917
918                 if (ast_is_shrinkable_phonenumber(cid_num)) {
919                         ast_shrink_phone_number(cid_num);
920                 }
921         }
922
923         if (!ast_strlen_zero(args_originator)) {
924                 other = ast_channel_get_by_name(args_originator);
925                 if (!other) {
926                         ast_ari_response_error(
927                                 response, 400, "Bad Request",
928                                 "Provided originator channel was not found");
929                         ast_dial_destroy(dial);
930                         ast_free(origination);
931                         return;
932                 }
933         }
934
935         if (ast_dial_prerun(dial, other, cap)) {
936                 ast_ari_response_alloc_failed(response);
937                 ast_dial_destroy(dial);
938                 ast_free(origination);
939                 ast_channel_cleanup(other);
940                 return;
941         }
942
943         ast_channel_cleanup(other);
944
945         chan = ast_dial_get_channel(dial, 0);
946         if (!chan) {
947                 ast_ari_response_alloc_failed(response);
948                 ast_dial_destroy(dial);
949                 ast_free(origination);
950                 return;
951         }
952
953         if (!ast_strlen_zero(cid_num) || !ast_strlen_zero(cid_name)) {
954                 struct ast_party_connected_line connected;
955
956                 /*
957                  * It seems strange to set the CallerID on an outgoing call leg
958                  * to whom we are calling, but this function's callers are doing
959                  * various Originate methods.  This call leg goes to the local
960                  * user.  Once the called party answers, the dialplan needs to
961                  * be able to access the CallerID from the CALLERID function as
962                  * if the called party had placed this call.
963                  */
964                 ast_set_callerid(chan, cid_num, cid_name, cid_num);
965
966                 ast_party_connected_line_set_init(&connected, ast_channel_connected(chan));
967                 if (!ast_strlen_zero(cid_num)) {
968                         connected.id.number.valid = 1;
969                         connected.id.number.str = (char *) cid_num;
970                         connected.id.number.presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
971                 }
972                 if (!ast_strlen_zero(cid_name)) {
973                         connected.id.name.valid = 1;
974                         connected.id.name.str = (char *) cid_name;
975                         connected.id.name.presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
976                 }
977                 ast_channel_set_connected_line(chan, &connected, NULL);
978         }
979
980         ast_channel_lock(chan);
981         if (variables) {
982                 ast_set_variables(chan, variables);
983         }
984         ast_set_flag(ast_channel_flags(chan), AST_FLAG_ORIGINATED);
985
986         if (!ast_strlen_zero(args_app)) {
987                 struct ast_channel *local_peer;
988
989                 stasis_app_subscribe_channel(args_app, chan);
990
991                 /* Subscribe to the Local channel peer also. */
992                 local_peer = ast_local_get_peer(chan);
993                 if (local_peer) {
994                         stasis_app_subscribe_channel(args_app, local_peer);
995                         ast_channel_unref(local_peer);
996                 }
997         }
998
999         snapshot = ast_channel_snapshot_get_latest(ast_channel_uniqueid(chan));
1000         ast_channel_unlock(chan);
1001
1002         /* Before starting the async dial bump the ref in case the dial quickly goes away and takes
1003          * the reference with it
1004          */
1005         ast_channel_ref(chan);
1006
1007         if (ast_pthread_create_detached(&thread, NULL, ari_originate_dial, dial)) {
1008                 ast_ari_response_alloc_failed(response);
1009                 ast_dial_destroy(dial);
1010                 ast_free(origination);
1011         } else {
1012                 ast_ari_response_ok(response, ast_channel_snapshot_to_json(snapshot, NULL));
1013         }
1014
1015         ast_channel_unref(chan);
1016         return;
1017 }
1018
1019 void ast_ari_channels_originate_with_id(struct ast_variable *headers,
1020         struct ast_ari_channels_originate_with_id_args *args,
1021         struct ast_ari_response *response)
1022 {
1023         RAII_VAR(struct ast_variable *, variables, NULL, ast_variables_destroy);
1024
1025         /* Parse any query parameters out of the body parameter */
1026         if (args->variables) {
1027                 struct ast_json *json_variables;
1028
1029                 ast_ari_channels_originate_with_id_parse_body(args->variables, args);
1030                 json_variables = ast_json_object_get(args->variables, "variables");
1031                 if (json_variables) {
1032                         if (ast_json_to_ast_variables(json_variables, &variables)) {
1033                                 ast_log(AST_LOG_ERROR, "Unable to convert 'variables' in JSON body to channel variables\n");
1034                                 ast_ari_response_alloc_failed(response);
1035                                 return;
1036                         }
1037                 }
1038         }
1039
1040         ari_channels_handle_originate_with_id(
1041                 args->endpoint,
1042                 args->extension,
1043                 args->context,
1044                 args->priority,
1045                 args->app,
1046                 args->app_args,
1047                 args->caller_id,
1048                 args->timeout,
1049                 variables,
1050                 args->channel_id,
1051                 args->other_channel_id,
1052                 args->originator,
1053                 response);
1054 }
1055
1056 void ast_ari_channels_originate(struct ast_variable *headers,
1057         struct ast_ari_channels_originate_args *args,
1058         struct ast_ari_response *response)
1059 {
1060         RAII_VAR(struct ast_variable *, variables, NULL, ast_variables_destroy);
1061
1062         /* Parse any query parameters out of the body parameter */
1063         if (args->variables) {
1064                 struct ast_json *json_variables;
1065
1066                 ast_ari_channels_originate_parse_body(args->variables, args);
1067                 json_variables = ast_json_object_get(args->variables, "variables");
1068                 if (json_variables) {
1069                         if (ast_json_to_ast_variables(json_variables, &variables)) {
1070                                 ast_log(AST_LOG_ERROR, "Unable to convert 'variables' in JSON body to channel variables\n");
1071                                 ast_ari_response_alloc_failed(response);
1072                                 return;
1073                         }
1074                 }
1075         }
1076
1077         ari_channels_handle_originate_with_id(
1078                 args->endpoint,
1079                 args->extension,
1080                 args->context,
1081                 args->priority,
1082                 args->app,
1083                 args->app_args,
1084                 args->caller_id,
1085                 args->timeout,
1086                 variables,
1087                 args->channel_id,
1088                 args->other_channel_id,
1089                 args->originator,
1090                 response);
1091 }
1092
1093 void ast_ari_channels_get_channel_var(struct ast_variable *headers,
1094         struct ast_ari_channels_get_channel_var_args *args,
1095         struct ast_ari_response *response)
1096 {
1097         RAII_VAR(struct ast_json *, json, NULL, ast_json_unref);
1098         RAII_VAR(struct stasis_app_control *, control, NULL, ao2_cleanup);
1099         RAII_VAR(struct ast_str *, value, ast_str_create(32), ast_free);
1100         RAII_VAR(struct ast_channel *, channel, NULL, ast_channel_cleanup);
1101
1102         ast_assert(response != NULL);
1103
1104         if (ast_strlen_zero(args->variable)) {
1105                 ast_ari_response_error(
1106                         response, 400, "Bad Request",
1107                         "Variable name is required");
1108                 return;
1109         }
1110
1111         if (ast_strlen_zero(args->channel_id)) {
1112                 ast_ari_response_error(
1113                         response, 400, "Bad Request",
1114                         "Channel ID is required");
1115                 return;
1116         }
1117
1118         channel = ast_channel_get_by_name(args->channel_id);
1119         if (!channel) {
1120                 ast_ari_response_error(
1121                         response, 404, "Channel Not Found",
1122                         "Provided channel was not found");
1123                 return;
1124         }
1125
1126         /* You may be tempted to lock the channel you're about to read from. You
1127          * would be wrong. Some dialplan functions put the channel into
1128          * autoservice, which deadlocks if the channel is already locked.
1129          * ast_str_retrieve_variable() does its own locking, and the dialplan
1130          * functions need to as well. We should be fine without the lock.
1131          */
1132
1133         if (args->variable[strlen(args->variable) - 1] == ')') {
1134                 if (ast_func_read2(channel, args->variable, &value, 0)) {
1135                         ast_ari_response_error(
1136                                 response, 500, "Error With Function",
1137                                 "Unable to read provided function");
1138                         return;
1139                 }
1140         } else {
1141                 if (!ast_str_retrieve_variable(&value, 0, channel, NULL, args->variable)) {
1142                         ast_ari_response_alloc_failed(response);
1143                         return;
1144                 }
1145         }
1146
1147         if (!(json = ast_json_pack("{s: s}", "value", S_OR(ast_str_buffer(value), "")))) {
1148                 ast_ari_response_alloc_failed(response);
1149                 return;
1150         }
1151
1152         ast_ari_response_ok(response, ast_json_ref(json));
1153 }
1154
1155 void ast_ari_channels_set_channel_var(struct ast_variable *headers,
1156         struct ast_ari_channels_set_channel_var_args *args,
1157         struct ast_ari_response *response)
1158 {
1159         RAII_VAR(struct stasis_app_control *, control, NULL, ao2_cleanup);
1160
1161         ast_assert(response != NULL);
1162
1163         if (ast_strlen_zero(args->variable)) {
1164                 ast_ari_response_error(
1165                         response, 400, "Bad Request",
1166                         "Variable name is required");
1167                 return;
1168         }
1169
1170         control = find_control(response, args->channel_id);
1171         if (control == NULL) {
1172                 /* response filled in by find_control */
1173                 return;
1174         }
1175
1176         if (stasis_app_control_set_channel_var(control, args->variable, args->value)) {
1177                 ast_ari_response_error(
1178                         response, 400, "Bad Request",
1179                         "Failed to execute function");
1180                 return;
1181         }
1182
1183         ast_ari_response_no_content(response);
1184 }
1185
1186 static void ari_channels_handle_snoop_channel(
1187         const char *args_channel_id,
1188         const char *args_spy,
1189         const char *args_whisper,
1190         const char *args_app,
1191         const char *args_app_args,
1192         const char *args_snoop_id,
1193         struct ast_ari_response *response)
1194 {
1195         enum stasis_app_snoop_direction spy, whisper;
1196         RAII_VAR(struct ast_channel *, chan, NULL, ast_channel_cleanup);
1197         RAII_VAR(struct ast_channel *, snoop, NULL, ast_channel_cleanup);
1198         RAII_VAR(struct ast_channel_snapshot *, snapshot, NULL, ao2_cleanup);
1199
1200         ast_assert(response != NULL);
1201
1202         if (ast_strlen_zero(args_spy) || !strcmp(args_spy, "none")) {
1203                 spy = STASIS_SNOOP_DIRECTION_NONE;
1204         } else if (!strcmp(args_spy, "both")) {
1205                 spy = STASIS_SNOOP_DIRECTION_BOTH;
1206         } else if (!strcmp(args_spy, "out")) {
1207                 spy = STASIS_SNOOP_DIRECTION_OUT;
1208         } else if (!strcmp(args_spy, "in")) {
1209                 spy = STASIS_SNOOP_DIRECTION_IN;
1210         } else {
1211                 ast_ari_response_error(
1212                         response, 400, "Bad Request",
1213                         "Invalid direction specified for spy");
1214                 return;
1215         }
1216
1217         if (ast_strlen_zero(args_whisper) || !strcmp(args_whisper, "none")) {
1218                 whisper = STASIS_SNOOP_DIRECTION_NONE;
1219         } else if (!strcmp(args_whisper, "both")) {
1220                 whisper = STASIS_SNOOP_DIRECTION_BOTH;
1221         } else if (!strcmp(args_whisper, "out")) {
1222                 whisper = STASIS_SNOOP_DIRECTION_OUT;
1223         } else if (!strcmp(args_whisper, "in")) {
1224                 whisper = STASIS_SNOOP_DIRECTION_IN;
1225         } else {
1226                 ast_ari_response_error(
1227                         response, 400, "Bad Request",
1228                         "Invalid direction specified for whisper");
1229                 return;
1230         }
1231
1232         if (spy == STASIS_SNOOP_DIRECTION_NONE && whisper == STASIS_SNOOP_DIRECTION_NONE) {
1233                 ast_ari_response_error(
1234                         response, 400, "Bad Request",
1235                         "Direction must be specified for at least spy or whisper");
1236                 return;
1237         } else if (ast_strlen_zero(args_app)) {
1238                 ast_ari_response_error(
1239                         response, 400, "Bad Request",
1240                         "Application name is required");
1241                 return;
1242         }
1243
1244         chan = ast_channel_get_by_name(args_channel_id);
1245         if (chan == NULL) {
1246                 ast_ari_response_error(
1247                         response, 404, "Channel Not Found",
1248                         "Provided channel was not found");
1249                 return;
1250         }
1251
1252         snoop = stasis_app_control_snoop(chan, spy, whisper, args_app, args_app_args,
1253                 args_snoop_id);
1254         if (snoop == NULL) {
1255                 ast_ari_response_error(
1256                         response, 500, "Internal error",
1257                         "Snoop channel could not be created");
1258                 return;
1259         }
1260
1261         snapshot = ast_channel_snapshot_get_latest(ast_channel_uniqueid(snoop));
1262         ast_ari_response_ok(response, ast_channel_snapshot_to_json(snapshot, NULL));
1263 }
1264
1265 void ast_ari_channels_snoop_channel(struct ast_variable *headers,
1266         struct ast_ari_channels_snoop_channel_args *args,
1267         struct ast_ari_response *response)
1268 {
1269         ari_channels_handle_snoop_channel(
1270                 args->channel_id,
1271                 args->spy,
1272                 args->whisper,
1273                 args->app,
1274                 args->app_args,
1275                 args->snoop_id,
1276                 response);
1277 }
1278
1279 void ast_ari_channels_snoop_channel_with_id(struct ast_variable *headers,
1280         struct ast_ari_channels_snoop_channel_with_id_args *args,
1281         struct ast_ari_response *response)
1282 {
1283         ari_channels_handle_snoop_channel(
1284                 args->channel_id,
1285                 args->spy,
1286                 args->whisper,
1287                 args->app,
1288                 args->app_args,
1289                 args->snoop_id,
1290                 response);
1291 }