08f97f1d34b68e3f5810bc555f2a3c5c144c092c
[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         <support_level>core</support_level>
28  ***/
29
30 #include "asterisk.h"
31
32 #include "asterisk/file.h"
33 #include "asterisk/pbx.h"
34 #include "asterisk/bridge.h"
35 #include "asterisk/callerid.h"
36 #include "asterisk/stasis_app.h"
37 #include "asterisk/stasis_app_playback.h"
38 #include "asterisk/stasis_app_recording.h"
39 #include "asterisk/stasis_app_snoop.h"
40 #include "asterisk/stasis_channels.h"
41 #include "asterisk/causes.h"
42 #include "asterisk/format_cache.h"
43 #include "asterisk/core_local.h"
44 #include "asterisk/dial.h"
45 #include "asterisk/max_forwards.h"
46 #include "resource_channels.h"
47
48 #include <limits.h>
49
50 /*!
51  * \brief Ensure channel is in a state that allows operation to be performed.
52  *
53  * Since Asterisk 14, it has been possible for down channels, as well as unanswered
54  * outbound channels to enter Stasis. While some operations are fine to perform on
55  * such channels, operations that
56  *
57  * - Attempt to manipulate channel state
58  * - Attempt to play media
59  * - Attempt to control the channel's location in the dialplan
60  *
61  * are invalid. This function can be used to determine if the channel is in an
62  * appropriate state.
63  *
64  * \note When this function returns an error, the HTTP response is taken care of.
65  *
66  * \param control The app control
67  * \param response Response to fill in if there is an error
68  *
69  * \retval 0 Channel is in a valid state. Continue on!
70  * \retval non-zero Channel is in an invalid state. Bail!
71  */
72 static int channel_state_invalid(struct stasis_app_control *control,
73         struct ast_ari_response *response)
74 {
75         struct ast_channel_snapshot *snapshot;
76
77         snapshot = stasis_app_control_get_snapshot(control);
78         if (!snapshot) {
79                 ast_ari_response_error(response, 404, "Not Found", "Channel not found");
80                 return -1;
81         }
82
83         /* These channel states apply only to outbound channels:
84          * - Down: Channel has been created, and nothing else has been done
85          * - Reserved: For a PRI, an underlying B-channel is reserved,
86          *   but the channel is not yet dialed
87          * - Ringing: The channel has been dialed.
88          *
89          * This does not affect inbound channels. Inbound channels, when they
90          * enter the dialplan, are in the "Ring" state. If they have already
91          * been answered, then they are in the "Up" state.
92          */
93         if (snapshot->state == AST_STATE_DOWN
94                 || snapshot->state == AST_STATE_RESERVED
95                 || snapshot->state == AST_STATE_RINGING) {
96                 ast_ari_response_error(response, 412, "Precondition Failed",
97                         "Channel in invalid state");
98                 ao2_ref(snapshot, -1);
99
100                 return -1;
101         }
102
103         ao2_ref(snapshot, -1);
104
105         return 0;
106 }
107
108 /*!
109  * \brief Finds the control object for a channel, filling the response with an
110  * error, if appropriate.
111  * \param[out] response Response to fill with an error if control is not found.
112  * \param channel_id ID of the channel to lookup.
113  * \return Channel control object.
114  * \return \c NULL if control object does not exist.
115  */
116 static struct stasis_app_control *find_control(
117         struct ast_ari_response *response,
118         const char *channel_id)
119 {
120         RAII_VAR(struct stasis_app_control *, control, NULL, ao2_cleanup);
121
122         ast_assert(response != NULL);
123
124         control = stasis_app_control_find_by_channel_id(channel_id);
125         if (control == NULL) {
126                 /* Distinguish between 404 and 409 errors */
127                 RAII_VAR(struct ast_channel *, chan, NULL, ao2_cleanup);
128                 chan = ast_channel_get_by_name(channel_id);
129                 if (chan == NULL) {
130                         ast_ari_response_error(response, 404, "Not Found",
131                                    "Channel not found");
132                         return NULL;
133                 }
134
135                 ast_ari_response_error(response, 409, "Conflict",
136                            "Channel not in Stasis application");
137                 return NULL;
138         }
139
140         ao2_ref(control, +1);
141         return control;
142 }
143
144 void ast_ari_channels_continue_in_dialplan(
145         struct ast_variable *headers,
146         struct ast_ari_channels_continue_in_dialplan_args *args,
147         struct ast_ari_response *response)
148 {
149         RAII_VAR(struct stasis_app_control *, control, NULL, ao2_cleanup);
150         RAII_VAR(struct ast_channel_snapshot *, snapshot, NULL, ao2_cleanup);
151         int ipri;
152         const char *context;
153         const char *exten;
154
155         ast_assert(response != NULL);
156
157         control = find_control(response, args->channel_id);
158         if (control == NULL) {
159                 return;
160         }
161
162         if (channel_state_invalid(control, response)) {
163                 return;
164         }
165
166         snapshot = stasis_app_control_get_snapshot(control);
167         if (!snapshot) {
168                 ast_ari_response_error(response, 404, "Not Found", "Channel not found");
169                 return;
170         }
171
172         if (ast_strlen_zero(args->context)) {
173                 context = snapshot->dialplan->context;
174                 exten = S_OR(args->extension, snapshot->dialplan->exten);
175         } else {
176                 context = args->context;
177                 exten = S_OR(args->extension, "s");
178         }
179
180         if (!ast_strlen_zero(args->label)) {
181                 /* A label was provided in the request, use that */
182
183                 if (sscanf(args->label, "%30d", &ipri) != 1) {
184                         ipri = ast_findlabel_extension(NULL, context, exten, args->label, NULL);
185                         if (ipri == -1) {
186                                 ast_log(AST_LOG_ERROR, "Requested label: %s can not be found in context: %s\n", args->label, context);
187                                 ast_ari_response_error(response, 404, "Not Found", "Requested label can not be found");
188                                 return;
189                         }
190                 } else {
191                         ast_debug(3, "Numeric value provided for label, jumping to that priority\n");
192                 }
193
194                 if (ipri == 0) {
195                         ast_log(AST_LOG_ERROR, "Invalid priority label '%s' specified for extension %s in context: %s\n",
196                                         args->label, exten, context);
197                         ast_ari_response_error(response, 400, "Bad Request", "Requested priority is illegal");
198                         return;
199                 }
200
201         } else if (args->priority) {
202                 /* No label provided, use provided priority */
203                 ipri = args->priority;
204         } else if (ast_strlen_zero(args->context) && ast_strlen_zero(args->extension)) {
205                 /* Special case. No exten, context, or priority provided, then move on to the next priority */
206                 ipri = snapshot->dialplan->priority + 1;
207         } else {
208                 ipri = 1;
209         }
210
211
212         if (stasis_app_control_continue(control, context, exten, ipri)) {
213                 ast_ari_response_alloc_failed(response);
214                 return;
215         }
216
217         ast_ari_response_no_content(response);
218 }
219
220 void ast_ari_channels_redirect(struct ast_variable *headers,
221         struct ast_ari_channels_redirect_args *args,
222         struct ast_ari_response *response)
223 {
224         RAII_VAR(struct stasis_app_control *, control, NULL, ao2_cleanup);
225         RAII_VAR(struct ast_channel_snapshot *, chan_snapshot, NULL, ao2_cleanup);
226         char *tech;
227         char *resource;
228         int tech_len;
229
230         control = find_control(response, args->channel_id);
231         if (!control) {
232                 return;
233         }
234
235         if (channel_state_invalid(control, response)) {
236                 return;
237         }
238
239         if (ast_strlen_zero(args->endpoint)) {
240                 ast_ari_response_error(response, 400, "Not Found",
241                         "Required parameter 'endpoint' not provided.");
242                 return;
243         }
244
245         tech = ast_strdupa(args->endpoint);
246         if (!(resource = strchr(tech, '/')) || !(tech_len = resource - tech)) {
247                 ast_ari_response_error(response, 422, "Unprocessable Entity",
248                         "Endpoint parameter '%s' does not contain tech/resource", args->endpoint);
249                 return;
250         }
251
252         *resource++ = '\0';
253         if (ast_strlen_zero(resource)) {
254                 ast_ari_response_error(response, 422, "Unprocessable Entity",
255                         "No resource provided in endpoint parameter '%s'", args->endpoint);
256                 return;
257         }
258
259         chan_snapshot = ast_channel_snapshot_get_latest(args->channel_id);
260         if (!chan_snapshot) {
261                 ast_ari_response_error(response, 500, "Internal Server Error",
262                         "Unable to find channel snapshot for '%s'", args->channel_id);
263                 return;
264         }
265
266         if (strncasecmp(chan_snapshot->base->type, tech, tech_len)) {
267                 ast_ari_response_error(response, 422, "Unprocessable Entity",
268                         "Endpoint technology '%s' does not match channel technology '%s'",
269                         tech, chan_snapshot->base->type);
270                 return;
271         }
272
273         if (stasis_app_control_redirect(control, resource)) {
274                 ast_ari_response_error(response, 500, "Internal Server Error",
275                         "Failed to redirect channel");
276                 return;
277         }
278
279         ast_ari_response_no_content(response);
280 }
281
282 void ast_ari_channels_answer(struct ast_variable *headers,
283         struct ast_ari_channels_answer_args *args,
284         struct ast_ari_response *response)
285 {
286         RAII_VAR(struct stasis_app_control *, control, NULL, ao2_cleanup);
287
288         control = find_control(response, args->channel_id);
289         if (control == NULL) {
290                 return;
291         }
292
293         if (channel_state_invalid(control, response)) {
294                 return;
295         }
296
297         if (stasis_app_control_answer(control) != 0) {
298                 ast_ari_response_error(
299                         response, 500, "Internal Server Error",
300                         "Failed to answer channel");
301                 return;
302         }
303
304         ast_ari_response_no_content(response);
305 }
306
307 void ast_ari_channels_ring(struct ast_variable *headers,
308         struct ast_ari_channels_ring_args *args,
309         struct ast_ari_response *response)
310 {
311         RAII_VAR(struct stasis_app_control *, control, NULL, ao2_cleanup);
312
313         control = find_control(response, args->channel_id);
314         if (control == NULL) {
315                 return;
316         }
317
318         if (channel_state_invalid(control, response)) {
319                 return;
320         }
321
322         stasis_app_control_ring(control);
323
324         ast_ari_response_no_content(response);
325 }
326
327 void ast_ari_channels_ring_stop(struct ast_variable *headers,
328         struct ast_ari_channels_ring_stop_args *args,
329         struct ast_ari_response *response)
330 {
331         RAII_VAR(struct stasis_app_control *, control, NULL, ao2_cleanup);
332
333         control = find_control(response, args->channel_id);
334         if (control == NULL) {
335                 return;
336         }
337
338         if (channel_state_invalid(control, response)) {
339                 return;
340         }
341
342         stasis_app_control_ring_stop(control);
343
344         ast_ari_response_no_content(response);
345 }
346
347 void ast_ari_channels_mute(struct ast_variable *headers,
348         struct ast_ari_channels_mute_args *args,
349         struct ast_ari_response *response)
350 {
351         RAII_VAR(struct stasis_app_control *, control, NULL, ao2_cleanup);
352         unsigned int direction = 0;
353         enum ast_frame_type frametype = AST_FRAME_VOICE;
354
355         control = find_control(response, args->channel_id);
356         if (control == NULL) {
357                 return;
358         }
359
360         if (channel_state_invalid(control, response)) {
361                 return;
362         }
363
364         if (ast_strlen_zero(args->direction)) {
365                 ast_ari_response_error(
366                         response, 400, "Bad Request",
367                         "Direction is required");
368                 return;
369         }
370
371         if (!strcmp(args->direction, "in")) {
372                 direction = AST_MUTE_DIRECTION_READ;
373         } else if (!strcmp(args->direction, "out")) {
374                 direction = AST_MUTE_DIRECTION_WRITE;
375         } else if (!strcmp(args->direction, "both")) {
376                 direction = AST_MUTE_DIRECTION_READ | AST_MUTE_DIRECTION_WRITE;
377         } else {
378                 ast_ari_response_error(
379                         response, 400, "Bad Request",
380                         "Invalid direction specified");
381                 return;
382         }
383
384         stasis_app_control_mute(control, direction, frametype);
385
386         ast_ari_response_no_content(response);
387 }
388
389 void ast_ari_channels_unmute(struct ast_variable *headers,
390         struct ast_ari_channels_unmute_args *args,
391         struct ast_ari_response *response)
392 {
393         RAII_VAR(struct stasis_app_control *, control, NULL, ao2_cleanup);
394         unsigned int direction = 0;
395         enum ast_frame_type frametype = AST_FRAME_VOICE;
396
397         control = find_control(response, args->channel_id);
398         if (control == NULL) {
399                 return;
400         }
401
402         if (channel_state_invalid(control, response)) {
403                 return;
404         }
405
406         if (ast_strlen_zero(args->direction)) {
407                 ast_ari_response_error(
408                         response, 400, "Bad Request",
409                         "Direction is required");
410                 return;
411         }
412
413         if (!strcmp(args->direction, "in")) {
414                 direction = AST_MUTE_DIRECTION_READ;
415         } else if (!strcmp(args->direction, "out")) {
416                 direction = AST_MUTE_DIRECTION_WRITE;
417         } else if (!strcmp(args->direction, "both")) {
418                 direction = AST_MUTE_DIRECTION_READ | AST_MUTE_DIRECTION_WRITE;
419         } else {
420                 ast_ari_response_error(
421                         response, 400, "Bad Request",
422                         "Invalid direction specified");
423                 return;
424         }
425
426         stasis_app_control_unmute(control, direction, frametype);
427
428         ast_ari_response_no_content(response);
429 }
430
431 void ast_ari_channels_send_dtmf(struct ast_variable *headers,
432         struct ast_ari_channels_send_dtmf_args *args,
433         struct ast_ari_response *response)
434 {
435         RAII_VAR(struct stasis_app_control *, control, NULL, ao2_cleanup);
436
437         control = find_control(response, args->channel_id);
438         if (control == NULL) {
439                 return;
440         }
441
442         if (channel_state_invalid(control, response)) {
443                 return;
444         }
445
446         if (ast_strlen_zero(args->dtmf)) {
447                 ast_ari_response_error(
448                         response, 400, "Bad Request",
449                         "DTMF is required");
450                 return;
451         }
452
453         stasis_app_control_dtmf(control, args->dtmf, args->before, args->between, args->duration, args->after);
454
455         ast_ari_response_no_content(response);
456 }
457
458 void ast_ari_channels_hold(struct ast_variable *headers,
459         struct ast_ari_channels_hold_args *args,
460         struct ast_ari_response *response)
461 {
462         RAII_VAR(struct stasis_app_control *, control, NULL, ao2_cleanup);
463
464         control = find_control(response, args->channel_id);
465         if (control == NULL) {
466                 /* Response filled in by find_control */
467                 return;
468         }
469
470         if (channel_state_invalid(control, response)) {
471                 return;
472         }
473
474         stasis_app_control_hold(control);
475
476         ast_ari_response_no_content(response);
477 }
478
479 void ast_ari_channels_unhold(struct ast_variable *headers,
480         struct ast_ari_channels_unhold_args *args,
481         struct ast_ari_response *response)
482 {
483         RAII_VAR(struct stasis_app_control *, control, NULL, ao2_cleanup);
484
485         control = find_control(response, args->channel_id);
486         if (control == NULL) {
487                 /* Response filled in by find_control */
488                 return;
489         }
490
491         if (channel_state_invalid(control, response)) {
492                 return;
493         }
494
495         stasis_app_control_unhold(control);
496
497         ast_ari_response_no_content(response);
498 }
499
500 void ast_ari_channels_start_moh(struct ast_variable *headers,
501         struct ast_ari_channels_start_moh_args *args,
502         struct ast_ari_response *response)
503 {
504         RAII_VAR(struct stasis_app_control *, control, NULL, ao2_cleanup);
505
506         control = find_control(response, args->channel_id);
507         if (control == NULL) {
508                 /* Response filled in by find_control */
509                 return;
510         }
511
512         if (channel_state_invalid(control, response)) {
513                 return;
514         }
515
516         stasis_app_control_moh_start(control, args->moh_class);
517         ast_ari_response_no_content(response);
518 }
519
520 void ast_ari_channels_stop_moh(struct ast_variable *headers,
521         struct ast_ari_channels_stop_moh_args *args,
522         struct ast_ari_response *response)
523 {
524         RAII_VAR(struct stasis_app_control *, control, NULL, ao2_cleanup);
525
526         control = find_control(response, args->channel_id);
527         if (control == NULL) {
528                 /* Response filled in by find_control */
529                 return;
530         }
531
532         if (channel_state_invalid(control, response)) {
533                 return;
534         }
535
536         stasis_app_control_moh_stop(control);
537         ast_ari_response_no_content(response);
538 }
539
540 void ast_ari_channels_start_silence(struct ast_variable *headers,
541         struct ast_ari_channels_start_silence_args *args,
542         struct ast_ari_response *response)
543 {
544         RAII_VAR(struct stasis_app_control *, control, NULL, ao2_cleanup);
545
546         control = find_control(response, args->channel_id);
547         if (control == NULL) {
548                 /* Response filled in by find_control */
549                 return;
550         }
551
552         if (channel_state_invalid(control, response)) {
553                 return;
554         }
555
556         stasis_app_control_silence_start(control);
557         ast_ari_response_no_content(response);
558 }
559
560 void ast_ari_channels_stop_silence(struct ast_variable *headers,
561         struct ast_ari_channels_stop_silence_args *args,
562         struct ast_ari_response *response)
563 {
564         RAII_VAR(struct stasis_app_control *, control, NULL, ao2_cleanup);
565
566         control = find_control(response, args->channel_id);
567         if (control == NULL) {
568                 /* Response filled in by find_control */
569                 return;
570         }
571
572         if (channel_state_invalid(control, response)) {
573                 return;
574         }
575
576         stasis_app_control_silence_stop(control);
577         ast_ari_response_no_content(response);
578 }
579
580 static void ari_channels_handle_play(
581         const char *args_channel_id,
582         const char **args_media,
583         size_t args_media_count,
584         const char *args_lang,
585         int args_offsetms,
586         int args_skipms,
587         const char *args_playback_id,
588         struct ast_ari_response *response)
589 {
590         RAII_VAR(struct stasis_app_control *, control, NULL, ao2_cleanup);
591         RAII_VAR(struct ast_channel_snapshot *, snapshot, NULL, ao2_cleanup);
592         RAII_VAR(struct stasis_app_playback *, playback, NULL, ao2_cleanup);
593         RAII_VAR(char *, playback_url, NULL, ast_free);
594         struct ast_json *json;
595         const char *language;
596
597         ast_assert(response != NULL);
598
599         control = find_control(response, args_channel_id);
600         if (control == NULL) {
601                 /* Response filled in by find_control */
602                 return;
603         }
604
605         if (channel_state_invalid(control, response)) {
606                 return;
607         }
608
609         snapshot = stasis_app_control_get_snapshot(control);
610         if (!snapshot) {
611                 ast_ari_response_error(
612                         response, 404, "Not Found",
613                         "Channel not found");
614                 return;
615         }
616
617         if (args_skipms < 0) {
618                 ast_ari_response_error(
619                         response, 400, "Bad Request",
620                         "skipms cannot be negative");
621                 return;
622         }
623
624         if (args_offsetms < 0) {
625                 ast_ari_response_error(
626                         response, 400, "Bad Request",
627                         "offsetms cannot be negative");
628                 return;
629         }
630
631         language = S_OR(args_lang, snapshot->base->language);
632
633         playback = stasis_app_control_play_uri(control, args_media, args_media_count, language,
634                 args_channel_id, STASIS_PLAYBACK_TARGET_CHANNEL, args_skipms, args_offsetms, args_playback_id);
635         if (!playback) {
636                 ast_ari_response_error(
637                         response, 500, "Internal Server Error",
638                         "Failed to queue media for playback");
639                 return;
640         }
641
642         if (ast_asprintf(&playback_url, "/playbacks/%s",
643                         stasis_app_playback_get_id(playback)) == -1) {
644                 playback_url = NULL;
645                 ast_ari_response_error(
646                         response, 500, "Internal Server Error",
647                         "Out of memory");
648                 return;
649         }
650
651         json = stasis_app_playback_to_json(playback);
652         if (!json) {
653                 ast_ari_response_error(
654                         response, 500, "Internal Server Error",
655                         "Out of memory");
656                 return;
657         }
658
659         ast_ari_response_created(response, playback_url, json);
660 }
661
662 void ast_ari_channels_play(struct ast_variable *headers,
663         struct ast_ari_channels_play_args *args,
664         struct ast_ari_response *response)
665 {
666         ari_channels_handle_play(
667                 args->channel_id,
668                 args->media,
669                 args->media_count,
670                 args->lang,
671                 args->offsetms,
672                 args->skipms,
673                 args->playback_id,
674                 response);
675 }
676
677 void ast_ari_channels_play_with_id(struct ast_variable *headers,
678         struct ast_ari_channels_play_with_id_args *args,
679         struct ast_ari_response *response)
680 {
681         ari_channels_handle_play(
682                 args->channel_id,
683                 args->media,
684                 args->media_count,
685                 args->lang,
686                 args->offsetms,
687                 args->skipms,
688                 args->playback_id,
689                 response);
690 }
691
692 void ast_ari_channels_record(struct ast_variable *headers,
693         struct ast_ari_channels_record_args *args,
694         struct ast_ari_response *response)
695 {
696         RAII_VAR(struct stasis_app_control *, control, NULL, ao2_cleanup);
697         RAII_VAR(struct stasis_app_recording *, recording, NULL, ao2_cleanup);
698         RAII_VAR(char *, recording_url, NULL, ast_free);
699         struct ast_json *json;
700         RAII_VAR(struct stasis_app_recording_options *, options, NULL,
701                 ao2_cleanup);
702         RAII_VAR(char *, uri_encoded_name, NULL, ast_free);
703         size_t uri_name_maxlen;
704
705         ast_assert(response != NULL);
706
707         if (args->max_duration_seconds < 0) {
708                 ast_ari_response_error(
709                         response, 400, "Bad Request",
710                         "max_duration_seconds cannot be negative");
711                 return;
712         }
713
714         if (args->max_silence_seconds < 0) {
715                 ast_ari_response_error(
716                         response, 400, "Bad Request",
717                         "max_silence_seconds cannot be negative");
718                 return;
719         }
720
721         control = find_control(response, args->channel_id);
722         if (control == NULL) {
723                 /* Response filled in by find_control */
724                 return;
725         }
726
727         options = stasis_app_recording_options_create(args->name, args->format);
728         if (options == NULL) {
729                 ast_ari_response_error(
730                         response, 500, "Internal Server Error",
731                         "Out of memory");
732         }
733         ast_string_field_build(options, target, "channel:%s", args->channel_id);
734         options->max_silence_seconds = args->max_silence_seconds;
735         options->max_duration_seconds = args->max_duration_seconds;
736         options->terminate_on =
737                 stasis_app_recording_termination_parse(args->terminate_on);
738         options->if_exists =
739                 stasis_app_recording_if_exists_parse(args->if_exists);
740         options->beep = args->beep;
741
742         if (options->terminate_on == STASIS_APP_RECORDING_TERMINATE_INVALID) {
743                 ast_ari_response_error(
744                         response, 400, "Bad Request",
745                         "terminateOn invalid");
746                 return;
747         }
748
749         if (options->if_exists == AST_RECORD_IF_EXISTS_ERROR) {
750                 ast_ari_response_error(
751                         response, 400, "Bad Request",
752                         "ifExists invalid");
753                 return;
754         }
755
756         if (!ast_get_format_for_file_ext(options->format)) {
757                 ast_ari_response_error(
758                         response, 422, "Unprocessable Entity",
759                         "specified format is unknown on this system");
760                 return;
761         }
762
763         recording = stasis_app_control_record(control, options);
764         if (recording == NULL) {
765                 switch(errno) {
766                 case EINVAL:
767                         /* While the arguments are invalid, we should have
768                          * caught them prior to calling record.
769                          */
770                         ast_ari_response_error(
771                                 response, 500, "Internal Server Error",
772                                 "Error parsing request");
773                         break;
774                 case EEXIST:
775                         ast_ari_response_error(response, 409, "Conflict",
776                                 "Recording '%s' already exists and can not be overwritten",
777                                 args->name);
778                         break;
779                 case ENOMEM:
780                         ast_ari_response_error(
781                                 response, 500, "Internal Server Error",
782                                 "Out of memory");
783                         break;
784                 case EPERM:
785                         ast_ari_response_error(
786                                 response, 400, "Bad Request",
787                                 "Recording name invalid");
788                         break;
789                 default:
790                         ast_log(LOG_WARNING,
791                                 "Unrecognized recording error: %s\n",
792                                 strerror(errno));
793                         ast_ari_response_error(
794                                 response, 500, "Internal Server Error",
795                                 "Internal Server Error");
796                         break;
797                 }
798                 return;
799         }
800
801         uri_name_maxlen = strlen(args->name) * 3;
802         uri_encoded_name = ast_malloc(uri_name_maxlen);
803         if (!uri_encoded_name) {
804                 ast_ari_response_error(
805                         response, 500, "Internal Server Error",
806                         "Out of memory");
807                 return;
808         }
809         ast_uri_encode(args->name, uri_encoded_name, uri_name_maxlen,
810                 ast_uri_http);
811
812         if (ast_asprintf(&recording_url, "/recordings/live/%s",
813                         uri_encoded_name) == -1) {
814                 recording_url = NULL;
815                 ast_ari_response_error(
816                         response, 500, "Internal Server Error",
817                         "Out of memory");
818                 return;
819         }
820
821         json = stasis_app_recording_to_json(recording);
822         if (!json) {
823                 ast_ari_response_error(
824                         response, 500, "Internal Server Error",
825                         "Out of memory");
826                 return;
827         }
828
829         ast_ari_response_created(response, recording_url, json);
830 }
831
832 void ast_ari_channels_get(struct ast_variable *headers,
833         struct ast_ari_channels_get_args *args,
834         struct ast_ari_response *response)
835 {
836         struct ast_channel_snapshot *snapshot;
837
838         snapshot = ast_channel_snapshot_get_latest(args->channel_id);
839         if (!snapshot) {
840                 ast_ari_response_error(
841                         response, 404, "Not Found",
842                         "Channel not found");
843                 return;
844         }
845
846         ast_ari_response_ok(response,
847                                 ast_channel_snapshot_to_json(snapshot, NULL));
848         ao2_ref(snapshot, -1);
849 }
850
851 void ast_ari_channels_hangup(struct ast_variable *headers,
852         struct ast_ari_channels_hangup_args *args,
853         struct ast_ari_response *response)
854 {
855         RAII_VAR(struct ast_channel *, chan, NULL, ao2_cleanup);
856         int cause;
857
858         chan = ast_channel_get_by_name(args->channel_id);
859         if (chan == NULL) {
860                 ast_ari_response_error(
861                         response, 404, "Not Found",
862                         "Channel not found");
863                 return;
864         }
865
866         if (ast_strlen_zero(args->reason) || !strcmp(args->reason, "normal")) {
867                 cause = AST_CAUSE_NORMAL;
868         } else if (!strcmp(args->reason, "busy")) {
869                 cause = AST_CAUSE_BUSY;
870         } else if (!strcmp(args->reason, "congestion")) {
871                 cause = AST_CAUSE_CONGESTION;
872         } else if (!strcmp(args->reason, "no_answer")) {
873                 cause = AST_CAUSE_NOANSWER;
874         } else if (!strcmp(args->reason, "timeout")) {
875                 cause = AST_CAUSE_NO_USER_RESPONSE;
876         } else if (!strcmp(args->reason, "rejected")) {
877                 cause = AST_CAUSE_CALL_REJECTED;
878         } else if (!strcmp(args->reason, "unallocated")) {
879                 cause = AST_CAUSE_UNALLOCATED;
880         } else if (!strcmp(args->reason, "normal_unspecified")) {
881                 cause = AST_CAUSE_NORMAL_UNSPECIFIED;
882         } else if (!strcmp(args->reason, "number_incomplete")) {
883                 cause = AST_CAUSE_INVALID_NUMBER_FORMAT;
884         } else if (!strcmp(args->reason, "codec_mismatch")) {
885                 cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
886         } else if (!strcmp(args->reason, "interworking")) {
887                 cause = AST_CAUSE_INTERWORKING;
888         } else if (!strcmp(args->reason, "failure")) {
889                 cause = AST_CAUSE_FAILURE;
890         } else if(!strcmp(args->reason, "answered_elsewhere")) {
891                 cause = AST_CAUSE_ANSWERED_ELSEWHERE;
892         } else {
893                 ast_ari_response_error(
894                         response, 400, "Invalid Reason",
895                         "Invalid reason for hangup provided");
896                 return;
897         }
898
899         ast_channel_hangupcause_set(chan, cause);
900         ast_softhangup(chan, AST_SOFTHANGUP_EXPLICIT);
901
902         ast_ari_response_no_content(response);
903 }
904
905 void ast_ari_channels_list(struct ast_variable *headers,
906         struct ast_ari_channels_list_args *args,
907         struct ast_ari_response *response)
908 {
909         RAII_VAR(struct ao2_container *, snapshots, NULL, ao2_cleanup);
910         RAII_VAR(struct ast_json *, json, NULL, ast_json_unref);
911         struct ao2_iterator i;
912         void *obj;
913         struct stasis_message_sanitizer *sanitize = stasis_app_get_sanitizer();
914
915         snapshots = ast_channel_cache_all();
916
917         json = ast_json_array_create();
918         if (!json) {
919                 ast_ari_response_alloc_failed(response);
920                 return;
921         }
922
923         i = ao2_iterator_init(snapshots, 0);
924         while ((obj = ao2_iterator_next(&i))) {
925                 struct ast_channel_snapshot *snapshot = obj;
926                 int r;
927
928                 if (sanitize && sanitize->channel_snapshot
929                         && sanitize->channel_snapshot(snapshot)) {
930                         ao2_ref(snapshot, -1);
931                         continue;
932                 }
933
934                 r = ast_json_array_append(
935                         json, ast_channel_snapshot_to_json(snapshot, NULL));
936                 if (r != 0) {
937                         ast_ari_response_alloc_failed(response);
938                         ao2_iterator_destroy(&i);
939                         ao2_ref(snapshot, -1);
940                         return;
941                 }
942                 ao2_ref(snapshot, -1);
943         }
944         ao2_iterator_destroy(&i);
945
946         ast_ari_response_ok(response, ast_json_ref(json));
947 }
948
949 /*! \brief Structure used for origination */
950 struct ari_origination {
951         /*! \brief Dialplan context */
952         char context[AST_MAX_CONTEXT];
953         /*! \brief Dialplan extension */
954         char exten[AST_MAX_EXTENSION];
955         /*! \brief Dialplan priority */
956         int priority;
957         /*! \brief Application data to pass to Stasis application */
958         char appdata[0];
959 };
960
961 /*! \brief Thread which dials and executes upon answer */
962 static void *ari_originate_dial(void *data)
963 {
964         struct ast_dial *dial = data;
965         struct ari_origination *origination = ast_dial_get_user_data(dial);
966         enum ast_dial_result res;
967
968         res = ast_dial_run(dial, NULL, 0);
969         if (res != AST_DIAL_RESULT_ANSWERED) {
970                 goto end;
971         }
972
973         if (!ast_strlen_zero(origination->appdata)) {
974                 struct ast_app *app = pbx_findapp("Stasis");
975
976                 if (app) {
977                         ast_verb(4, "Launching Stasis(%s) on %s\n", origination->appdata,
978                                 ast_channel_name(ast_dial_answered(dial)));
979                         pbx_exec(ast_dial_answered(dial), app, origination->appdata);
980                 } else {
981                         ast_log(LOG_WARNING, "No such application 'Stasis'\n");
982                 }
983         } else {
984                 struct ast_channel *answered = ast_dial_answered(dial);
985
986                 if (!ast_strlen_zero(origination->context)) {
987                         ast_channel_context_set(answered, origination->context);
988                 }
989
990                 if (!ast_strlen_zero(origination->exten)) {
991                         ast_channel_exten_set(answered, origination->exten);
992                 }
993
994                 if (origination->priority > 0) {
995                         ast_channel_priority_set(answered, origination->priority);
996                 }
997
998                 if (ast_pbx_run(answered)) {
999                         ast_log(LOG_ERROR, "Failed to start PBX on %s\n", ast_channel_name(answered));
1000                 } else {
1001                         /* PBX will have taken care of hanging up, so we steal the answered channel so dial doesn't do it */
1002                         ast_dial_answered_steal(dial);
1003                 }
1004         }
1005
1006 end:
1007         ast_dial_destroy(dial);
1008         ast_free(origination);
1009         return NULL;
1010 }
1011
1012 static void ari_channels_handle_originate_with_id(const char *args_endpoint,
1013         const char *args_extension,
1014         const char *args_context,
1015         long args_priority,
1016         const char *args_label,
1017         const char *args_app,
1018         const char *args_app_args,
1019         const char *args_caller_id,
1020         int args_timeout,
1021         struct ast_variable *variables,
1022         const char *args_channel_id,
1023         const char *args_other_channel_id,
1024         const char *args_originator,
1025         const char *args_formats,
1026         struct ast_ari_response *response)
1027 {
1028         char *dialtech;
1029         char dialdevice[AST_CHANNEL_NAME];
1030         struct ast_dial *dial;
1031         char *caller_id = NULL;
1032         char *cid_num = NULL;
1033         char *cid_name = NULL;
1034         char *stuff;
1035         struct ast_channel *other = NULL;
1036         struct ast_channel *chan = NULL;
1037         RAII_VAR(struct ast_channel_snapshot *, snapshot, NULL, ao2_cleanup);
1038         struct ast_assigned_ids assignedids = {
1039                 .uniqueid = args_channel_id,
1040                 .uniqueid2 = args_other_channel_id,
1041         };
1042         struct ari_origination *origination;
1043         pthread_t thread;
1044         struct ast_format_cap *format_cap = NULL;
1045
1046         if ((assignedids.uniqueid && AST_MAX_PUBLIC_UNIQUEID < strlen(assignedids.uniqueid))
1047                 || (assignedids.uniqueid2 && AST_MAX_PUBLIC_UNIQUEID < strlen(assignedids.uniqueid2))) {
1048                 ast_ari_response_error(response, 400, "Bad Request",
1049                         "Uniqueid length exceeds maximum of %d", AST_MAX_PUBLIC_UNIQUEID);
1050                 return;
1051         }
1052
1053         if (ast_strlen_zero(args_endpoint)) {
1054                 ast_ari_response_error(response, 400, "Bad Request",
1055                         "Endpoint must be specified");
1056                 return;
1057         }
1058
1059         if (!ast_strlen_zero(args_originator) && !ast_strlen_zero(args_formats)) {
1060                 ast_ari_response_error(response, 400, "Bad Request",
1061                         "Originator and formats can't both be specified");
1062                 return;
1063         }
1064
1065         dialtech = ast_strdupa(args_endpoint);
1066         if ((stuff = strchr(dialtech, '/'))) {
1067                 *stuff++ = '\0';
1068                 ast_copy_string(dialdevice, stuff, sizeof(dialdevice));
1069         }
1070
1071         if (ast_strlen_zero(dialtech) || ast_strlen_zero(dialdevice)) {
1072                 ast_ari_response_error(response, 400, "Bad Request",
1073                         "Invalid endpoint specified");
1074                 return;
1075         }
1076
1077         if (!ast_strlen_zero(args_app)) {
1078                 RAII_VAR(struct ast_str *, appdata, ast_str_create(64), ast_free);
1079
1080                 if (!appdata) {
1081                         ast_ari_response_alloc_failed(response);
1082                         return;
1083                 }
1084
1085                 ast_str_set(&appdata, 0, "%s", args_app);
1086                 if (!ast_strlen_zero(args_app_args)) {
1087                         ast_str_append(&appdata, 0, ",%s", args_app_args);
1088                 }
1089
1090                 origination = ast_calloc(1, sizeof(*origination) + ast_str_size(appdata) + 1);
1091                 if (!origination) {
1092                         ast_ari_response_alloc_failed(response);
1093                         return;
1094                 }
1095
1096                 strcpy(origination->appdata, ast_str_buffer(appdata));
1097         } else if (!ast_strlen_zero(args_extension)) {
1098                 origination = ast_calloc(1, sizeof(*origination) + 1);
1099                 if (!origination) {
1100                         ast_ari_response_alloc_failed(response);
1101                         return;
1102                 }
1103
1104                 ast_copy_string(origination->context, S_OR(args_context, "default"), sizeof(origination->context));
1105                 ast_copy_string(origination->exten, args_extension, sizeof(origination->exten));
1106
1107                 if (!ast_strlen_zero(args_label)) {
1108                         /* A label was provided in the request, use that */
1109                         int ipri = 1;
1110                         if (sscanf(args_label, "%30d", &ipri) != 1) {
1111                                 ipri = ast_findlabel_extension(chan, origination->context, origination->exten, args_label, args_caller_id);
1112
1113                                 if (ipri == -1) {
1114                                         ast_log(AST_LOG_ERROR, "Requested label: %s can not be found in context: %s\n", args_label, args_context);
1115                                         ast_ari_response_error(response, 404, "Not Found", "Requested label can not be found");
1116                                         return;
1117                                 }
1118                         } else {
1119                                 ast_debug(3, "Numeric value provided for label, jumping to that priority\n");
1120                         }
1121
1122                         if (ipri == 0) {
1123                                 ast_log(AST_LOG_ERROR, "Invalid priority label '%s' specified for extension %s in context: %s\n",
1124                                                 args_label, args_extension, args_context);
1125                                 ast_ari_response_error(response, 400, "Bad Request", "Requested priority is illegal");
1126                                 return;
1127                         }
1128
1129                         /* Our priority was provided by a label */
1130                         origination->priority =  ipri;
1131                 } else {
1132                         /* No label provided, use provided priority */
1133                         origination->priority = args_priority ? args_priority : 1;
1134                 }
1135
1136                 origination->appdata[0] = '\0';
1137         } else {
1138                 ast_ari_response_error(response, 400, "Bad Request",
1139                         "Application or extension must be specified");
1140                 return;
1141         }
1142
1143         dial = ast_dial_create();
1144         if (!dial) {
1145                 ast_ari_response_alloc_failed(response);
1146                 ast_free(origination);
1147                 return;
1148         }
1149         ast_dial_set_user_data(dial, origination);
1150
1151         if (ast_dial_append(dial, dialtech, dialdevice, &assignedids)) {
1152                 ast_ari_response_alloc_failed(response);
1153                 ast_dial_destroy(dial);
1154                 ast_free(origination);
1155                 return;
1156         }
1157
1158         if (args_timeout > 0) {
1159                 ast_dial_set_global_timeout(dial, args_timeout * 1000);
1160         } else if (args_timeout == -1) {
1161                 ast_dial_set_global_timeout(dial, -1);
1162         } else {
1163                 ast_dial_set_global_timeout(dial, 30000);
1164         }
1165
1166         if (!ast_strlen_zero(args_caller_id)) {
1167                 caller_id = ast_strdupa(args_caller_id);
1168                 ast_callerid_parse(caller_id, &cid_name, &cid_num);
1169
1170                 if (ast_is_shrinkable_phonenumber(cid_num)) {
1171                         ast_shrink_phone_number(cid_num);
1172                 }
1173         }
1174
1175         if (!ast_strlen_zero(args_originator)) {
1176                 other = ast_channel_get_by_name(args_originator);
1177                 if (!other) {
1178                         ast_ari_response_error(
1179                                 response, 400, "Bad Request",
1180                                 "Provided originator channel was not found");
1181                         ast_dial_destroy(dial);
1182                         ast_free(origination);
1183                         return;
1184                 }
1185         }
1186
1187         if (!ast_strlen_zero(args_formats)) {
1188                 char *format_name;
1189                 char *formats_copy = ast_strdupa(args_formats);
1190
1191                 if (!(format_cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
1192                         ast_ari_response_alloc_failed(response);
1193                         ast_dial_destroy(dial);
1194                         ast_free(origination);
1195                         ast_channel_cleanup(other);
1196                         return;
1197                 }
1198
1199                 while ((format_name = ast_strip(strsep(&formats_copy, ",")))) {
1200                         struct ast_format *fmt = ast_format_cache_get(format_name);
1201
1202                         if (!fmt || ast_format_cap_append(format_cap, fmt, 0)) {
1203                                 if (!fmt) {
1204                                         ast_ari_response_error(
1205                                                 response, 400, "Bad Request",
1206                                                 "Provided format (%s) was not found", format_name);
1207                                 } else {
1208                                         ast_ari_response_alloc_failed(response);
1209                                 }
1210                                 ast_dial_destroy(dial);
1211                                 ast_free(origination);
1212                                 ast_channel_cleanup(other);
1213                                 ao2_ref(format_cap, -1);
1214                                 ao2_cleanup(fmt);
1215                                 return;
1216                         }
1217                         ao2_ref(fmt, -1);
1218                 }
1219         }
1220
1221         if (ast_dial_prerun(dial, other, format_cap)) {
1222                 if (ast_channel_errno() == AST_CHANNEL_ERROR_ID_EXISTS) {
1223                         ast_ari_response_error(response, 409, "Conflict",
1224                                 "Channel with given unique ID already exists");
1225                 } else {
1226                         ast_ari_response_alloc_failed(response);
1227                 }
1228                 ast_dial_destroy(dial);
1229                 ast_free(origination);
1230                 ast_channel_cleanup(other);
1231                 return;
1232         }
1233
1234         ast_channel_cleanup(other);
1235         ao2_cleanup(format_cap);
1236
1237         chan = ast_dial_get_channel(dial, 0);
1238         if (!chan) {
1239                 ast_ari_response_alloc_failed(response);
1240                 ast_dial_destroy(dial);
1241                 ast_free(origination);
1242                 return;
1243         }
1244
1245         if (!ast_strlen_zero(cid_num) || !ast_strlen_zero(cid_name)) {
1246                 struct ast_party_connected_line connected;
1247
1248                 /*
1249                  * It seems strange to set the CallerID on an outgoing call leg
1250                  * to whom we are calling, but this function's callers are doing
1251                  * various Originate methods.  This call leg goes to the local
1252                  * user.  Once the called party answers, the dialplan needs to
1253                  * be able to access the CallerID from the CALLERID function as
1254                  * if the called party had placed this call.
1255                  */
1256                 ast_set_callerid(chan, cid_num, cid_name, cid_num);
1257
1258                 ast_party_connected_line_set_init(&connected, ast_channel_connected(chan));
1259                 if (!ast_strlen_zero(cid_num)) {
1260                         connected.id.number.valid = 1;
1261                         connected.id.number.str = (char *) cid_num;
1262                         connected.id.number.presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1263                 }
1264                 if (!ast_strlen_zero(cid_name)) {
1265                         connected.id.name.valid = 1;
1266                         connected.id.name.str = (char *) cid_name;
1267                         connected.id.name.presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1268                 }
1269                 ast_channel_set_connected_line(chan, &connected, NULL);
1270         }
1271
1272         ast_channel_lock(chan);
1273         if (variables) {
1274                 ast_set_variables(chan, variables);
1275         }
1276         ast_set_flag(ast_channel_flags(chan), AST_FLAG_ORIGINATED);
1277
1278         if (!ast_strlen_zero(args_app)) {
1279                 struct ast_channel *local_peer;
1280
1281                 stasis_app_subscribe_channel(args_app, chan);
1282
1283                 /* Subscribe to the Local channel peer also. */
1284                 local_peer = ast_local_get_peer(chan);
1285                 if (local_peer) {
1286                         stasis_app_subscribe_channel(args_app, local_peer);
1287                         ast_channel_unref(local_peer);
1288                 }
1289         }
1290
1291         snapshot = ast_channel_snapshot_get_latest(ast_channel_uniqueid(chan));
1292         ast_channel_unlock(chan);
1293
1294         /* Before starting the async dial bump the ref in case the dial quickly goes away and takes
1295          * the reference with it
1296          */
1297         ast_channel_ref(chan);
1298
1299         if (ast_pthread_create_detached(&thread, NULL, ari_originate_dial, dial)) {
1300                 ast_ari_response_alloc_failed(response);
1301                 ast_dial_destroy(dial);
1302                 ast_free(origination);
1303         } else {
1304                 ast_ari_response_ok(response, ast_channel_snapshot_to_json(snapshot, NULL));
1305         }
1306
1307         ast_channel_unref(chan);
1308         return;
1309 }
1310
1311 /*!
1312  * \internal
1313  * \brief Convert a \c ast_json list of key/value pair tuples into a \c ast_variable list
1314  * \since 13.3.0
1315  *
1316  * \param[out] response HTTP response if error
1317  * \param json_variables The JSON blob containing the variable
1318  * \param[out] variables An out reference to the variables to populate.
1319  *
1320  * \retval 0 on success.
1321  * \retval -1 on error.
1322  */
1323 static int json_to_ast_variables(struct ast_ari_response *response, struct ast_json *json_variables, struct ast_variable **variables)
1324 {
1325         enum ast_json_to_ast_vars_code res;
1326
1327         res = ast_json_to_ast_variables(json_variables, variables);
1328         switch (res) {
1329         case AST_JSON_TO_AST_VARS_CODE_SUCCESS:
1330                 return 0;
1331         case AST_JSON_TO_AST_VARS_CODE_INVALID_TYPE:
1332                 ast_ari_response_error(response, 400, "Bad Request",
1333                         "Only string values in the 'variables' object allowed");
1334                 break;
1335         case AST_JSON_TO_AST_VARS_CODE_OOM:
1336                 ast_ari_response_alloc_failed(response);
1337                 break;
1338         }
1339         ast_log(AST_LOG_ERROR, "Unable to convert 'variables' in JSON body to channel variables\n");
1340
1341         return -1;
1342 }
1343
1344 void ast_ari_channels_originate_with_id(struct ast_variable *headers,
1345         struct ast_ari_channels_originate_with_id_args *args,
1346         struct ast_ari_response *response)
1347 {
1348         struct ast_variable *variables = NULL;
1349
1350         /* Parse any query parameters out of the body parameter */
1351         if (args->variables) {
1352                 struct ast_json *json_variables;
1353
1354                 ast_ari_channels_originate_with_id_parse_body(args->variables, args);
1355                 json_variables = ast_json_object_get(args->variables, "variables");
1356                 if (json_variables
1357                         && json_to_ast_variables(response, json_variables, &variables)) {
1358                         return;
1359                 }
1360         }
1361
1362         ari_channels_handle_originate_with_id(
1363                 args->endpoint,
1364                 args->extension,
1365                 args->context,
1366                 args->priority,
1367                 args->label,
1368                 args->app,
1369                 args->app_args,
1370                 args->caller_id,
1371                 args->timeout,
1372                 variables,
1373                 args->channel_id,
1374                 args->other_channel_id,
1375                 args->originator,
1376                 args->formats,
1377                 response);
1378         ast_variables_destroy(variables);
1379 }
1380
1381 void ast_ari_channels_originate(struct ast_variable *headers,
1382         struct ast_ari_channels_originate_args *args,
1383         struct ast_ari_response *response)
1384 {
1385         struct ast_variable *variables = NULL;
1386
1387         /* Parse any query parameters out of the body parameter */
1388         if (args->variables) {
1389                 struct ast_json *json_variables;
1390
1391                 ast_ari_channels_originate_parse_body(args->variables, args);
1392                 json_variables = ast_json_object_get(args->variables, "variables");
1393                 if (json_variables
1394                         && json_to_ast_variables(response, json_variables, &variables)) {
1395                         return;
1396                 }
1397         }
1398
1399         ari_channels_handle_originate_with_id(
1400                 args->endpoint,
1401                 args->extension,
1402                 args->context,
1403                 args->priority,
1404                 args->label,
1405                 args->app,
1406                 args->app_args,
1407                 args->caller_id,
1408                 args->timeout,
1409                 variables,
1410                 args->channel_id,
1411                 args->other_channel_id,
1412                 args->originator,
1413                 args->formats,
1414                 response);
1415         ast_variables_destroy(variables);
1416 }
1417
1418 void ast_ari_channels_get_channel_var(struct ast_variable *headers,
1419         struct ast_ari_channels_get_channel_var_args *args,
1420         struct ast_ari_response *response)
1421 {
1422         RAII_VAR(struct ast_json *, json, NULL, ast_json_unref);
1423         RAII_VAR(struct stasis_app_control *, control, NULL, ao2_cleanup);
1424         RAII_VAR(struct ast_str *, value, ast_str_create(32), ast_free);
1425         RAII_VAR(struct ast_channel *, channel, NULL, ast_channel_cleanup);
1426
1427         ast_assert(response != NULL);
1428
1429         if (!value) {
1430                 ast_ari_response_alloc_failed(response);
1431                 return;
1432         }
1433
1434         if (ast_strlen_zero(args->variable)) {
1435                 ast_ari_response_error(
1436                         response, 400, "Bad Request",
1437                         "Variable name is required");
1438                 return;
1439         }
1440
1441         if (ast_strlen_zero(args->channel_id)) {
1442                 ast_ari_response_error(
1443                         response, 400, "Bad Request",
1444                         "Channel ID is required");
1445                 return;
1446         }
1447
1448         channel = ast_channel_get_by_name(args->channel_id);
1449         if (!channel) {
1450                 ast_ari_response_error(
1451                         response, 404, "Channel Not Found",
1452                         "Provided channel was not found");
1453                 return;
1454         }
1455
1456         /* You may be tempted to lock the channel you're about to read from. You
1457          * would be wrong. Some dialplan functions put the channel into
1458          * autoservice, which deadlocks if the channel is already locked.
1459          * ast_str_retrieve_variable() does its own locking, and the dialplan
1460          * functions need to as well. We should be fine without the lock.
1461          */
1462
1463         if (args->variable[strlen(args->variable) - 1] == ')') {
1464                 if (ast_func_read2(channel, args->variable, &value, 0)) {
1465                         ast_ari_response_error(
1466                                 response, 500, "Error With Function",
1467                                 "Unable to read provided function");
1468                         return;
1469                 }
1470         } else {
1471                 if (!ast_str_retrieve_variable(&value, 0, channel, NULL, args->variable)) {
1472                         ast_ari_response_error(
1473                                 response, 404, "Variable Not Found",
1474                                 "Provided variable was not found");
1475                         return;
1476                 }
1477         }
1478
1479         if (!(json = ast_json_pack("{s: s}", "value", S_OR(ast_str_buffer(value), "")))) {
1480                 ast_ari_response_alloc_failed(response);
1481                 return;
1482         }
1483
1484         ast_ari_response_ok(response, ast_json_ref(json));
1485 }
1486
1487 void ast_ari_channels_set_channel_var(struct ast_variable *headers,
1488         struct ast_ari_channels_set_channel_var_args *args,
1489         struct ast_ari_response *response)
1490 {
1491         RAII_VAR(struct stasis_app_control *, control, NULL, ao2_cleanup);
1492
1493         ast_assert(response != NULL);
1494
1495         if (ast_strlen_zero(args->variable)) {
1496                 ast_ari_response_error(
1497                         response, 400, "Bad Request",
1498                         "Variable name is required");
1499                 return;
1500         }
1501
1502         control = find_control(response, args->channel_id);
1503         if (control == NULL) {
1504                 /* response filled in by find_control */
1505                 return;
1506         }
1507
1508         if (stasis_app_control_set_channel_var(control, args->variable, args->value)) {
1509                 ast_ari_response_error(
1510                         response, 400, "Bad Request",
1511                         "Failed to execute function");
1512                 return;
1513         }
1514
1515         ast_ari_response_no_content(response);
1516 }
1517
1518 static void ari_channels_handle_snoop_channel(
1519         const char *args_channel_id,
1520         const char *args_spy,
1521         const char *args_whisper,
1522         const char *args_app,
1523         const char *args_app_args,
1524         const char *args_snoop_id,
1525         struct ast_ari_response *response)
1526 {
1527         enum stasis_app_snoop_direction spy, whisper;
1528         RAII_VAR(struct ast_channel *, chan, NULL, ast_channel_cleanup);
1529         RAII_VAR(struct ast_channel *, snoop, NULL, ast_channel_cleanup);
1530         RAII_VAR(struct ast_channel_snapshot *, snapshot, NULL, ao2_cleanup);
1531
1532         ast_assert(response != NULL);
1533
1534         if (ast_strlen_zero(args_spy) || !strcmp(args_spy, "none")) {
1535                 spy = STASIS_SNOOP_DIRECTION_NONE;
1536         } else if (!strcmp(args_spy, "both")) {
1537                 spy = STASIS_SNOOP_DIRECTION_BOTH;
1538         } else if (!strcmp(args_spy, "out")) {
1539                 spy = STASIS_SNOOP_DIRECTION_OUT;
1540         } else if (!strcmp(args_spy, "in")) {
1541                 spy = STASIS_SNOOP_DIRECTION_IN;
1542         } else {
1543                 ast_ari_response_error(
1544                         response, 400, "Bad Request",
1545                         "Invalid direction specified for spy");
1546                 return;
1547         }
1548
1549         if (ast_strlen_zero(args_whisper) || !strcmp(args_whisper, "none")) {
1550                 whisper = STASIS_SNOOP_DIRECTION_NONE;
1551         } else if (!strcmp(args_whisper, "both")) {
1552                 whisper = STASIS_SNOOP_DIRECTION_BOTH;
1553         } else if (!strcmp(args_whisper, "out")) {
1554                 whisper = STASIS_SNOOP_DIRECTION_OUT;
1555         } else if (!strcmp(args_whisper, "in")) {
1556                 whisper = STASIS_SNOOP_DIRECTION_IN;
1557         } else {
1558                 ast_ari_response_error(
1559                         response, 400, "Bad Request",
1560                         "Invalid direction specified for whisper");
1561                 return;
1562         }
1563
1564         if (spy == STASIS_SNOOP_DIRECTION_NONE && whisper == STASIS_SNOOP_DIRECTION_NONE) {
1565                 ast_ari_response_error(
1566                         response, 400, "Bad Request",
1567                         "Direction must be specified for at least spy or whisper");
1568                 return;
1569         } else if (ast_strlen_zero(args_app)) {
1570                 ast_ari_response_error(
1571                         response, 400, "Bad Request",
1572                         "Application name is required");
1573                 return;
1574         }
1575
1576         chan = ast_channel_get_by_name(args_channel_id);
1577         if (chan == NULL) {
1578                 ast_ari_response_error(
1579                         response, 404, "Channel Not Found",
1580                         "Provided channel was not found");
1581                 return;
1582         }
1583
1584         snoop = stasis_app_control_snoop(chan, spy, whisper, args_app, args_app_args,
1585                 args_snoop_id);
1586         if (snoop == NULL) {
1587                 ast_ari_response_error(
1588                         response, 500, "Internal error",
1589                         "Snoop channel could not be created");
1590                 return;
1591         }
1592
1593         snapshot = ast_channel_snapshot_get_latest(ast_channel_uniqueid(snoop));
1594         ast_ari_response_ok(response, ast_channel_snapshot_to_json(snapshot, NULL));
1595 }
1596
1597 void ast_ari_channels_snoop_channel(struct ast_variable *headers,
1598         struct ast_ari_channels_snoop_channel_args *args,
1599         struct ast_ari_response *response)
1600 {
1601         ari_channels_handle_snoop_channel(
1602                 args->channel_id,
1603                 args->spy,
1604                 args->whisper,
1605                 args->app,
1606                 args->app_args,
1607                 args->snoop_id,
1608                 response);
1609 }
1610
1611 void ast_ari_channels_snoop_channel_with_id(struct ast_variable *headers,
1612         struct ast_ari_channels_snoop_channel_with_id_args *args,
1613         struct ast_ari_response *response)
1614 {
1615         ari_channels_handle_snoop_channel(
1616                 args->channel_id,
1617                 args->spy,
1618                 args->whisper,
1619                 args->app,
1620                 args->app_args,
1621                 args->snoop_id,
1622                 response);
1623 }
1624
1625 struct ari_channel_thread_data {
1626         struct ast_channel *chan;
1627         struct ast_str *stasis_stuff;
1628 };
1629
1630 static void chan_data_destroy(struct ari_channel_thread_data *chan_data)
1631 {
1632         ast_free(chan_data->stasis_stuff);
1633         ast_hangup(chan_data->chan);
1634         ast_free(chan_data);
1635 }
1636
1637 /*!
1638  * \brief Thread that owns stasis-created channel.
1639  *
1640  * The channel enters into a Stasis application immediately upon creation. In this
1641  * way, the channel can be manipulated by the Stasis application. Once the channel
1642  * exits the Stasis application, it is hung up.
1643  */
1644 static void *ari_channel_thread(void *data)
1645 {
1646         struct ari_channel_thread_data *chan_data = data;
1647         struct ast_app *stasis_app;
1648
1649         stasis_app = pbx_findapp("Stasis");
1650         if (!stasis_app) {
1651                 ast_log(LOG_ERROR, "Stasis dialplan application is not registered");
1652                 chan_data_destroy(chan_data);
1653                 return NULL;
1654         }
1655
1656         pbx_exec(chan_data->chan, stasis_app, ast_str_buffer(chan_data->stasis_stuff));
1657
1658         chan_data_destroy(chan_data);
1659
1660         return NULL;
1661 }
1662
1663 struct ast_datastore_info dialstring_info = {
1664         .type = "ARI Dialstring",
1665         .destroy = ast_free_ptr,
1666 };
1667
1668 /*!
1669  * \brief Save dialstring onto a channel datastore
1670  *
1671  * This will later be retrieved when it comes time to actually dial the channel
1672  *
1673  * \param chan The channel on which to save the dialstring
1674  * \param dialstring The dialstring to save
1675  * \retval 0 SUCCESS!
1676  * \reval -1 Failure :(
1677  */
1678 static int save_dialstring(struct ast_channel *chan, const char *dialstring)
1679 {
1680         struct ast_datastore *datastore;
1681
1682         datastore = ast_datastore_alloc(&dialstring_info, NULL);
1683         if (!datastore) {
1684                 return -1;
1685         }
1686
1687         datastore->data = ast_strdup(dialstring);
1688         if (!datastore->data) {
1689                 ast_datastore_free(datastore);
1690                 return -1;
1691         }
1692
1693         ast_channel_lock(chan);
1694         if (ast_channel_datastore_add(chan, datastore)) {
1695                 ast_channel_unlock(chan);
1696                 ast_datastore_free(datastore);
1697                 return -1;
1698         }
1699         ast_channel_unlock(chan);
1700
1701         return 0;
1702 }
1703
1704 /*!
1705  * \brief Retrieve the dialstring from the channel datastore
1706  *
1707  * \pre chan is locked
1708  * \param chan Channel that was previously created in ARI
1709  * \retval NULL Failed to find datastore
1710  * \retval non-NULL The dialstring
1711  */
1712 static char *restore_dialstring(struct ast_channel *chan)
1713 {
1714         struct ast_datastore *datastore;
1715
1716         datastore = ast_channel_datastore_find(chan, &dialstring_info, NULL);
1717         if (!datastore) {
1718                 return NULL;
1719         }
1720
1721         return datastore->data;
1722 }
1723
1724 void ast_ari_channels_create(struct ast_variable *headers,
1725         struct ast_ari_channels_create_args *args,
1726         struct ast_ari_response *response)
1727 {
1728         struct ast_assigned_ids assignedids = {
1729                 .uniqueid = args->channel_id,
1730                 .uniqueid2 = args->other_channel_id,
1731         };
1732         struct ari_channel_thread_data *chan_data;
1733         struct ast_channel_snapshot *snapshot;
1734         pthread_t thread;
1735         char *dialtech;
1736         char dialdevice[AST_CHANNEL_NAME];
1737         char *stuff;
1738         int cause;
1739         struct ast_format_cap *request_cap;
1740         struct ast_channel *originator;
1741
1742         if (!ast_strlen_zero(args->originator) && !ast_strlen_zero(args->formats)) {
1743                 ast_ari_response_error(response, 400, "Bad Request",
1744                         "Originator and formats can't both be specified");
1745                 return;
1746         }
1747
1748         if (ast_strlen_zero(args->endpoint)) {
1749                 ast_ari_response_error(response, 400, "Bad Request",
1750                         "Endpoint must be specified");
1751                 return;
1752         }
1753
1754         chan_data = ast_calloc(1, sizeof(*chan_data));
1755         if (!chan_data) {
1756                 ast_ari_response_alloc_failed(response);
1757                 return;
1758         }
1759
1760         chan_data->stasis_stuff = ast_str_create(32);
1761         if (!chan_data->stasis_stuff) {
1762                 ast_ari_response_alloc_failed(response);
1763                 chan_data_destroy(chan_data);
1764                 return;
1765         }
1766
1767         ast_str_append(&chan_data->stasis_stuff, 0, "%s", args->app);
1768         if (!ast_strlen_zero(args->app_args)) {
1769                 ast_str_append(&chan_data->stasis_stuff, 0, ",%s", args->app_args);
1770         }
1771
1772         dialtech = ast_strdupa(args->endpoint);
1773         if ((stuff = strchr(dialtech, '/'))) {
1774                 *stuff++ = '\0';
1775                 ast_copy_string(dialdevice, stuff, sizeof(dialdevice));
1776         }
1777
1778         originator = ast_channel_get_by_name(args->originator);
1779         if (originator) {
1780                 request_cap = ao2_bump(ast_channel_nativeformats(originator));
1781                 if (!ast_strlen_zero(args->app)) {
1782                         stasis_app_subscribe_channel(args->app, originator);
1783                 }
1784         } else if (!ast_strlen_zero(args->formats)) {
1785                 char *format_name;
1786                 char *formats_copy = ast_strdupa(args->formats);
1787
1788                 if (!(request_cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
1789                         ast_ari_response_alloc_failed(response);
1790                         chan_data_destroy(chan_data);
1791                         return;
1792                 }
1793
1794                 while ((format_name = ast_strip(strsep(&formats_copy, ",")))) {
1795                         struct ast_format *fmt = ast_format_cache_get(format_name);
1796
1797                         if (!fmt || ast_format_cap_append(request_cap, fmt, 0)) {
1798                                 if (!fmt) {
1799                                         ast_ari_response_error(
1800                                                 response, 400, "Bad Request",
1801                                                 "Provided format (%s) was not found", format_name);
1802                                 } else {
1803                                         ast_ari_response_alloc_failed(response);
1804                                 }
1805                                 ao2_ref(request_cap, -1);
1806                                 ao2_cleanup(fmt);
1807                                 chan_data_destroy(chan_data);
1808                                 return;
1809                         }
1810                         ao2_ref(fmt, -1);
1811                 }
1812         } else {
1813                 if (!(request_cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
1814                         ast_ari_response_alloc_failed(response);
1815                         chan_data_destroy(chan_data);
1816                         return;
1817                 }
1818
1819                 ast_format_cap_append_by_type(request_cap, AST_MEDIA_TYPE_AUDIO);
1820         }
1821
1822         chan_data->chan = ast_request(dialtech, request_cap, &assignedids, originator, dialdevice, &cause);
1823         ao2_cleanup(request_cap);
1824
1825         if (!chan_data->chan) {
1826                 if (ast_channel_errno() == AST_CHANNEL_ERROR_ID_EXISTS) {
1827                         ast_ari_response_error(response, 409, "Conflict",
1828                                 "Channel with given unique ID already exists");
1829                 } else {
1830                         ast_ari_response_alloc_failed(response);
1831                 }
1832                 ast_channel_cleanup(originator);
1833                 chan_data_destroy(chan_data);
1834                 return;
1835         }
1836
1837         if (!ast_strlen_zero(args->app)) {
1838                 stasis_app_subscribe_channel(args->app, chan_data->chan);
1839         }
1840
1841         ast_channel_cleanup(originator);
1842
1843         if (save_dialstring(chan_data->chan, stuff)) {
1844                 ast_ari_response_alloc_failed(response);
1845                 chan_data_destroy(chan_data);
1846                 return;
1847         }
1848
1849         snapshot = ast_channel_snapshot_get_latest(ast_channel_uniqueid(chan_data->chan));
1850
1851         if (ast_pthread_create_detached(&thread, NULL, ari_channel_thread, chan_data)) {
1852                 ast_ari_response_alloc_failed(response);
1853                 chan_data_destroy(chan_data);
1854         } else {
1855                 ast_ari_response_ok(response, ast_channel_snapshot_to_json(snapshot, NULL));
1856         }
1857
1858         ao2_ref(snapshot, -1);
1859 }
1860
1861 void ast_ari_channels_dial(struct ast_variable *headers,
1862         struct ast_ari_channels_dial_args *args,
1863         struct ast_ari_response *response)
1864 {
1865         RAII_VAR(struct stasis_app_control *, control, NULL, ao2_cleanup);
1866         RAII_VAR(struct ast_channel *, caller, NULL, ast_channel_cleanup);
1867         RAII_VAR(struct ast_channel *, callee, NULL, ast_channel_cleanup);
1868         char *dialstring;
1869
1870         control = find_control(response, args->channel_id);
1871         if (control == NULL) {
1872                 /* Response filled in by find_control */
1873                 return;
1874         }
1875
1876         caller = ast_channel_get_by_name(args->caller);
1877
1878         callee = ast_channel_get_by_name(args->channel_id);
1879         if (!callee) {
1880                 ast_ari_response_error(response, 404, "Not Found",
1881                         "Callee not found");
1882                 return;
1883         }
1884
1885         if (ast_channel_state(callee) != AST_STATE_DOWN
1886                 && ast_channel_state(callee) != AST_STATE_RESERVED) {
1887                 ast_ari_response_error(response, 409, "Conflict",
1888                         "Channel is not in the 'Down' state");
1889                 return;
1890         }
1891
1892         /* XXX This is straight up copied from main/dial.c. It's probably good
1893          * to separate this to some common method.
1894          */
1895         if (caller) {
1896                 ast_channel_lock_both(caller, callee);
1897         } else {
1898                 ast_channel_lock(callee);
1899         }
1900
1901         dialstring = restore_dialstring(callee);
1902         if (!dialstring) {
1903                 ast_channel_unlock(callee);
1904                 if (caller) {
1905                         ast_channel_unlock(caller);
1906                 }
1907                 ast_ari_response_error(response, 409, "Conflict",
1908                         "Dialing a channel not created by ARI");
1909                 return;
1910         }
1911         /* Make a copy of the dialstring just in case some jerk tries to hang up the
1912          * channel before we can actually dial
1913          */
1914         dialstring = ast_strdupa(dialstring);
1915
1916         ast_channel_stage_snapshot(callee);
1917         if (caller) {
1918                 ast_channel_inherit_variables(caller, callee);
1919                 ast_channel_datastore_inherit(caller, callee);
1920                 ast_max_forwards_decrement(callee);
1921
1922                 /* Copy over callerid information */
1923                 ast_party_redirecting_copy(ast_channel_redirecting(callee), ast_channel_redirecting(caller));
1924
1925                 ast_channel_dialed(callee)->transit_network_select = ast_channel_dialed(caller)->transit_network_select;
1926
1927                 ast_connected_line_copy_from_caller(ast_channel_connected(callee), ast_channel_caller(caller));
1928
1929                 ast_channel_language_set(callee, ast_channel_language(caller));
1930                 ast_channel_req_accountcodes(callee, caller, AST_CHANNEL_REQUESTOR_BRIDGE_PEER);
1931                 if (ast_strlen_zero(ast_channel_musicclass(callee)))
1932                         ast_channel_musicclass_set(callee, ast_channel_musicclass(caller));
1933
1934                 ast_channel_adsicpe_set(callee, ast_channel_adsicpe(caller));
1935                 ast_channel_transfercapability_set(callee, ast_channel_transfercapability(caller));
1936                 ast_channel_unlock(caller);
1937         }
1938
1939         ast_channel_stage_snapshot_done(callee);
1940         ast_channel_unlock(callee);
1941
1942         if (stasis_app_control_dial(control, dialstring, args->timeout)) {
1943                 ast_ari_response_alloc_failed(response);
1944                 return;
1945         }
1946
1947         ast_ari_response_no_content(response);
1948 }