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