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