ARI: Add the ability to intercept hold and raise an event
[asterisk/asterisk.git] / main / manager_channels.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 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 The Asterisk Management Interface - AMI (channel event handling)
22  *
23  * \author David M. Lee, II <dlee@digium.com>
24  *
25  * AMI generated many per-channel and global-channel events by converting Stasis
26  * messages to AMI events. It makes sense to simply put them into a single file.
27  */
28
29 #include "asterisk.h"
30
31 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
32
33 #include "asterisk/callerid.h"
34 #include "asterisk/channel.h"
35 #include "asterisk/manager.h"
36 #include "asterisk/stasis_message_router.h"
37 #include "asterisk/pbx.h"
38 #include "asterisk/stasis_channels.h"
39
40 /*** DOCUMENTATION
41         <managerEvent language="en_US" name="Newchannel">
42                 <managerEventInstance class="EVENT_FLAG_CALL">
43                         <synopsis>Raised when a new channel is created.</synopsis>
44                         <syntax>
45                                 <channel_snapshot/>
46                         </syntax>
47                 </managerEventInstance>
48         </managerEvent>
49         <managerEvent language="en_US" name="Newstate">
50                 <managerEventInstance class="EVENT_FLAG_CALL">
51                         <synopsis>Raised when a channel's state changes.</synopsis>
52                         <syntax>
53                                 <channel_snapshot/>
54                         </syntax>
55                 </managerEventInstance>
56         </managerEvent>
57         <managerEvent language="en_US" name="Hangup">
58                 <managerEventInstance class="EVENT_FLAG_CALL">
59                         <synopsis>Raised when a channel is hung up.</synopsis>
60                         <syntax>
61                                 <channel_snapshot/>
62                                 <parameter name="Cause">
63                                         <para>A numeric cause code for why the channel was hung up.</para>
64                                 </parameter>
65                                 <parameter name="Cause-txt">
66                                         <para>A description of why the channel was hung up.</para>
67                                 </parameter>
68                         </syntax>
69                 </managerEventInstance>
70         </managerEvent>
71         <managerEvent language="en_US" name="HangupRequest">
72                 <managerEventInstance class="EVENT_FLAG_CALL">
73                         <synopsis>Raised when a hangup is requested.</synopsis>
74                         <syntax>
75                                 <channel_snapshot/>
76                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='Hangup']/managerEventInstance/syntax/parameter[@name='Cause'])" />
77                         </syntax>
78                 </managerEventInstance>
79         </managerEvent>
80         <managerEvent language="en_US" name="SoftHangupRequest">
81                 <managerEventInstance class="EVENT_FLAG_CALL">
82                         <synopsis>Raised when a soft hangup is requested with a specific cause code.</synopsis>
83                         <syntax>
84                                 <channel_snapshot/>
85                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='Hangup']/managerEventInstance/syntax/parameter[@name='Cause'])" />
86                         </syntax>
87                 </managerEventInstance>
88         </managerEvent>
89         <managerEvent language="en_US" name="NewExten">
90                 <managerEventInstance class="EVENT_FLAG_DIALPLAN">
91                         <synopsis>Raised when a channel enters a new context, extension, priority.</synopsis>
92                         <syntax>
93                                 <channel_snapshot/>
94                                 <parameter name="Extension">
95                                         <para>Deprecated in 12, but kept for
96                                         backward compatability. Please use
97                                         'Exten' instead.</para>
98                                 </parameter>
99                                 <parameter name="Application">
100                                         <para>The application about to be executed.</para>
101                                 </parameter>
102                                 <parameter name="AppData">
103                                         <para>The data to be passed to the application.</para>
104                                 </parameter>
105                         </syntax>
106                 </managerEventInstance>
107         </managerEvent>
108         <managerEvent language="en_US" name="NewCallerid">
109                 <managerEventInstance class="EVENT_FLAG_CALL">
110                         <synopsis>Raised when a channel receives new Caller ID information.</synopsis>
111                         <syntax>
112                                 <channel_snapshot/>
113                                 <parameter name="CID-CallingPres">
114                                         <para>A description of the Caller ID presentation.</para>
115                                 </parameter>
116                         </syntax>
117                 </managerEventInstance>
118         </managerEvent>
119         <managerEvent language="en_US" name="NewAccountCode">
120                 <managerEventInstance class="EVENT_FLAG_CALL">
121                         <synopsis>Raised when a Channel's AccountCode is changed.</synopsis>
122                         <syntax>
123                                 <channel_snapshot/>
124                                 <parameter name="OldAccountCode">
125                                         <para>The channel's previous account code</para>
126                                 </parameter>
127                         </syntax>
128                 </managerEventInstance>
129         </managerEvent>
130         <managerEvent language="en_US" name="DialBegin">
131                 <managerEventInstance class="EVENT_FLAG_CALL">
132                         <synopsis>Raised when a dial action has started.</synopsis>
133                         <syntax>
134                                 <channel_snapshot/>
135                                 <channel_snapshot prefix="Dest"/>
136                                 <parameter name="DialString">
137                                         <para>The non-technology specific device being dialed.</para>
138                                 </parameter>
139                         </syntax>
140                         <see-also>
141                                 <ref type="application">Dial</ref>
142                         </see-also>
143                 </managerEventInstance>
144         </managerEvent>
145         <managerEvent language="en_US" name="DialEnd">
146                 <managerEventInstance class="EVENT_FLAG_CALL">
147                         <synopsis>Raised when a dial action has completed.</synopsis>
148                         <syntax>
149                                 <channel_snapshot/>
150                                 <channel_snapshot prefix="Dest"/>
151                                 <parameter name="DialStatus">
152                                         <para>The result of the dial operation.</para>
153                                         <enumlist>
154                                                 <enum name="ABORT">
155                                                         <para>The call was aborted.</para>
156                                                 </enum>
157                                                 <enum name="ANSWER">
158                                                         <para>The caller answered.</para>
159                                                 </enum>
160                                                 <enum name="BUSY">
161                                                         <para>The caller was busy.</para>
162                                                 </enum>
163                                                 <enum name="CANCEL">
164                                                         <para>The caller cancelled the call.</para>
165                                                 </enum>
166                                                 <enum name="CHANUNAVAIL">
167                                                         <para>The requested channel is unavailable.</para>
168                                                 </enum>
169                                                 <enum name="CONGESTION">
170                                                         <para>The called party is congested.</para>
171                                                 </enum>
172                                                 <enum name="CONTINUE">
173                                                         <para>The dial completed, but the caller elected
174                                                         to continue in the dialplan.</para>
175                                                 </enum>
176                                                 <enum name="GOTO">
177                                                         <para>The dial completed, but the caller jumped to
178                                                         a dialplan location.</para>
179                                                         <para>If known, the location the caller is jumping
180                                                         to will be appended to the result following a
181                                                         ":".</para>
182                                                 </enum>
183                                                 <enum name="NOANSWER">
184                                                         <para>The called party failed to answer.</para>
185                                                 </enum>
186                                         </enumlist>
187                                 </parameter>
188                                 <parameter name="Forward" required="false">
189                                         <para>If the call was forwarded, where the call was
190                                         forwarded to.</para>
191                                 </parameter>
192                         </syntax>
193                         <see-also>
194                                 <ref type="application">Dial</ref>
195                         </see-also>
196                 </managerEventInstance>
197         </managerEvent>
198         <managerEvent language="en_US" name="Hold">
199                 <managerEventInstance class="EVENT_FLAG_CALL">
200                         <synopsis>Raised when a channel goes on hold.</synopsis>
201                         <syntax>
202                                 <channel_snapshot/>
203                                 <parameter name="MusicClass">
204                                         <para>The suggested MusicClass, if provided.</para>
205                                 </parameter>
206                         </syntax>
207                 </managerEventInstance>
208         </managerEvent>
209         <managerEvent language="en_US" name="Unhold">
210                 <managerEventInstance class="EVENT_FLAG_CALL">
211                         <synopsis>Raised when a channel goes off hold.</synopsis>
212                         <syntax>
213                                 <channel_snapshot/>
214                         </syntax>
215                 </managerEventInstance>
216         </managerEvent>
217         <managerEvent language="en_US" name="ChanSpyStart">
218                 <managerEventInstance class="EVENT_FLAG_CALL">
219                         <synopsis>Raised when one channel begins spying on another channel.</synopsis>
220                         <syntax>
221                                 <channel_snapshot prefix="Spyer"/>
222                                 <channel_snapshot prefix="Spyee"/>
223                         </syntax>
224                         <see-also>
225                                 <ref type="application">ChanSpyStop</ref>
226                         </see-also>
227                 </managerEventInstance>
228         </managerEvent>
229         <managerEvent language="en_US" name="ChanSpyStop">
230                 <managerEventInstance class="EVENT_FLAG_CALL">
231                         <synopsis>Raised when a channel has stopped spying.</synopsis>
232                         <syntax>
233                                 <channel_snapshot prefix="Spyer"/>
234                                 <channel_snapshot prefix="Spyee"/>
235                         </syntax>
236                         <see-also>
237                                 <ref type="application">ChanSpyStart</ref>
238                         </see-also>
239                 </managerEventInstance>
240         </managerEvent>
241         <managerEvent language="en_US" name="HangupHandlerRun">
242                 <managerEventInstance class="EVENT_FLAG_DIALPLAN">
243                         <synopsis>Raised when a hangup handler is about to be called.</synopsis>
244                         <syntax>
245                                 <channel_snapshot/>
246                                 <parameter name="Handler">
247                                         <para>Hangup handler parameter string passed to the Gosub application.</para>
248                                 </parameter>
249                         </syntax>
250                 </managerEventInstance>
251         </managerEvent>
252         <managerEvent language="en_US" name="HangupHandlerPop">
253                 <managerEventInstance class="EVENT_FLAG_DIALPLAN">
254                         <synopsis>
255                                 Raised when a hangup handler is removed from the handler stack
256                                 by the CHANNEL() function.
257                         </synopsis>
258                         <syntax>
259                                 <channel_snapshot/>
260                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='HangupHandlerRun']/managerEventInstance/syntax/parameter)" />
261                         </syntax>
262                         <see-also>
263                                 <ref type="managerEvent">HangupHandlerPush</ref>
264                                 <ref type="function">CHANNEL</ref>
265                         </see-also>
266                 </managerEventInstance>
267         </managerEvent>
268         <managerEvent language="en_US" name="HangupHandlerPush">
269                 <managerEventInstance class="EVENT_FLAG_DIALPLAN">
270                         <synopsis>
271                                 Raised when a hangup handler is added to the handler stack by
272                                 the CHANNEL() function.
273                         </synopsis>
274                         <syntax>
275                                 <channel_snapshot/>
276                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='HangupHandlerRun']/managerEventInstance/syntax/parameter)" />
277                         </syntax>
278                         <see-also>
279                                 <ref type="managerEvent">HangupHandlerPop</ref>
280                                 <ref type="function">CHANNEL</ref>
281                         </see-also>
282                 </managerEventInstance>
283         </managerEvent>
284         <managerEvent language="en_US" name="FAXStatus">
285                 <managerEventInstance class="EVENT_FLAG_CALL">
286                         <synopsis>
287                                 Raised periodically during a fax transmission.
288                         </synopsis>
289                         <syntax>
290                                 <channel_snapshot/>
291                                 <parameter name="Operation">
292                                         <enumlist>
293                                                 <enum name="gateway"/>
294                                                 <enum name="receive"/>
295                                                 <enum name="send"/>
296                                         </enumlist>
297                                 </parameter>
298                                 <parameter name="Status">
299                                         <para>A text message describing the current status of the fax</para>
300                                 </parameter>
301                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='ReceiveFAX']/managerEventInstance/syntax/parameter[@name='LocalStationID'])" />
302                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='ReceiveFAX']/managerEventInstance/syntax/parameter[@name='FileName'])" />
303                         </syntax>
304                 </managerEventInstance>
305         </managerEvent>
306         <managerEvent language="en_US" name="ReceiveFAX">
307                 <managerEventInstance class="EVENT_FLAG_CALL">
308                         <synopsis>
309                                 Raised when a receive fax operation has completed.
310                         </synopsis>
311                         <syntax>
312                                 <channel_snapshot/>
313                                 <parameter name="LocalStationID">
314                                         <para>The value of the <variable>LOCALSTATIONID</variable> channel variable</para>
315                                 </parameter>
316                                 <parameter name="RemoteStationID">
317                                         <para>The value of the <variable>REMOTESTATIONID</variable> channel variable</para>
318                                 </parameter>
319                                 <parameter name="PagesTransferred">
320                                         <para>The number of pages that have been transferred</para>
321                                 </parameter>
322                                 <parameter name="Resolution">
323                                         <para>The negotiated resolution</para>
324                                 </parameter>
325                                 <parameter name="TransferRate">
326                                         <para>The negotiated transfer rate</para>
327                                 </parameter>
328                                 <parameter name="FileName" multiple="yes">
329                                         <para>The files being affected by the fax operation</para>
330                                 </parameter>
331                         </syntax>
332                 </managerEventInstance>
333         </managerEvent>
334         <managerEvent language="en_US" name="SendFAX">
335                 <managerEventInstance class="EVENT_FLAG_CALL">
336                         <synopsis>
337                                 Raised when a send fax operation has completed.
338                         </synopsis>
339                         <syntax>
340                                 <channel_snapshot/>
341                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='ReceiveFAX']/managerEventInstance/syntax/parameter)" />
342                         </syntax>
343                 </managerEventInstance>
344         </managerEvent>
345         <managerEvent language="en_US" name="MusicOnHoldStart">
346                 <managerEventInstance class="EVENT_FLAG_CALL">
347                         <synopsis>Raised when music on hold has started on a channel.</synopsis>
348                         <syntax>
349                                 <channel_snapshot/>
350                                 <parameter name="Class">
351                                         <para>The class of music being played on the channel</para>
352                                 </parameter>
353                         </syntax>
354                         <see-also>
355                                 <ref type="managerEvent">MusicOnHoldStop</ref>
356                                 <ref type="application">MusicOnHold</ref>
357                         </see-also>
358                 </managerEventInstance>
359         </managerEvent>
360         <managerEvent language="en_US" name="MusicOnHoldStop">
361                 <managerEventInstance class="EVENT_FLAG_CALL">
362                         <synopsis>Raised when music on hold has stopped on a channel.</synopsis>
363                         <syntax>
364                                 <channel_snapshot/>
365                         </syntax>
366                         <see-also>
367                                 <ref type="managerEvent">MusicOnHoldStart</ref>
368                                 <ref type="application">StopMusicOnHold</ref>
369                         </see-also>
370                 </managerEventInstance>
371         </managerEvent>
372         <managerEvent language="en_US" name="MonitorStart">
373                 <managerEventInstance class="EVENT_FLAG_CALL">
374                         <synopsis>Raised when monitoring has started on a channel.</synopsis>
375                         <syntax>
376                                 <channel_snapshot/>
377                         </syntax>
378                         <see-also>
379                                 <ref type="managerEvent">MonitorStop</ref>
380                                 <ref type="application">Monitor</ref>
381                                 <ref type="manager">Monitor</ref>
382                         </see-also>
383                 </managerEventInstance>
384         </managerEvent>
385         <managerEvent language="en_US" name="MonitorStop">
386                 <managerEventInstance class="EVENT_FLAG_CALL">
387                 <synopsis>Raised when monitoring has stopped on a channel.</synopsis>
388                 <syntax>
389                         <channel_snapshot/>
390                 </syntax>
391                 <see-also>
392                         <ref type="managerEvent">MonitorStart</ref>
393                         <ref type="application">StopMonitor</ref>
394                         <ref type="manager">StopMonitor</ref>
395                 </see-also>
396                 </managerEventInstance>
397         </managerEvent>
398 ***/
399
400 /*! \brief The \ref stasis subscription returned by the forwarding of the channel topic
401  * to the manager topic
402  */
403 static struct stasis_forward *topic_forwarder;
404
405 struct ast_str *ast_manager_build_channel_state_string_prefix(
406                 const struct ast_channel_snapshot *snapshot,
407                 const char *prefix)
408 {
409         struct ast_str *out = ast_str_create(1024);
410         int res = 0;
411
412         if (!out) {
413                 return NULL;
414         }
415
416         if (snapshot->tech_properties & AST_CHAN_TP_INTERNAL) {
417                 ast_free(out);
418                 return NULL;
419         }
420
421         res = ast_str_set(&out, 0,
422                 "%sChannel: %s\r\n"
423                 "%sChannelState: %u\r\n"
424                 "%sChannelStateDesc: %s\r\n"
425                 "%sCallerIDNum: %s\r\n"
426                 "%sCallerIDName: %s\r\n"
427                 "%sConnectedLineNum: %s\r\n"
428                 "%sConnectedLineName: %s\r\n"
429                 "%sLanguage: %s\r\n"
430                 "%sAccountCode: %s\r\n"
431                 "%sContext: %s\r\n"
432                 "%sExten: %s\r\n"
433                 "%sPriority: %d\r\n"
434                 "%sUniqueid: %s\r\n",
435                 prefix, snapshot->name,
436                 prefix, snapshot->state,
437                 prefix, ast_state2str(snapshot->state),
438                 prefix, S_OR(snapshot->caller_number, "<unknown>"),
439                 prefix, S_OR(snapshot->caller_name, "<unknown>"),
440                 prefix, S_OR(snapshot->connected_number, "<unknown>"),
441                 prefix, S_OR(snapshot->connected_name, "<unknown>"),
442                 prefix, snapshot->language,
443                 prefix, snapshot->accountcode,
444                 prefix, snapshot->context,
445                 prefix, snapshot->exten,
446                 prefix, snapshot->priority,
447                 prefix, snapshot->uniqueid);
448
449         if (!res) {
450                 ast_free(out);
451                 return NULL;
452         }
453
454         if (snapshot->manager_vars) {
455                 struct ast_var_t *var;
456                 AST_LIST_TRAVERSE(snapshot->manager_vars, var, entries) {
457                         ast_str_append(&out, 0, "%sChanVariable: %s=%s\r\n",
458                                        prefix,
459                                        var->name, var->value);
460                 }
461         }
462
463         return out;
464 }
465
466 struct ast_str *ast_manager_build_channel_state_string(
467                 const struct ast_channel_snapshot *snapshot)
468 {
469         return ast_manager_build_channel_state_string_prefix(snapshot, "");
470 }
471
472 /*! \brief Typedef for callbacks that get called on channel snapshot updates */
473 typedef struct ast_manager_event_blob *(*channel_snapshot_monitor)(
474         struct ast_channel_snapshot *old_snapshot,
475         struct ast_channel_snapshot *new_snapshot);
476
477 /*! \brief Handle channel state changes */
478 static struct ast_manager_event_blob *channel_state_change(
479         struct ast_channel_snapshot *old_snapshot,
480         struct ast_channel_snapshot *new_snapshot)
481 {
482         int is_hungup, was_hungup;
483
484         if (!new_snapshot) {
485                 /* Ignore cache clearing events; we'll see the hangup first */
486                 return NULL;
487         }
488
489         /* The Newchannel, Newstate and Hangup events are closely related, in
490          * in that they are mutually exclusive, basically different flavors
491          * of a new channel state event.
492          */
493
494         if (!old_snapshot) {
495                 return ast_manager_event_blob_create(
496                         EVENT_FLAG_CALL, "Newchannel", NO_EXTRA_FIELDS);
497         }
498
499         was_hungup = ast_test_flag(&old_snapshot->flags, AST_FLAG_DEAD) ? 1 : 0;
500         is_hungup = ast_test_flag(&new_snapshot->flags, AST_FLAG_DEAD) ? 1 : 0;
501
502         if (!was_hungup && is_hungup) {
503                 return ast_manager_event_blob_create(
504                         EVENT_FLAG_CALL, "Hangup",
505                         "Cause: %d\r\n"
506                         "Cause-txt: %s\r\n",
507                         new_snapshot->hangupcause,
508                         ast_cause2str(new_snapshot->hangupcause));
509         }
510
511         if (old_snapshot->state != new_snapshot->state) {
512                 return ast_manager_event_blob_create(
513                         EVENT_FLAG_CALL, "Newstate", NO_EXTRA_FIELDS);
514         }
515
516         /* No event */
517         return NULL;
518 }
519
520 static struct ast_manager_event_blob *channel_newexten(
521         struct ast_channel_snapshot *old_snapshot,
522         struct ast_channel_snapshot *new_snapshot)
523 {
524         /* No Newexten event on cache clear */
525         if (!new_snapshot) {
526                 return NULL;
527         }
528
529         /* Empty application is not valid for a Newexten event */
530         if (ast_strlen_zero(new_snapshot->appl)) {
531                 return NULL;
532         }
533
534         /* Ignore any updates if we're hungup */
535         if (ast_test_flag(&new_snapshot->flags, AST_FLAG_DEAD)) {
536                 return NULL;
537         }
538
539         /* Ignore updates if the CEP is unchanged */
540         if (old_snapshot && ast_channel_snapshot_cep_equal(old_snapshot, new_snapshot)) {
541                 return NULL;
542         }
543
544         /* DEPRECATED: Extension field deprecated in 12; remove in 14 */
545         return ast_manager_event_blob_create(
546                 EVENT_FLAG_CALL, "Newexten",
547                 "Extension: %s\r\n"
548                 "Application: %s\r\n"
549                 "AppData: %s\r\n",
550                 new_snapshot->exten,
551                 new_snapshot->appl,
552                 new_snapshot->data);
553 }
554
555 static struct ast_manager_event_blob *channel_new_callerid(
556         struct ast_channel_snapshot *old_snapshot,
557         struct ast_channel_snapshot *new_snapshot)
558 {
559         /* No NewCallerid event on cache clear or first event */
560         if (!old_snapshot || !new_snapshot) {
561                 return NULL;
562         }
563
564         if (ast_channel_snapshot_caller_id_equal(old_snapshot, new_snapshot)) {
565                 return NULL;
566         }
567
568         return ast_manager_event_blob_create(
569                 EVENT_FLAG_CALL, "NewCallerid",
570                 "CID-CallingPres: %d (%s)\r\n",
571                 new_snapshot->caller_pres,
572                 ast_describe_caller_presentation(new_snapshot->caller_pres));
573 }
574
575 static struct ast_manager_event_blob *channel_new_connected_line(
576         struct ast_channel_snapshot *old_snapshot,
577         struct ast_channel_snapshot *new_snapshot)
578 {
579         /* No NewConnectedLine event on cache clear or first event */
580         if (!old_snapshot || !new_snapshot) {
581                 return NULL;
582         }
583
584         if (ast_channel_snapshot_connected_line_equal(old_snapshot, new_snapshot)) {
585                 return NULL;
586         }
587
588         return ast_manager_event_blob_create(
589                 EVENT_FLAG_CALL, "NewConnectedLine", "%s", "");
590 }
591
592 static struct ast_manager_event_blob *channel_new_accountcode(
593         struct ast_channel_snapshot *old_snapshot,
594         struct ast_channel_snapshot *new_snapshot)
595 {
596         if (!old_snapshot || !new_snapshot) {
597                 return NULL;
598         }
599
600         if (!strcmp(old_snapshot->accountcode, new_snapshot->accountcode)) {
601                 return NULL;
602         }
603
604         return ast_manager_event_blob_create(
605                 EVENT_FLAG_CALL, "NewAccountCode",
606                 "OldAccountCode: %s\r\n", old_snapshot->accountcode);
607 }
608
609 channel_snapshot_monitor channel_monitors[] = {
610         channel_state_change,
611         channel_newexten,
612         channel_new_callerid,
613         channel_new_accountcode,
614         channel_new_connected_line,
615 };
616
617 static void channel_snapshot_update(void *data, struct stasis_subscription *sub,
618                                     struct stasis_message *message)
619 {
620         RAII_VAR(struct ast_str *, channel_event_string, NULL, ast_free);
621         struct stasis_cache_update *update;
622         struct ast_channel_snapshot *old_snapshot;
623         struct ast_channel_snapshot *new_snapshot;
624         size_t i;
625
626         update = stasis_message_data(message);
627
628         ast_assert(ast_channel_snapshot_type() == update->type);
629
630         old_snapshot = stasis_message_data(update->old_snapshot);
631         new_snapshot = stasis_message_data(update->new_snapshot);
632
633         for (i = 0; i < ARRAY_LEN(channel_monitors); ++i) {
634                 RAII_VAR(struct ast_manager_event_blob *, ev, NULL, ao2_cleanup);
635                 ev = channel_monitors[i](old_snapshot, new_snapshot);
636
637                 if (!ev) {
638                         continue;
639                 }
640
641                 /* If we haven't already, build the channel event string */
642                 if (!channel_event_string) {
643                         channel_event_string =
644                                 ast_manager_build_channel_state_string(new_snapshot);
645                         if (!channel_event_string) {
646                                 return;
647                         }
648                 }
649
650                 manager_event(ev->event_flags, ev->manager_event, "%s%s",
651                         ast_str_buffer(channel_event_string),
652                         ev->extra_fields);
653         }
654 }
655
656 static void publish_basic_channel_event(const char *event, int class, struct ast_channel_snapshot *snapshot)
657 {
658         RAII_VAR(struct ast_str *, channel_event_string, NULL, ast_free);
659
660         channel_event_string = ast_manager_build_channel_state_string(snapshot);
661         if (!channel_event_string) {
662                 return;
663         }
664
665         manager_event(class, event,
666                 "%s",
667                 ast_str_buffer(channel_event_string));
668 }
669
670 static void channel_hangup_request_cb(void *data,
671         struct stasis_subscription *sub,
672         struct stasis_message *message)
673 {
674         struct ast_channel_blob *obj = stasis_message_data(message);
675         RAII_VAR(struct ast_str *, extra, NULL, ast_free);
676         RAII_VAR(struct ast_str *, channel_event_string, NULL, ast_free);
677         struct ast_json *cause;
678         int is_soft;
679         char *manager_event = "HangupRequest";
680
681         extra = ast_str_create(20);
682         if (!extra) {
683                 return;
684         }
685
686         channel_event_string = ast_manager_build_channel_state_string(obj->snapshot);
687
688         if (!channel_event_string) {
689                 return;
690         }
691
692         cause = ast_json_object_get(obj->blob, "cause");
693         if (cause) {
694                 ast_str_append(&extra, 0,
695                                "Cause: %jd\r\n",
696                                ast_json_integer_get(cause));
697         }
698
699         is_soft = ast_json_is_true(ast_json_object_get(obj->blob, "soft"));
700         if (is_soft) {
701                 manager_event = "SoftHangupRequest";
702         }
703
704         manager_event(EVENT_FLAG_CALL, manager_event,
705                       "%s%s",
706                       ast_str_buffer(channel_event_string),
707                       ast_str_buffer(extra));
708 }
709
710 static void channel_chanspy_stop_cb(void *data, struct stasis_subscription *sub,
711                 struct stasis_message *message)
712 {
713         RAII_VAR(struct ast_str *, spyer_channel_string, NULL, ast_free);
714         struct ast_channel_snapshot *spyer;
715         struct ast_multi_channel_blob *payload = stasis_message_data(message);
716
717         spyer = ast_multi_channel_blob_get_channel(payload, "spyer_channel");
718         if (!spyer) {
719                 ast_log(AST_LOG_WARNING, "Received ChanSpy Start event with no spyer channel!\n");
720                 return;
721         }
722
723         spyer_channel_string = ast_manager_build_channel_state_string_prefix(spyer, "Spyer");
724         if (!spyer_channel_string) {
725                 return;
726         }
727
728         manager_event(EVENT_FLAG_CALL, "ChanSpyStop",
729                       "%s",
730                       ast_str_buffer(spyer_channel_string));
731 }
732
733 static void channel_chanspy_start_cb(void *data, struct stasis_subscription *sub,
734                 struct stasis_message *message)
735 {
736         RAII_VAR(struct ast_str *, spyer_channel_string, NULL, ast_free);
737         RAII_VAR(struct ast_str *, spyee_channel_string, NULL, ast_free);
738         struct ast_channel_snapshot *spyer;
739         struct ast_channel_snapshot *spyee;
740         struct ast_multi_channel_blob *payload = stasis_message_data(message);
741
742         spyer = ast_multi_channel_blob_get_channel(payload, "spyer_channel");
743         if (!spyer) {
744                 ast_log(AST_LOG_WARNING, "Received ChanSpy Start event with no spyer channel!\n");
745                 return;
746         }
747         spyee = ast_multi_channel_blob_get_channel(payload, "spyee_channel");
748         if (!spyee) {
749                 ast_log(AST_LOG_WARNING, "Received ChanSpy Start event with no spyee channel!\n");
750                 return;
751         }
752
753         spyer_channel_string = ast_manager_build_channel_state_string_prefix(spyer, "Spyer");
754         if (!spyer_channel_string) {
755                 return;
756         }
757         spyee_channel_string = ast_manager_build_channel_state_string_prefix(spyee, "Spyee");
758         if (!spyee_channel_string) {
759                 return;
760         }
761
762         manager_event(EVENT_FLAG_CALL, "ChanSpyStart",
763                       "%s%s",
764                       ast_str_buffer(spyer_channel_string),
765                       ast_str_buffer(spyee_channel_string));
766 }
767
768 static void channel_dtmf_begin_cb(void *data, struct stasis_subscription *sub,
769         struct stasis_message *message)
770 {
771         struct ast_channel_blob *obj = stasis_message_data(message);
772         RAII_VAR(struct ast_str *, channel_event_string, NULL, ast_free);
773         const char *digit =
774                 ast_json_string_get(ast_json_object_get(obj->blob, "digit"));
775         const char *direction =
776                 ast_json_string_get(ast_json_object_get(obj->blob, "direction"));
777
778         channel_event_string = ast_manager_build_channel_state_string(obj->snapshot);
779
780         if (!channel_event_string) {
781                 return;
782         }
783
784         /*** DOCUMENTATION
785                 <managerEventInstance>
786                         <synopsis>Raised when a DTMF digit has started on a channel.</synopsis>
787                                 <syntax>
788                                         <channel_snapshot/>
789                                         <parameter name="Digit">
790                                                 <para>DTMF digit received or transmitted (0-9, A-E, # or *</para>
791                                         </parameter>
792                                         <parameter name="Direction">
793                                                 <enumlist>
794                                                         <enum name="Received"/>
795                                                         <enum name="Sent"/>
796                                                 </enumlist>
797                                         </parameter>
798                                 </syntax>
799                 </managerEventInstance>
800         ***/
801         manager_event(EVENT_FLAG_DTMF, "DTMFBegin",
802                 "%s"
803                 "Digit: %s\r\n"
804                 "Direction: %s\r\n",
805                 ast_str_buffer(channel_event_string),
806                 digit, direction);
807 }
808
809 static void channel_dtmf_end_cb(void *data, struct stasis_subscription *sub,
810         struct stasis_message *message)
811 {
812         struct ast_channel_blob *obj = stasis_message_data(message);
813         RAII_VAR(struct ast_str *, channel_event_string, NULL, ast_free);
814         const char *digit =
815                 ast_json_string_get(ast_json_object_get(obj->blob, "digit"));
816         const char *direction =
817                 ast_json_string_get(ast_json_object_get(obj->blob, "direction"));
818         long duration_ms =
819                 ast_json_integer_get(ast_json_object_get(obj->blob, "duration_ms"));
820
821         channel_event_string = ast_manager_build_channel_state_string(obj->snapshot);
822
823         if (!channel_event_string) {
824                 return;
825         }
826
827         /*** DOCUMENTATION
828                 <managerEventInstance>
829                         <synopsis>Raised when a DTMF digit has ended on a channel.</synopsis>
830                                 <syntax>
831                                         <channel_snapshot/>
832                                         <parameter name="Digit">
833                                                 <para>DTMF digit received or transmitted (0-9, A-E, # or *</para>
834                                         </parameter>
835                                         <parameter name="DurationMs">
836                                                 <para>Duration (in milliseconds) DTMF was sent/received</para>
837                                         </parameter>
838                                         <parameter name="Direction">
839                                                 <enumlist>
840                                                         <enum name="Received"/>
841                                                         <enum name="Sent"/>
842                                                 </enumlist>
843                                         </parameter>
844                                 </syntax>
845                 </managerEventInstance>
846         ***/
847         manager_event(EVENT_FLAG_DTMF, "DTMFEnd",
848                 "%s"
849                 "Digit: %s\r\n"
850                 "DurationMs: %ld\r\n"
851                 "Direction: %s\r\n",
852                 ast_str_buffer(channel_event_string),
853                 digit, duration_ms, direction);
854 }
855
856 static void channel_hangup_handler_cb(void *data, struct stasis_subscription *sub,
857                 struct stasis_message *message)
858 {
859         RAII_VAR(struct ast_str *, channel_event_string, NULL, ast_free);
860         struct ast_channel_blob *payload = stasis_message_data(message);
861         const char *action = ast_json_string_get(ast_json_object_get(payload->blob, "type"));
862         const char *handler = ast_json_string_get(ast_json_object_get(payload->blob, "handler"));
863         const char *event;
864
865         channel_event_string = ast_manager_build_channel_state_string(payload->snapshot);
866
867         if (!channel_event_string) {
868                 return;
869         }
870
871         if (!strcmp(action, "type")) {
872                 event = "HangupHandlerRun";
873         } else if (!strcmp(action, "type")) {
874                 event = "HangupHandlerPop";
875         } else if (!strcmp(action, "type")) {
876                 event = "HangupHandlerPush";
877         } else {
878                 return;
879         }
880         manager_event(EVENT_FLAG_DIALPLAN, event,
881                 "%s"
882                 "Handler: %s\r\n",
883                 ast_str_buffer(channel_event_string),
884                 handler);
885 }
886
887 static void channel_fax_cb(void *data, struct stasis_subscription *sub,
888                 struct stasis_message *message)
889 {
890         RAII_VAR(struct ast_str *, channel_event_string, NULL, ast_free);
891         RAII_VAR(struct ast_str *, event_buffer, ast_str_create(256), ast_free);
892         struct ast_channel_blob *payload = stasis_message_data(message);
893         const char *type = ast_json_string_get(ast_json_object_get(payload->blob, "type"));
894         struct ast_json *operation = ast_json_object_get(payload->blob, "operation");
895         struct ast_json *status = ast_json_object_get(payload->blob, "status");
896         struct ast_json *local_station_id = ast_json_object_get(payload->blob, "local_station_id");
897         struct ast_json *remote_station_id = ast_json_object_get(payload->blob, "remote_station_id");
898         struct ast_json *fax_pages = ast_json_object_get(payload->blob, "fax_pages");
899         struct ast_json *fax_resolution = ast_json_object_get(payload->blob, "fax_resolution");
900         struct ast_json *fax_bitrate = ast_json_object_get(payload->blob, "fax_bitrate");
901         struct ast_json *filenames = ast_json_object_get(payload->blob, "filenames");
902         const char *event;
903         size_t array_len;
904         size_t i;
905
906         if (!event_buffer) {
907                 return;
908         }
909
910         channel_event_string = ast_manager_build_channel_state_string(payload->snapshot);
911         if (!channel_event_string) {
912                 return;
913         }
914
915         if (!strcmp(type, "status")) {
916                 event = "FAXStatus";
917         } else if (!strcmp(type, "receive")) {
918                 event = "ReceiveFAX";
919         } else if (!strcmp(type, "send")) {
920                 event = "SendFAX";
921         } else {
922                 return;
923         }
924
925         if (operation) {
926                 ast_str_append(&event_buffer, 0, "Operation: %s\r\n", ast_json_string_get(operation));
927         }
928         if (status) {
929                 ast_str_append(&event_buffer, 0, "Status: %s\r\n", ast_json_string_get(status));
930         }
931         if (local_station_id) {
932                 ast_str_append(&event_buffer, 0, "LocalStationID: %s\r\n", ast_json_string_get(local_station_id));
933         }
934         if (remote_station_id) {
935                 ast_str_append(&event_buffer, 0, "RemoteStationID: %s\r\n", ast_json_string_get(remote_station_id));
936         }
937         if (fax_pages) {
938                 ast_str_append(&event_buffer, 0, "PagesTransferred: %s\r\n", ast_json_string_get(fax_pages));
939         }
940         if (fax_resolution) {
941                 ast_str_append(&event_buffer, 0, "Resolution: %s\r\n", ast_json_string_get(fax_resolution));
942         }
943         if (fax_bitrate) {
944                 ast_str_append(&event_buffer, 0, "TransferRate: %s\r\n", ast_json_string_get(fax_bitrate));
945         }
946         if (filenames) {
947                 array_len = ast_json_array_size(filenames);
948                 for (i = 0; i < array_len; i++) {
949                         ast_str_append(&event_buffer, 0, "FileName: %s\r\n", ast_json_string_get(ast_json_array_get(filenames, i)));
950                 }
951         }
952
953         manager_event(EVENT_FLAG_CALL, event,
954                 "%s"
955                 "%s",
956                 ast_str_buffer(channel_event_string),
957                 ast_str_buffer(event_buffer));
958 }
959
960 static void channel_moh_start_cb(void *data, struct stasis_subscription *sub,
961                 struct stasis_message *message)
962 {
963         struct ast_channel_blob *payload = stasis_message_data(message);
964         struct ast_json *blob = payload->blob;
965         RAII_VAR(struct ast_str *, channel_event_string, NULL, ast_free);
966
967         channel_event_string = ast_manager_build_channel_state_string(payload->snapshot);
968         if (!channel_event_string) {
969                 return;
970         }
971
972         manager_event(EVENT_FLAG_CALL, "MusicOnHoldStart",
973                 "%s"
974                 "Class: %s\r\n",
975                 ast_str_buffer(channel_event_string),
976                 ast_json_string_get(ast_json_object_get(blob, "class")));
977
978 }
979
980 static void channel_moh_stop_cb(void *data, struct stasis_subscription *sub,
981                 struct stasis_message *message)
982 {
983         struct ast_channel_blob *payload = stasis_message_data(message);
984
985         publish_basic_channel_event("MusicOnHoldStop", EVENT_FLAG_CALL, payload->snapshot);
986 }
987
988 static void channel_monitor_start_cb(void *data, struct stasis_subscription *sub,
989                 struct stasis_message *message)
990 {
991         struct ast_channel_blob *payload = stasis_message_data(message);
992
993         publish_basic_channel_event("MonitorStart", EVENT_FLAG_CALL, payload->snapshot);
994 }
995
996 static void channel_monitor_stop_cb(void *data, struct stasis_subscription *sub,
997                 struct stasis_message *message)
998 {
999         struct ast_channel_blob *payload = stasis_message_data(message);
1000
1001         publish_basic_channel_event("MonitorStop", EVENT_FLAG_CALL, payload->snapshot);
1002 }
1003
1004 /*!
1005  * \brief Callback processing messages for channel dialing
1006  */
1007 static void channel_dial_cb(void *data, struct stasis_subscription *sub,
1008         struct stasis_message *message)
1009 {
1010         struct ast_multi_channel_blob *obj = stasis_message_data(message);
1011         const char *dialstatus;
1012         const char *dialstring;
1013         const char *forward;
1014         struct ast_channel_snapshot *caller;
1015         struct ast_channel_snapshot *peer;
1016         RAII_VAR(struct ast_str *, caller_event_string, NULL, ast_free);
1017         RAII_VAR(struct ast_str *, peer_event_string, NULL, ast_free);
1018
1019         caller = ast_multi_channel_blob_get_channel(obj, "caller");
1020         peer = ast_multi_channel_blob_get_channel(obj, "peer");
1021
1022         /* Peer is required - otherwise, who are we dialing? */
1023         ast_assert(peer != NULL);
1024         peer_event_string = ast_manager_build_channel_state_string_prefix(peer, "Dest");
1025         if (!peer_event_string) {
1026                 return;
1027         }
1028
1029         if (caller && !(caller_event_string = ast_manager_build_channel_state_string(caller))) {
1030                 return;
1031         }
1032
1033         dialstatus = ast_json_string_get(ast_json_object_get(ast_multi_channel_blob_get_json(obj), "dialstatus"));
1034         dialstring = ast_json_string_get(ast_json_object_get(ast_multi_channel_blob_get_json(obj), "dialstring"));
1035         forward = ast_json_string_get(ast_json_object_get(ast_multi_channel_blob_get_json(obj), "forward"));
1036         if (ast_strlen_zero(dialstatus)) {
1037                 manager_event(EVENT_FLAG_CALL, "DialBegin",
1038                                 "%s"
1039                                 "%s"
1040                                 "DialString: %s\r\n",
1041                                 caller_event_string ? ast_str_buffer(caller_event_string) : "",
1042                                 ast_str_buffer(peer_event_string),
1043                                 S_OR(dialstring, "unknown"));
1044         } else {
1045                 int forwarded = !ast_strlen_zero(forward);
1046
1047                 manager_event(EVENT_FLAG_CALL, "DialEnd",
1048                                 "%s"
1049                                 "%s"
1050                                 "%s%s%s"
1051                                 "DialStatus: %s\r\n",
1052                                 caller_event_string ? ast_str_buffer(caller_event_string) : "",
1053                                 ast_str_buffer(peer_event_string),
1054                                 forwarded ? "Forward: " : "", S_OR(forward, ""), forwarded ? "\r\n" : "",
1055                                 S_OR(dialstatus, "unknown"));
1056         }
1057
1058 }
1059
1060 static void channel_hold_cb(void *data, struct stasis_subscription *sub,
1061         struct stasis_message *message)
1062 {
1063         struct ast_channel_blob *obj = stasis_message_data(message);
1064         struct ast_str *musicclass_string = ast_str_create(32);
1065         struct ast_str *channel_event_string;
1066
1067         if (!musicclass_string) {
1068                 return;
1069         }
1070
1071         channel_event_string = ast_manager_build_channel_state_string(obj->snapshot);
1072         if (!channel_event_string) {
1073                 ast_free(musicclass_string);
1074                 return;
1075         }
1076
1077         if (obj->blob) {
1078                 const char *musicclass;
1079
1080                 musicclass = ast_json_string_get(ast_json_object_get(obj->blob, "musicclass"));
1081
1082                 if (!ast_strlen_zero(musicclass)) {
1083                         ast_str_set(&musicclass_string, 0, "MusicClass: %s\r\n", musicclass);
1084                 }
1085         }
1086
1087         manager_event(EVENT_FLAG_CALL, "Hold",
1088                 "%s"
1089                 "%s",
1090                 ast_str_buffer(channel_event_string),
1091                 ast_str_buffer(musicclass_string));
1092
1093         ast_free(musicclass_string);
1094         ast_free(channel_event_string);
1095 }
1096
1097 static void channel_unhold_cb(void *data, struct stasis_subscription *sub,
1098         struct stasis_message *message)
1099 {
1100         struct ast_channel_blob *obj = stasis_message_data(message);
1101         struct ast_str *channel_event_string;
1102
1103         channel_event_string = ast_manager_build_channel_state_string(obj->snapshot);
1104         if (!channel_event_string) {
1105                 return;
1106         }
1107
1108         manager_event(EVENT_FLAG_CALL, "Unhold",
1109                 "%s",
1110                 ast_str_buffer(channel_event_string));
1111
1112         ast_free(channel_event_string);
1113 }
1114
1115 static void manager_channels_shutdown(void)
1116 {
1117         stasis_forward_cancel(topic_forwarder);
1118         topic_forwarder = NULL;
1119 }
1120
1121 int manager_channels_init(void)
1122 {
1123         int ret = 0;
1124         struct stasis_topic *manager_topic;
1125         struct stasis_topic *channel_topic;
1126         struct stasis_message_router *message_router;
1127
1128         manager_topic = ast_manager_get_topic();
1129         if (!manager_topic) {
1130                 return -1;
1131         }
1132         message_router = ast_manager_get_message_router();
1133         if (!message_router) {
1134                 return -1;
1135         }
1136         channel_topic = ast_channel_topic_all_cached();
1137         if (!channel_topic) {
1138                 return -1;
1139         }
1140
1141         topic_forwarder = stasis_forward_all(channel_topic, manager_topic);
1142         if (!topic_forwarder) {
1143                 return -1;
1144         }
1145
1146         ast_register_cleanup(manager_channels_shutdown);
1147
1148         ret |= stasis_message_router_add_cache_update(message_router,
1149                 ast_channel_snapshot_type(), channel_snapshot_update, NULL);
1150
1151         ret |= stasis_message_router_add(message_router,
1152                 ast_channel_dtmf_begin_type(), channel_dtmf_begin_cb, NULL);
1153
1154         ret |= stasis_message_router_add(message_router,
1155                 ast_channel_dtmf_end_type(), channel_dtmf_end_cb, NULL);
1156
1157         ret |= stasis_message_router_add(message_router,
1158                 ast_channel_hangup_request_type(), channel_hangup_request_cb,
1159                 NULL);
1160
1161         ret |= stasis_message_router_add(message_router,
1162                 ast_channel_dial_type(), channel_dial_cb, NULL);
1163
1164         ret |= stasis_message_router_add(message_router,
1165                 ast_channel_hold_type(), channel_hold_cb, NULL);
1166
1167         ret |= stasis_message_router_add(message_router,
1168                 ast_channel_unhold_type(), channel_unhold_cb, NULL);
1169
1170         ret |= stasis_message_router_add(message_router,
1171                 ast_channel_fax_type(), channel_fax_cb, NULL);
1172
1173         ret |= stasis_message_router_add(message_router,
1174                 ast_channel_chanspy_start_type(), channel_chanspy_start_cb,
1175                 NULL);
1176
1177         ret |= stasis_message_router_add(message_router,
1178                 ast_channel_chanspy_stop_type(), channel_chanspy_stop_cb, NULL);
1179
1180         ret |= stasis_message_router_add(message_router,
1181                 ast_channel_hangup_handler_type(), channel_hangup_handler_cb,
1182                 NULL);
1183
1184         ret |= stasis_message_router_add(message_router,
1185                 ast_channel_moh_start_type(), channel_moh_start_cb, NULL);
1186
1187         ret |= stasis_message_router_add(message_router,
1188                 ast_channel_moh_stop_type(), channel_moh_stop_cb, NULL);
1189
1190         ret |= stasis_message_router_add(message_router,
1191                 ast_channel_monitor_start_type(), channel_monitor_start_cb,
1192                 NULL);
1193
1194         ret |= stasis_message_router_add(message_router,
1195                 ast_channel_monitor_stop_type(), channel_monitor_stop_cb, NULL);
1196
1197         /* If somehow we failed to add any routes, just shut down the whole
1198          * thing and fail it.
1199          */
1200         if (ret) {
1201                 manager_channels_shutdown();
1202                 return -1;
1203         }
1204
1205         return 0;
1206 }
1207