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