res/res_ari: Fix null endpoint handle
[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->context;
174                 exten = S_OR(args->extension, snapshot->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->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->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->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->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         RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
837         struct stasis_cache *cache;
838         struct ast_channel_snapshot *snapshot;
839
840         cache = ast_channel_cache();
841         if (!cache) {
842                 ast_ari_response_error(
843                         response, 500, "Internal Server Error",
844                         "Message bus not initialized");
845                 return;
846         }
847
848         msg = stasis_cache_get(cache, ast_channel_snapshot_type(),
849                                    args->channel_id);
850         if (!msg) {
851                 ast_ari_response_error(
852                         response, 404, "Not Found",
853                         "Channel not found");
854                 return;
855         }
856
857         snapshot = stasis_message_data(msg);
858         ast_assert(snapshot != NULL);
859
860         ast_ari_response_ok(response,
861                                 ast_channel_snapshot_to_json(snapshot, NULL));
862 }
863
864 void ast_ari_channels_hangup(struct ast_variable *headers,
865         struct ast_ari_channels_hangup_args *args,
866         struct ast_ari_response *response)
867 {
868         RAII_VAR(struct ast_channel *, chan, NULL, ao2_cleanup);
869         int cause;
870
871         chan = ast_channel_get_by_name(args->channel_id);
872         if (chan == NULL) {
873                 ast_ari_response_error(
874                         response, 404, "Not Found",
875                         "Channel not found");
876                 return;
877         }
878
879         if (ast_strlen_zero(args->reason) || !strcmp(args->reason, "normal")) {
880                 cause = AST_CAUSE_NORMAL;
881         } else if (!strcmp(args->reason, "busy")) {
882                 cause = AST_CAUSE_BUSY;
883         } else if (!strcmp(args->reason, "congestion")) {
884                 cause = AST_CAUSE_CONGESTION;
885         } else if (!strcmp(args->reason, "no_answer")) {
886                 cause = AST_CAUSE_NOANSWER;
887         } else if(!strcmp(args->reason, "answered_elsewhere")) {
888                 cause = AST_CAUSE_ANSWERED_ELSEWHERE;
889         } else {
890                 ast_ari_response_error(
891                         response, 400, "Invalid Reason",
892                         "Invalid reason for hangup provided");
893                 return;
894         }
895
896         ast_channel_hangupcause_set(chan, cause);
897         ast_softhangup(chan, AST_SOFTHANGUP_EXPLICIT);
898
899         ast_ari_response_no_content(response);
900 }
901
902 void ast_ari_channels_list(struct ast_variable *headers,
903         struct ast_ari_channels_list_args *args,
904         struct ast_ari_response *response)
905 {
906         RAII_VAR(struct stasis_cache *, cache, NULL, ao2_cleanup);
907         RAII_VAR(struct ao2_container *, snapshots, NULL, ao2_cleanup);
908         RAII_VAR(struct ast_json *, json, NULL, ast_json_unref);
909         struct ao2_iterator i;
910         void *obj;
911         struct stasis_message_sanitizer *sanitize = stasis_app_get_sanitizer();
912
913         cache = ast_channel_cache();
914         if (!cache) {
915                 ast_ari_response_error(
916                         response, 500, "Internal Server Error",
917                         "Message bus not initialized");
918                 return;
919         }
920         ao2_ref(cache, +1);
921
922         snapshots = stasis_cache_dump(cache, ast_channel_snapshot_type());
923         if (!snapshots) {
924                 ast_ari_response_alloc_failed(response);
925                 return;
926         }
927
928         json = ast_json_array_create();
929         if (!json) {
930                 ast_ari_response_alloc_failed(response);
931                 return;
932         }
933
934         i = ao2_iterator_init(snapshots, 0);
935         while ((obj = ao2_iterator_next(&i))) {
936                 RAII_VAR(struct stasis_message *, msg, obj, ao2_cleanup);
937                 struct ast_channel_snapshot *snapshot = stasis_message_data(msg);
938                 int r;
939
940                 if (sanitize && sanitize->channel_snapshot
941                         && sanitize->channel_snapshot(snapshot)) {
942                         continue;
943                 }
944
945                 r = ast_json_array_append(
946                         json, ast_channel_snapshot_to_json(snapshot, NULL));
947                 if (r != 0) {
948                         ast_ari_response_alloc_failed(response);
949                         ao2_iterator_destroy(&i);
950                         return;
951                 }
952         }
953         ao2_iterator_destroy(&i);
954
955         ast_ari_response_ok(response, ast_json_ref(json));
956 }
957
958 /*! \brief Structure used for origination */
959 struct ari_origination {
960         /*! \brief Dialplan context */
961         char context[AST_MAX_CONTEXT];
962         /*! \brief Dialplan extension */
963         char exten[AST_MAX_EXTENSION];
964         /*! \brief Dialplan priority */
965         int priority;
966         /*! \brief Application data to pass to Stasis application */
967         char appdata[0];
968 };
969
970 /*! \brief Thread which dials and executes upon answer */
971 static void *ari_originate_dial(void *data)
972 {
973         struct ast_dial *dial = data;
974         struct ari_origination *origination = ast_dial_get_user_data(dial);
975         enum ast_dial_result res;
976
977         res = ast_dial_run(dial, NULL, 0);
978         if (res != AST_DIAL_RESULT_ANSWERED) {
979                 goto end;
980         }
981
982         if (!ast_strlen_zero(origination->appdata)) {
983                 struct ast_app *app = pbx_findapp("Stasis");
984
985                 if (app) {
986                         ast_verb(4, "Launching Stasis(%s) on %s\n", origination->appdata,
987                                 ast_channel_name(ast_dial_answered(dial)));
988                         pbx_exec(ast_dial_answered(dial), app, origination->appdata);
989                 } else {
990                         ast_log(LOG_WARNING, "No such application 'Stasis'\n");
991                 }
992         } else {
993                 struct ast_channel *answered = ast_dial_answered(dial);
994
995                 if (!ast_strlen_zero(origination->context)) {
996                         ast_channel_context_set(answered, origination->context);
997                 }
998
999                 if (!ast_strlen_zero(origination->exten)) {
1000                         ast_channel_exten_set(answered, origination->exten);
1001                 }
1002
1003                 if (origination->priority > 0) {
1004                         ast_channel_priority_set(answered, origination->priority);
1005                 }
1006
1007                 if (ast_pbx_run(answered)) {
1008                         ast_log(LOG_ERROR, "Failed to start PBX on %s\n", ast_channel_name(answered));
1009                 } else {
1010                         /* PBX will have taken care of hanging up, so we steal the answered channel so dial doesn't do it */
1011                         ast_dial_answered_steal(dial);
1012                 }
1013         }
1014
1015 end:
1016         ast_dial_destroy(dial);
1017         ast_free(origination);
1018         return NULL;
1019 }
1020
1021 static void ari_channels_handle_originate_with_id(const char *args_endpoint,
1022         const char *args_extension,
1023         const char *args_context,
1024         long args_priority,
1025         const char *args_label,
1026         const char *args_app,
1027         const char *args_app_args,
1028         const char *args_caller_id,
1029         int args_timeout,
1030         struct ast_variable *variables,
1031         const char *args_channel_id,
1032         const char *args_other_channel_id,
1033         const char *args_originator,
1034         const char *args_formats,
1035         struct ast_ari_response *response)
1036 {
1037         char *dialtech;
1038         char dialdevice[AST_CHANNEL_NAME];
1039         struct ast_dial *dial;
1040         char *caller_id = NULL;
1041         char *cid_num = NULL;
1042         char *cid_name = NULL;
1043         char *stuff;
1044         struct ast_channel *other = NULL;
1045         struct ast_channel *chan = NULL;
1046         RAII_VAR(struct ast_channel_snapshot *, snapshot, NULL, ao2_cleanup);
1047         struct ast_assigned_ids assignedids = {
1048                 .uniqueid = args_channel_id,
1049                 .uniqueid2 = args_other_channel_id,
1050         };
1051         struct ari_origination *origination;
1052         pthread_t thread;
1053         struct ast_format_cap *format_cap = NULL;
1054
1055         if ((assignedids.uniqueid && AST_MAX_PUBLIC_UNIQUEID < strlen(assignedids.uniqueid))
1056                 || (assignedids.uniqueid2 && AST_MAX_PUBLIC_UNIQUEID < strlen(assignedids.uniqueid2))) {
1057                 ast_ari_response_error(response, 400, "Bad Request",
1058                         "Uniqueid length exceeds maximum of %d", AST_MAX_PUBLIC_UNIQUEID);
1059                 return;
1060         }
1061
1062         if (ast_strlen_zero(args_endpoint)) {
1063                 ast_ari_response_error(response, 400, "Bad Request",
1064                         "Endpoint must be specified");
1065                 return;
1066         }
1067
1068         if (!ast_strlen_zero(args_originator) && !ast_strlen_zero(args_formats)) {
1069                 ast_ari_response_error(response, 400, "Bad Request",
1070                         "Originator and formats can't both be specified");
1071                 return;
1072         }
1073
1074         dialtech = ast_strdupa(args_endpoint);
1075         if ((stuff = strchr(dialtech, '/'))) {
1076                 *stuff++ = '\0';
1077                 ast_copy_string(dialdevice, stuff, sizeof(dialdevice));
1078         }
1079
1080         if (ast_strlen_zero(dialtech) || ast_strlen_zero(dialdevice)) {
1081                 ast_ari_response_error(response, 400, "Bad Request",
1082                         "Invalid endpoint specified");
1083                 return;
1084         }
1085
1086         if (!ast_strlen_zero(args_app)) {
1087                 RAII_VAR(struct ast_str *, appdata, ast_str_create(64), ast_free);
1088
1089                 if (!appdata) {
1090                         ast_ari_response_alloc_failed(response);
1091                         return;
1092                 }
1093
1094                 ast_str_set(&appdata, 0, "%s", args_app);
1095                 if (!ast_strlen_zero(args_app_args)) {
1096                         ast_str_append(&appdata, 0, ",%s", args_app_args);
1097                 }
1098
1099                 origination = ast_calloc(1, sizeof(*origination) + ast_str_size(appdata) + 1);
1100                 if (!origination) {
1101                         ast_ari_response_alloc_failed(response);
1102                         return;
1103                 }
1104
1105                 strcpy(origination->appdata, ast_str_buffer(appdata));
1106         } else if (!ast_strlen_zero(args_extension)) {
1107                 origination = ast_calloc(1, sizeof(*origination) + 1);
1108                 if (!origination) {
1109                         ast_ari_response_alloc_failed(response);
1110                         return;
1111                 }
1112
1113                 ast_copy_string(origination->context, S_OR(args_context, "default"), sizeof(origination->context));
1114                 ast_copy_string(origination->exten, args_extension, sizeof(origination->exten));
1115
1116                 if (!ast_strlen_zero(args_label)) {
1117                         /* A label was provided in the request, use that */
1118                         int ipri = 1;
1119                         if (sscanf(args_label, "%30d", &ipri) != 1) {
1120                                 ipri = ast_findlabel_extension(chan, origination->context, origination->exten, args_label, args_caller_id);
1121
1122                                 if (ipri == -1) {
1123                                         ast_log(AST_LOG_ERROR, "Requested label: %s can not be found in context: %s\n", args_label, args_context);
1124                                         ast_ari_response_error(response, 404, "Not Found", "Requested label can not be found");
1125                                         return;
1126                                 }
1127                         } else {
1128                                 ast_debug(3, "Numeric value provided for label, jumping to that priority\n");
1129                         }
1130
1131                         if (ipri == 0) {
1132                                 ast_log(AST_LOG_ERROR, "Invalid priority label '%s' specified for extension %s in context: %s\n",
1133                                                 args_label, args_extension, args_context);
1134                                 ast_ari_response_error(response, 400, "Bad Request", "Requested priority is illegal");
1135                                 return;
1136                         }
1137
1138                         /* Our priority was provided by a label */
1139                         origination->priority =  ipri;
1140                 } else {
1141                         /* No label provided, use provided priority */
1142                         origination->priority = args_priority ? args_priority : 1;
1143                 }
1144
1145                 origination->appdata[0] = '\0';
1146         } else {
1147                 ast_ari_response_error(response, 400, "Bad Request",
1148                         "Application or extension must be specified");
1149                 return;
1150         }
1151
1152         dial = ast_dial_create();
1153         if (!dial) {
1154                 ast_ari_response_alloc_failed(response);
1155                 ast_free(origination);
1156                 return;
1157         }
1158         ast_dial_set_user_data(dial, origination);
1159
1160         if (ast_dial_append(dial, dialtech, dialdevice, &assignedids)) {
1161                 ast_ari_response_alloc_failed(response);
1162                 ast_dial_destroy(dial);
1163                 ast_free(origination);
1164                 return;
1165         }
1166
1167         if (args_timeout > 0) {
1168                 ast_dial_set_global_timeout(dial, args_timeout * 1000);
1169         } else if (args_timeout == -1) {
1170                 ast_dial_set_global_timeout(dial, -1);
1171         } else {
1172                 ast_dial_set_global_timeout(dial, 30000);
1173         }
1174
1175         if (!ast_strlen_zero(args_caller_id)) {
1176                 caller_id = ast_strdupa(args_caller_id);
1177                 ast_callerid_parse(caller_id, &cid_name, &cid_num);
1178
1179                 if (ast_is_shrinkable_phonenumber(cid_num)) {
1180                         ast_shrink_phone_number(cid_num);
1181                 }
1182         }
1183
1184         if (!ast_strlen_zero(args_originator)) {
1185                 other = ast_channel_get_by_name(args_originator);
1186                 if (!other) {
1187                         ast_ari_response_error(
1188                                 response, 400, "Bad Request",
1189                                 "Provided originator channel was not found");
1190                         ast_dial_destroy(dial);
1191                         ast_free(origination);
1192                         return;
1193                 }
1194         }
1195
1196         if (!ast_strlen_zero(args_formats)) {
1197                 char *format_name;
1198                 char *formats_copy = ast_strdupa(args_formats);
1199
1200                 if (!(format_cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
1201                         ast_ari_response_alloc_failed(response);
1202                         ast_dial_destroy(dial);
1203                         ast_free(origination);
1204                         ast_channel_cleanup(other);
1205                         return;
1206                 }
1207
1208                 while ((format_name = ast_strip(strsep(&formats_copy, ",")))) {
1209                         struct ast_format *fmt = ast_format_cache_get(format_name);
1210
1211                         if (!fmt || ast_format_cap_append(format_cap, fmt, 0)) {
1212                                 if (!fmt) {
1213                                         ast_ari_response_error(
1214                                                 response, 400, "Bad Request",
1215                                                 "Provided format (%s) was not found", format_name);
1216                                 } else {
1217                                         ast_ari_response_alloc_failed(response);
1218                                 }
1219                                 ast_dial_destroy(dial);
1220                                 ast_free(origination);
1221                                 ast_channel_cleanup(other);
1222                                 ao2_ref(format_cap, -1);
1223                                 ao2_cleanup(fmt);
1224                                 return;
1225                         }
1226                         ao2_ref(fmt, -1);
1227                 }
1228         }
1229
1230         if (ast_dial_prerun(dial, other, format_cap)) {
1231                 if (ast_channel_errno() == AST_CHANNEL_ERROR_ID_EXISTS) {
1232                         ast_ari_response_error(response, 409, "Conflict",
1233                                 "Channel with given unique ID already exists");
1234                 } else {
1235                         ast_ari_response_alloc_failed(response);
1236                 }
1237                 ast_dial_destroy(dial);
1238                 ast_free(origination);
1239                 ast_channel_cleanup(other);
1240                 return;
1241         }
1242
1243         ast_channel_cleanup(other);
1244         ao2_cleanup(format_cap);
1245
1246         chan = ast_dial_get_channel(dial, 0);
1247         if (!chan) {
1248                 ast_ari_response_alloc_failed(response);
1249                 ast_dial_destroy(dial);
1250                 ast_free(origination);
1251                 return;
1252         }
1253
1254         if (!ast_strlen_zero(cid_num) || !ast_strlen_zero(cid_name)) {
1255                 struct ast_party_connected_line connected;
1256
1257                 /*
1258                  * It seems strange to set the CallerID on an outgoing call leg
1259                  * to whom we are calling, but this function's callers are doing
1260                  * various Originate methods.  This call leg goes to the local
1261                  * user.  Once the called party answers, the dialplan needs to
1262                  * be able to access the CallerID from the CALLERID function as
1263                  * if the called party had placed this call.
1264                  */
1265                 ast_set_callerid(chan, cid_num, cid_name, cid_num);
1266
1267                 ast_party_connected_line_set_init(&connected, ast_channel_connected(chan));
1268                 if (!ast_strlen_zero(cid_num)) {
1269                         connected.id.number.valid = 1;
1270                         connected.id.number.str = (char *) cid_num;
1271                         connected.id.number.presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1272                 }
1273                 if (!ast_strlen_zero(cid_name)) {
1274                         connected.id.name.valid = 1;
1275                         connected.id.name.str = (char *) cid_name;
1276                         connected.id.name.presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
1277                 }
1278                 ast_channel_set_connected_line(chan, &connected, NULL);
1279         }
1280
1281         ast_channel_lock(chan);
1282         if (variables) {
1283                 ast_set_variables(chan, variables);
1284         }
1285         ast_set_flag(ast_channel_flags(chan), AST_FLAG_ORIGINATED);
1286
1287         if (!ast_strlen_zero(args_app)) {
1288                 struct ast_channel *local_peer;
1289
1290                 stasis_app_subscribe_channel(args_app, chan);
1291
1292                 /* Subscribe to the Local channel peer also. */
1293                 local_peer = ast_local_get_peer(chan);
1294                 if (local_peer) {
1295                         stasis_app_subscribe_channel(args_app, local_peer);
1296                         ast_channel_unref(local_peer);
1297                 }
1298         }
1299
1300         snapshot = ast_channel_snapshot_get_latest(ast_channel_uniqueid(chan));
1301         ast_channel_unlock(chan);
1302
1303         /* Before starting the async dial bump the ref in case the dial quickly goes away and takes
1304          * the reference with it
1305          */
1306         ast_channel_ref(chan);
1307
1308         if (ast_pthread_create_detached(&thread, NULL, ari_originate_dial, dial)) {
1309                 ast_ari_response_alloc_failed(response);
1310                 ast_dial_destroy(dial);
1311                 ast_free(origination);
1312         } else {
1313                 ast_ari_response_ok(response, ast_channel_snapshot_to_json(snapshot, NULL));
1314         }
1315
1316         ast_channel_unref(chan);
1317         return;
1318 }
1319
1320 /*!
1321  * \internal
1322  * \brief Convert a \c ast_json list of key/value pair tuples into a \c ast_variable list
1323  * \since 13.3.0
1324  *
1325  * \param[out] response HTTP response if error
1326  * \param json_variables The JSON blob containing the variable
1327  * \param[out] variables An out reference to the variables to populate.
1328  *
1329  * \retval 0 on success.
1330  * \retval -1 on error.
1331  */
1332 static int json_to_ast_variables(struct ast_ari_response *response, struct ast_json *json_variables, struct ast_variable **variables)
1333 {
1334         enum ast_json_to_ast_vars_code res;
1335
1336         res = ast_json_to_ast_variables(json_variables, variables);
1337         switch (res) {
1338         case AST_JSON_TO_AST_VARS_CODE_SUCCESS:
1339                 return 0;
1340         case AST_JSON_TO_AST_VARS_CODE_INVALID_TYPE:
1341                 ast_ari_response_error(response, 400, "Bad Request",
1342                         "Only string values in the 'variables' object allowed");
1343                 break;
1344         case AST_JSON_TO_AST_VARS_CODE_OOM:
1345                 ast_ari_response_alloc_failed(response);
1346                 break;
1347         }
1348         ast_log(AST_LOG_ERROR, "Unable to convert 'variables' in JSON body to channel variables\n");
1349
1350         return -1;
1351 }
1352
1353 void ast_ari_channels_originate_with_id(struct ast_variable *headers,
1354         struct ast_ari_channels_originate_with_id_args *args,
1355         struct ast_ari_response *response)
1356 {
1357         struct ast_variable *variables = NULL;
1358
1359         /* Parse any query parameters out of the body parameter */
1360         if (args->variables) {
1361                 struct ast_json *json_variables;
1362
1363                 ast_ari_channels_originate_with_id_parse_body(args->variables, args);
1364                 json_variables = ast_json_object_get(args->variables, "variables");
1365                 if (json_variables
1366                         && json_to_ast_variables(response, json_variables, &variables)) {
1367                         return;
1368                 }
1369         }
1370
1371         ari_channels_handle_originate_with_id(
1372                 args->endpoint,
1373                 args->extension,
1374                 args->context,
1375                 args->priority,
1376                 args->label,
1377                 args->app,
1378                 args->app_args,
1379                 args->caller_id,
1380                 args->timeout,
1381                 variables,
1382                 args->channel_id,
1383                 args->other_channel_id,
1384                 args->originator,
1385                 args->formats,
1386                 response);
1387         ast_variables_destroy(variables);
1388 }
1389
1390 void ast_ari_channels_originate(struct ast_variable *headers,
1391         struct ast_ari_channels_originate_args *args,
1392         struct ast_ari_response *response)
1393 {
1394         struct ast_variable *variables = NULL;
1395
1396         /* Parse any query parameters out of the body parameter */
1397         if (args->variables) {
1398                 struct ast_json *json_variables;
1399
1400                 ast_ari_channels_originate_parse_body(args->variables, args);
1401                 json_variables = ast_json_object_get(args->variables, "variables");
1402                 if (json_variables
1403                         && json_to_ast_variables(response, json_variables, &variables)) {
1404                         return;
1405                 }
1406         }
1407
1408         ari_channels_handle_originate_with_id(
1409                 args->endpoint,
1410                 args->extension,
1411                 args->context,
1412                 args->priority,
1413                 args->label,
1414                 args->app,
1415                 args->app_args,
1416                 args->caller_id,
1417                 args->timeout,
1418                 variables,
1419                 args->channel_id,
1420                 args->other_channel_id,
1421                 args->originator,
1422                 args->formats,
1423                 response);
1424         ast_variables_destroy(variables);
1425 }
1426
1427 void ast_ari_channels_get_channel_var(struct ast_variable *headers,
1428         struct ast_ari_channels_get_channel_var_args *args,
1429         struct ast_ari_response *response)
1430 {
1431         RAII_VAR(struct ast_json *, json, NULL, ast_json_unref);
1432         RAII_VAR(struct stasis_app_control *, control, NULL, ao2_cleanup);
1433         RAII_VAR(struct ast_str *, value, ast_str_create(32), ast_free);
1434         RAII_VAR(struct ast_channel *, channel, NULL, ast_channel_cleanup);
1435
1436         ast_assert(response != NULL);
1437
1438         if (!value) {
1439                 ast_ari_response_alloc_failed(response);
1440                 return;
1441         }
1442
1443         if (ast_strlen_zero(args->variable)) {
1444                 ast_ari_response_error(
1445                         response, 400, "Bad Request",
1446                         "Variable name is required");
1447                 return;
1448         }
1449
1450         if (ast_strlen_zero(args->channel_id)) {
1451                 ast_ari_response_error(
1452                         response, 400, "Bad Request",
1453                         "Channel ID is required");
1454                 return;
1455         }
1456
1457         channel = ast_channel_get_by_name(args->channel_id);
1458         if (!channel) {
1459                 ast_ari_response_error(
1460                         response, 404, "Channel Not Found",
1461                         "Provided channel was not found");
1462                 return;
1463         }
1464
1465         /* You may be tempted to lock the channel you're about to read from. You
1466          * would be wrong. Some dialplan functions put the channel into
1467          * autoservice, which deadlocks if the channel is already locked.
1468          * ast_str_retrieve_variable() does its own locking, and the dialplan
1469          * functions need to as well. We should be fine without the lock.
1470          */
1471
1472         if (args->variable[strlen(args->variable) - 1] == ')') {
1473                 if (ast_func_read2(channel, args->variable, &value, 0)) {
1474                         ast_ari_response_error(
1475                                 response, 500, "Error With Function",
1476                                 "Unable to read provided function");
1477                         return;
1478                 }
1479         } else {
1480                 if (!ast_str_retrieve_variable(&value, 0, channel, NULL, args->variable)) {
1481                         ast_ari_response_error(
1482                                 response, 404, "Variable Not Found",
1483                                 "Provided variable was not found");
1484                         return;
1485                 }
1486         }
1487
1488         if (!(json = ast_json_pack("{s: s}", "value", S_OR(ast_str_buffer(value), "")))) {
1489                 ast_ari_response_alloc_failed(response);
1490                 return;
1491         }
1492
1493         ast_ari_response_ok(response, ast_json_ref(json));
1494 }
1495
1496 void ast_ari_channels_set_channel_var(struct ast_variable *headers,
1497         struct ast_ari_channels_set_channel_var_args *args,
1498         struct ast_ari_response *response)
1499 {
1500         RAII_VAR(struct stasis_app_control *, control, NULL, ao2_cleanup);
1501
1502         ast_assert(response != NULL);
1503
1504         if (ast_strlen_zero(args->variable)) {
1505                 ast_ari_response_error(
1506                         response, 400, "Bad Request",
1507                         "Variable name is required");
1508                 return;
1509         }
1510
1511         control = find_control(response, args->channel_id);
1512         if (control == NULL) {
1513                 /* response filled in by find_control */
1514                 return;
1515         }
1516
1517         if (stasis_app_control_set_channel_var(control, args->variable, args->value)) {
1518                 ast_ari_response_error(
1519                         response, 400, "Bad Request",
1520                         "Failed to execute function");
1521                 return;
1522         }
1523
1524         ast_ari_response_no_content(response);
1525 }
1526
1527 static void ari_channels_handle_snoop_channel(
1528         const char *args_channel_id,
1529         const char *args_spy,
1530         const char *args_whisper,
1531         const char *args_app,
1532         const char *args_app_args,
1533         const char *args_snoop_id,
1534         struct ast_ari_response *response)
1535 {
1536         enum stasis_app_snoop_direction spy, whisper;
1537         RAII_VAR(struct ast_channel *, chan, NULL, ast_channel_cleanup);
1538         RAII_VAR(struct ast_channel *, snoop, NULL, ast_channel_cleanup);
1539         RAII_VAR(struct ast_channel_snapshot *, snapshot, NULL, ao2_cleanup);
1540
1541         ast_assert(response != NULL);
1542
1543         if (ast_strlen_zero(args_spy) || !strcmp(args_spy, "none")) {
1544                 spy = STASIS_SNOOP_DIRECTION_NONE;
1545         } else if (!strcmp(args_spy, "both")) {
1546                 spy = STASIS_SNOOP_DIRECTION_BOTH;
1547         } else if (!strcmp(args_spy, "out")) {
1548                 spy = STASIS_SNOOP_DIRECTION_OUT;
1549         } else if (!strcmp(args_spy, "in")) {
1550                 spy = STASIS_SNOOP_DIRECTION_IN;
1551         } else {
1552                 ast_ari_response_error(
1553                         response, 400, "Bad Request",
1554                         "Invalid direction specified for spy");
1555                 return;
1556         }
1557
1558         if (ast_strlen_zero(args_whisper) || !strcmp(args_whisper, "none")) {
1559                 whisper = STASIS_SNOOP_DIRECTION_NONE;
1560         } else if (!strcmp(args_whisper, "both")) {
1561                 whisper = STASIS_SNOOP_DIRECTION_BOTH;
1562         } else if (!strcmp(args_whisper, "out")) {
1563                 whisper = STASIS_SNOOP_DIRECTION_OUT;
1564         } else if (!strcmp(args_whisper, "in")) {
1565                 whisper = STASIS_SNOOP_DIRECTION_IN;
1566         } else {
1567                 ast_ari_response_error(
1568                         response, 400, "Bad Request",
1569                         "Invalid direction specified for whisper");
1570                 return;
1571         }
1572
1573         if (spy == STASIS_SNOOP_DIRECTION_NONE && whisper == STASIS_SNOOP_DIRECTION_NONE) {
1574                 ast_ari_response_error(
1575                         response, 400, "Bad Request",
1576                         "Direction must be specified for at least spy or whisper");
1577                 return;
1578         } else if (ast_strlen_zero(args_app)) {
1579                 ast_ari_response_error(
1580                         response, 400, "Bad Request",
1581                         "Application name is required");
1582                 return;
1583         }
1584
1585         chan = ast_channel_get_by_name(args_channel_id);
1586         if (chan == NULL) {
1587                 ast_ari_response_error(
1588                         response, 404, "Channel Not Found",
1589                         "Provided channel was not found");
1590                 return;
1591         }
1592
1593         snoop = stasis_app_control_snoop(chan, spy, whisper, args_app, args_app_args,
1594                 args_snoop_id);
1595         if (snoop == NULL) {
1596                 ast_ari_response_error(
1597                         response, 500, "Internal error",
1598                         "Snoop channel could not be created");
1599                 return;
1600         }
1601
1602         snapshot = ast_channel_snapshot_get_latest(ast_channel_uniqueid(snoop));
1603         ast_ari_response_ok(response, ast_channel_snapshot_to_json(snapshot, NULL));
1604 }
1605
1606 void ast_ari_channels_snoop_channel(struct ast_variable *headers,
1607         struct ast_ari_channels_snoop_channel_args *args,
1608         struct ast_ari_response *response)
1609 {
1610         ari_channels_handle_snoop_channel(
1611                 args->channel_id,
1612                 args->spy,
1613                 args->whisper,
1614                 args->app,
1615                 args->app_args,
1616                 args->snoop_id,
1617                 response);
1618 }
1619
1620 void ast_ari_channels_snoop_channel_with_id(struct ast_variable *headers,
1621         struct ast_ari_channels_snoop_channel_with_id_args *args,
1622         struct ast_ari_response *response)
1623 {
1624         ari_channels_handle_snoop_channel(
1625                 args->channel_id,
1626                 args->spy,
1627                 args->whisper,
1628                 args->app,
1629                 args->app_args,
1630                 args->snoop_id,
1631                 response);
1632 }
1633
1634 struct ari_channel_thread_data {
1635         struct ast_channel *chan;
1636         struct ast_str *stasis_stuff;
1637 };
1638
1639 static void chan_data_destroy(struct ari_channel_thread_data *chan_data)
1640 {
1641         ast_free(chan_data->stasis_stuff);
1642         ast_hangup(chan_data->chan);
1643         ast_free(chan_data);
1644 }
1645
1646 /*!
1647  * \brief Thread that owns stasis-created channel.
1648  *
1649  * The channel enters into a Stasis application immediately upon creation. In this
1650  * way, the channel can be manipulated by the Stasis application. Once the channel
1651  * exits the Stasis application, it is hung up.
1652  */
1653 static void *ari_channel_thread(void *data)
1654 {
1655         struct ari_channel_thread_data *chan_data = data;
1656         struct ast_app *stasis_app;
1657
1658         stasis_app = pbx_findapp("Stasis");
1659         if (!stasis_app) {
1660                 ast_log(LOG_ERROR, "Stasis dialplan application is not registered");
1661                 chan_data_destroy(chan_data);
1662                 return NULL;
1663         }
1664
1665         pbx_exec(chan_data->chan, stasis_app, ast_str_buffer(chan_data->stasis_stuff));
1666
1667         chan_data_destroy(chan_data);
1668
1669         return NULL;
1670 }
1671
1672 struct ast_datastore_info dialstring_info = {
1673         .type = "ARI Dialstring",
1674         .destroy = ast_free_ptr,
1675 };
1676
1677 /*!
1678  * \brief Save dialstring onto a channel datastore
1679  *
1680  * This will later be retrieved when it comes time to actually dial the channel
1681  *
1682  * \param chan The channel on which to save the dialstring
1683  * \param dialstring The dialstring to save
1684  * \retval 0 SUCCESS!
1685  * \reval -1 Failure :(
1686  */
1687 static int save_dialstring(struct ast_channel *chan, const char *dialstring)
1688 {
1689         struct ast_datastore *datastore;
1690
1691         datastore = ast_datastore_alloc(&dialstring_info, NULL);
1692         if (!datastore) {
1693                 return -1;
1694         }
1695
1696         datastore->data = ast_strdup(dialstring);
1697         if (!datastore->data) {
1698                 ast_datastore_free(datastore);
1699                 return -1;
1700         }
1701
1702         ast_channel_lock(chan);
1703         if (ast_channel_datastore_add(chan, datastore)) {
1704                 ast_channel_unlock(chan);
1705                 ast_datastore_free(datastore);
1706                 return -1;
1707         }
1708         ast_channel_unlock(chan);
1709
1710         return 0;
1711 }
1712
1713 /*!
1714  * \brief Retrieve the dialstring from the channel datastore
1715  *
1716  * \pre chan is locked
1717  * \param chan Channel that was previously created in ARI
1718  * \retval NULL Failed to find datastore
1719  * \retval non-NULL The dialstring
1720  */
1721 static char *restore_dialstring(struct ast_channel *chan)
1722 {
1723         struct ast_datastore *datastore;
1724
1725         datastore = ast_channel_datastore_find(chan, &dialstring_info, NULL);
1726         if (!datastore) {
1727                 return NULL;
1728         }
1729
1730         return datastore->data;
1731 }
1732
1733 void ast_ari_channels_create(struct ast_variable *headers,
1734         struct ast_ari_channels_create_args *args,
1735         struct ast_ari_response *response)
1736 {
1737         struct ast_assigned_ids assignedids = {
1738                 .uniqueid = args->channel_id,
1739                 .uniqueid2 = args->other_channel_id,
1740         };
1741         struct ari_channel_thread_data *chan_data;
1742         struct ast_channel_snapshot *snapshot;
1743         pthread_t thread;
1744         char *dialtech;
1745         char dialdevice[AST_CHANNEL_NAME];
1746         char *stuff;
1747         int cause;
1748         struct ast_format_cap *request_cap;
1749         struct ast_channel *originator;
1750
1751         if (!ast_strlen_zero(args->originator) && !ast_strlen_zero(args->formats)) {
1752                 ast_ari_response_error(response, 400, "Bad Request",
1753                         "Originator and formats can't both be specified");
1754                 return;
1755         }
1756
1757         if (ast_strlen_zero(args->endpoint)) {
1758                 ast_ari_response_error(response, 400, "Bad Request",
1759                         "Endpoint must be specified");
1760                 return;
1761         }
1762
1763         chan_data = ast_calloc(1, sizeof(*chan_data));
1764         if (!chan_data) {
1765                 ast_ari_response_alloc_failed(response);
1766                 return;
1767         }
1768
1769         chan_data->stasis_stuff = ast_str_create(32);
1770         if (!chan_data->stasis_stuff) {
1771                 ast_ari_response_alloc_failed(response);
1772                 chan_data_destroy(chan_data);
1773                 return;
1774         }
1775
1776         ast_str_append(&chan_data->stasis_stuff, 0, "%s", args->app);
1777         if (!ast_strlen_zero(args->app_args)) {
1778                 ast_str_append(&chan_data->stasis_stuff, 0, ",%s", args->app_args);
1779         }
1780
1781         dialtech = ast_strdupa(args->endpoint);
1782         if ((stuff = strchr(dialtech, '/'))) {
1783                 *stuff++ = '\0';
1784                 ast_copy_string(dialdevice, stuff, sizeof(dialdevice));
1785         }
1786
1787         originator = ast_channel_get_by_name(args->originator);
1788         if (originator) {
1789                 request_cap = ao2_bump(ast_channel_nativeformats(originator));
1790                 if (!ast_strlen_zero(args->app)) {
1791                         stasis_app_subscribe_channel(args->app, originator);
1792                 }
1793         } else if (!ast_strlen_zero(args->formats)) {
1794                 char *format_name;
1795                 char *formats_copy = ast_strdupa(args->formats);
1796
1797                 if (!(request_cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
1798                         ast_ari_response_alloc_failed(response);
1799                         chan_data_destroy(chan_data);
1800                         return;
1801                 }
1802
1803                 while ((format_name = ast_strip(strsep(&formats_copy, ",")))) {
1804                         struct ast_format *fmt = ast_format_cache_get(format_name);
1805
1806                         if (!fmt || ast_format_cap_append(request_cap, fmt, 0)) {
1807                                 if (!fmt) {
1808                                         ast_ari_response_error(
1809                                                 response, 400, "Bad Request",
1810                                                 "Provided format (%s) was not found", format_name);
1811                                 } else {
1812                                         ast_ari_response_alloc_failed(response);
1813                                 }
1814                                 ao2_ref(request_cap, -1);
1815                                 ao2_cleanup(fmt);
1816                                 chan_data_destroy(chan_data);
1817                                 return;
1818                         }
1819                         ao2_ref(fmt, -1);
1820                 }
1821         } else {
1822                 if (!(request_cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
1823                         ast_ari_response_alloc_failed(response);
1824                         chan_data_destroy(chan_data);
1825                         return;
1826                 }
1827
1828                 ast_format_cap_append_by_type(request_cap, AST_MEDIA_TYPE_AUDIO);
1829         }
1830
1831         chan_data->chan = ast_request(dialtech, request_cap, &assignedids, originator, dialdevice, &cause);
1832         ao2_cleanup(request_cap);
1833
1834         if (!chan_data->chan) {
1835                 if (ast_channel_errno() == AST_CHANNEL_ERROR_ID_EXISTS) {
1836                         ast_ari_response_error(response, 409, "Conflict",
1837                                 "Channel with given unique ID already exists");
1838                 } else {
1839                         ast_ari_response_alloc_failed(response);
1840                 }
1841                 ast_channel_cleanup(originator);
1842                 chan_data_destroy(chan_data);
1843                 return;
1844         }
1845
1846         if (!ast_strlen_zero(args->app)) {
1847                 stasis_app_subscribe_channel(args->app, chan_data->chan);
1848         }
1849
1850         ast_channel_cleanup(originator);
1851
1852         if (save_dialstring(chan_data->chan, stuff)) {
1853                 ast_ari_response_alloc_failed(response);
1854                 chan_data_destroy(chan_data);
1855                 return;
1856         }
1857
1858         snapshot = ast_channel_snapshot_get_latest(ast_channel_uniqueid(chan_data->chan));
1859
1860         if (ast_pthread_create_detached(&thread, NULL, ari_channel_thread, chan_data)) {
1861                 ast_ari_response_alloc_failed(response);
1862                 chan_data_destroy(chan_data);
1863         } else {
1864                 ast_ari_response_ok(response, ast_channel_snapshot_to_json(snapshot, NULL));
1865         }
1866
1867         ao2_ref(snapshot, -1);
1868 }
1869
1870 void ast_ari_channels_dial(struct ast_variable *headers,
1871         struct ast_ari_channels_dial_args *args,
1872         struct ast_ari_response *response)
1873 {
1874         RAII_VAR(struct stasis_app_control *, control, NULL, ao2_cleanup);
1875         RAII_VAR(struct ast_channel *, caller, NULL, ast_channel_cleanup);
1876         RAII_VAR(struct ast_channel *, callee, NULL, ast_channel_cleanup);
1877         char *dialstring;
1878
1879         control = find_control(response, args->channel_id);
1880         if (control == NULL) {
1881                 /* Response filled in by find_control */
1882                 return;
1883         }
1884
1885         caller = ast_channel_get_by_name(args->caller);
1886
1887         callee = ast_channel_get_by_name(args->channel_id);
1888         if (!callee) {
1889                 ast_ari_response_error(response, 404, "Not Found",
1890                         "Callee not found");
1891                 return;
1892         }
1893
1894         if (ast_channel_state(callee) != AST_STATE_DOWN
1895                 && ast_channel_state(callee) != AST_STATE_RESERVED) {
1896                 ast_ari_response_error(response, 409, "Conflict",
1897                         "Channel is not in the 'Down' state");
1898                 return;
1899         }
1900
1901         /* XXX This is straight up copied from main/dial.c. It's probably good
1902          * to separate this to some common method.
1903          */
1904         if (caller) {
1905                 ast_channel_lock_both(caller, callee);
1906         } else {
1907                 ast_channel_lock(callee);
1908         }
1909
1910         dialstring = restore_dialstring(callee);
1911         if (!dialstring) {
1912                 ast_channel_unlock(callee);
1913                 if (caller) {
1914                         ast_channel_unlock(caller);
1915                 }
1916                 ast_ari_response_error(response, 409, "Conflict",
1917                         "Dialing a channel not created by ARI");
1918                 return;
1919         }
1920         /* Make a copy of the dialstring just in case some jerk tries to hang up the
1921          * channel before we can actually dial
1922          */
1923         dialstring = ast_strdupa(dialstring);
1924
1925         ast_channel_stage_snapshot(callee);
1926         if (caller) {
1927                 ast_channel_inherit_variables(caller, callee);
1928                 ast_channel_datastore_inherit(caller, callee);
1929                 ast_max_forwards_decrement(callee);
1930
1931                 /* Copy over callerid information */
1932                 ast_party_redirecting_copy(ast_channel_redirecting(callee), ast_channel_redirecting(caller));
1933
1934                 ast_channel_dialed(callee)->transit_network_select = ast_channel_dialed(caller)->transit_network_select;
1935
1936                 ast_connected_line_copy_from_caller(ast_channel_connected(callee), ast_channel_caller(caller));
1937
1938                 ast_channel_language_set(callee, ast_channel_language(caller));
1939                 ast_channel_req_accountcodes(callee, caller, AST_CHANNEL_REQUESTOR_BRIDGE_PEER);
1940                 if (ast_strlen_zero(ast_channel_musicclass(callee)))
1941                         ast_channel_musicclass_set(callee, ast_channel_musicclass(caller));
1942
1943                 ast_channel_adsicpe_set(callee, ast_channel_adsicpe(caller));
1944                 ast_channel_transfercapability_set(callee, ast_channel_transfercapability(caller));
1945                 ast_channel_unlock(caller);
1946         }
1947
1948         ast_channel_stage_snapshot_done(callee);
1949         ast_channel_unlock(callee);
1950
1951         if (stasis_app_control_dial(control, dialstring, args->timeout)) {
1952                 ast_ari_response_alloc_failed(response);
1953                 return;
1954         }
1955
1956         ast_ari_response_no_content(response);
1957 }