Merge "manager_channels.c: Fix allocation failure crash."
[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_REGISTER_FILE()
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         char *caller_name, *connected_name;
412
413         if (!out) {
414                 return NULL;
415         }
416
417         if (snapshot->tech_properties & AST_CHAN_TP_INTERNAL) {
418                 ast_free(out);
419                 return NULL;
420         }
421
422         caller_name = ast_escape_c_alloc(snapshot->caller_name);
423         connected_name = ast_escape_c_alloc(snapshot->connected_name);
424
425         res = ast_str_set(&out, 0,
426                 "%sChannel: %s\r\n"
427                 "%sChannelState: %u\r\n"
428                 "%sChannelStateDesc: %s\r\n"
429                 "%sCallerIDNum: %s\r\n"
430                 "%sCallerIDName: %s\r\n"
431                 "%sConnectedLineNum: %s\r\n"
432                 "%sConnectedLineName: %s\r\n"
433                 "%sLanguage: %s\r\n"
434                 "%sAccountCode: %s\r\n"
435                 "%sContext: %s\r\n"
436                 "%sExten: %s\r\n"
437                 "%sPriority: %d\r\n"
438                 "%sUniqueid: %s\r\n"
439                 "%sLinkedid: %s\r\n",
440                 prefix, snapshot->name,
441                 prefix, snapshot->state,
442                 prefix, ast_state2str(snapshot->state),
443                 prefix, S_OR(snapshot->caller_number, "<unknown>"),
444                 prefix, S_OR(caller_name, "<unknown>"),
445                 prefix, S_OR(snapshot->connected_number, "<unknown>"),
446                 prefix, S_OR(connected_name, "<unknown>"),
447                 prefix, snapshot->language,
448                 prefix, snapshot->accountcode,
449                 prefix, snapshot->context,
450                 prefix, snapshot->exten,
451                 prefix, snapshot->priority,
452                 prefix, snapshot->uniqueid,
453                 prefix, snapshot->linkedid);
454
455         if (!res) {
456                 ast_free(out);
457                 ast_free(caller_name);
458                 ast_free(connected_name);
459                 return NULL;
460         }
461
462         if (snapshot->manager_vars) {
463                 struct ast_var_t *var;
464                 char *val;
465                 AST_LIST_TRAVERSE(snapshot->manager_vars, var, entries) {
466                         val = ast_escape_c_alloc(var->value);
467                         ast_str_append(&out, 0, "%sChanVariable: %s=%s\r\n",
468                                        prefix,
469                                        var->name, S_OR(val, ""));
470                         ast_free(val);
471                 }
472         }
473
474         ast_free(caller_name);
475         ast_free(connected_name);
476
477         return out;
478 }
479
480 struct ast_str *ast_manager_build_channel_state_string(
481                 const struct ast_channel_snapshot *snapshot)
482 {
483         return ast_manager_build_channel_state_string_prefix(snapshot, "");
484 }
485
486 /*! \brief Typedef for callbacks that get called on channel snapshot updates */
487 typedef struct ast_manager_event_blob *(*channel_snapshot_monitor)(
488         struct ast_channel_snapshot *old_snapshot,
489         struct ast_channel_snapshot *new_snapshot);
490
491 /*! \brief Handle channel state changes */
492 static struct ast_manager_event_blob *channel_state_change(
493         struct ast_channel_snapshot *old_snapshot,
494         struct ast_channel_snapshot *new_snapshot)
495 {
496         int is_hungup, was_hungup;
497
498         if (!new_snapshot) {
499                 /* Ignore cache clearing events; we'll see the hangup first */
500                 return NULL;
501         }
502
503         /* The Newchannel, Newstate and Hangup events are closely related, in
504          * in that they are mutually exclusive, basically different flavors
505          * of a new channel state event.
506          */
507
508         if (!old_snapshot) {
509                 return ast_manager_event_blob_create(
510                         EVENT_FLAG_CALL, "Newchannel", NO_EXTRA_FIELDS);
511         }
512
513         was_hungup = ast_test_flag(&old_snapshot->flags, AST_FLAG_DEAD) ? 1 : 0;
514         is_hungup = ast_test_flag(&new_snapshot->flags, AST_FLAG_DEAD) ? 1 : 0;
515
516         if (!was_hungup && is_hungup) {
517                 return ast_manager_event_blob_create(
518                         EVENT_FLAG_CALL, "Hangup",
519                         "Cause: %d\r\n"
520                         "Cause-txt: %s\r\n",
521                         new_snapshot->hangupcause,
522                         ast_cause2str(new_snapshot->hangupcause));
523         }
524
525         if (old_snapshot->state != new_snapshot->state) {
526                 return ast_manager_event_blob_create(
527                         EVENT_FLAG_CALL, "Newstate", NO_EXTRA_FIELDS);
528         }
529
530         /* No event */
531         return NULL;
532 }
533
534 static struct ast_manager_event_blob *channel_newexten(
535         struct ast_channel_snapshot *old_snapshot,
536         struct ast_channel_snapshot *new_snapshot)
537 {
538         /* No Newexten event on cache clear */
539         if (!new_snapshot) {
540                 return NULL;
541         }
542
543         /* Empty application is not valid for a Newexten event */
544         if (ast_strlen_zero(new_snapshot->appl)) {
545                 return NULL;
546         }
547
548         /* Ignore any updates if we're hungup */
549         if (ast_test_flag(&new_snapshot->flags, AST_FLAG_DEAD)) {
550                 return NULL;
551         }
552
553         /* Ignore updates if the CEP is unchanged */
554         if (old_snapshot && ast_channel_snapshot_cep_equal(old_snapshot, new_snapshot)) {
555                 return NULL;
556         }
557
558         /* DEPRECATED: Extension field deprecated in 12; remove in 14 */
559         return ast_manager_event_blob_create(
560                 EVENT_FLAG_CALL, "Newexten",
561                 "Extension: %s\r\n"
562                 "Application: %s\r\n"
563                 "AppData: %s\r\n",
564                 new_snapshot->exten,
565                 new_snapshot->appl,
566                 new_snapshot->data);
567 }
568
569 static struct ast_manager_event_blob *channel_new_callerid(
570         struct ast_channel_snapshot *old_snapshot,
571         struct ast_channel_snapshot *new_snapshot)
572 {
573         struct ast_manager_event_blob *res;
574         char *callerid;
575
576         /* No NewCallerid event on cache clear or first event */
577         if (!old_snapshot || !new_snapshot) {
578                 return NULL;
579         }
580
581         if (ast_channel_snapshot_caller_id_equal(old_snapshot, new_snapshot)) {
582                 return NULL;
583         }
584
585         if (!(callerid = ast_escape_c_alloc(
586                       ast_describe_caller_presentation(new_snapshot->caller_pres)))) {
587                 return NULL;
588         }
589
590         res = ast_manager_event_blob_create(
591                 EVENT_FLAG_CALL, "NewCallerid",
592                 "CID-CallingPres: %d (%s)\r\n",
593                 new_snapshot->caller_pres,
594                 callerid);
595
596         ast_free(callerid);
597         return res;
598 }
599
600 static struct ast_manager_event_blob *channel_new_connected_line(
601         struct ast_channel_snapshot *old_snapshot,
602         struct ast_channel_snapshot *new_snapshot)
603 {
604         /* No NewConnectedLine event on cache clear or first event */
605         if (!old_snapshot || !new_snapshot) {
606                 return NULL;
607         }
608
609         if (ast_channel_snapshot_connected_line_equal(old_snapshot, new_snapshot)) {
610                 return NULL;
611         }
612
613         return ast_manager_event_blob_create(
614                 EVENT_FLAG_CALL, "NewConnectedLine", "%s", "");
615 }
616
617 static struct ast_manager_event_blob *channel_new_accountcode(
618         struct ast_channel_snapshot *old_snapshot,
619         struct ast_channel_snapshot *new_snapshot)
620 {
621         if (!old_snapshot || !new_snapshot) {
622                 return NULL;
623         }
624
625         if (!strcmp(old_snapshot->accountcode, new_snapshot->accountcode)) {
626                 return NULL;
627         }
628
629         return ast_manager_event_blob_create(
630                 EVENT_FLAG_CALL, "NewAccountCode",
631                 "OldAccountCode: %s\r\n", old_snapshot->accountcode);
632 }
633
634 channel_snapshot_monitor channel_monitors[] = {
635         channel_state_change,
636         channel_newexten,
637         channel_new_callerid,
638         channel_new_accountcode,
639         channel_new_connected_line,
640 };
641
642 static void channel_snapshot_update(void *data, struct stasis_subscription *sub,
643                                     struct stasis_message *message)
644 {
645         RAII_VAR(struct ast_str *, channel_event_string, NULL, ast_free);
646         struct stasis_cache_update *update;
647         struct ast_channel_snapshot *old_snapshot;
648         struct ast_channel_snapshot *new_snapshot;
649         size_t i;
650
651         update = stasis_message_data(message);
652
653         ast_assert(ast_channel_snapshot_type() == update->type);
654
655         old_snapshot = stasis_message_data(update->old_snapshot);
656         new_snapshot = stasis_message_data(update->new_snapshot);
657
658         for (i = 0; i < ARRAY_LEN(channel_monitors); ++i) {
659                 RAII_VAR(struct ast_manager_event_blob *, ev, NULL, ao2_cleanup);
660                 ev = channel_monitors[i](old_snapshot, new_snapshot);
661
662                 if (!ev) {
663                         continue;
664                 }
665
666                 /* If we haven't already, build the channel event string */
667                 if (!channel_event_string) {
668                         channel_event_string =
669                                 ast_manager_build_channel_state_string(new_snapshot);
670                         if (!channel_event_string) {
671                                 return;
672                         }
673                 }
674
675                 manager_event(ev->event_flags, ev->manager_event, "%s%s",
676                         ast_str_buffer(channel_event_string),
677                         ev->extra_fields);
678         }
679 }
680
681 static void publish_basic_channel_event(const char *event, int class, struct ast_channel_snapshot *snapshot)
682 {
683         RAII_VAR(struct ast_str *, channel_event_string, NULL, ast_free);
684
685         channel_event_string = ast_manager_build_channel_state_string(snapshot);
686         if (!channel_event_string) {
687                 return;
688         }
689
690         manager_event(class, event,
691                 "%s",
692                 ast_str_buffer(channel_event_string));
693 }
694
695 static void channel_hangup_request_cb(void *data,
696         struct stasis_subscription *sub,
697         struct stasis_message *message)
698 {
699         struct ast_channel_blob *obj = stasis_message_data(message);
700         struct ast_str *extra;
701         struct ast_str *channel_event_string;
702         struct ast_json *cause;
703         int is_soft;
704         char *manager_event = "HangupRequest";
705
706         if (!obj->snapshot) {
707                 /* No snapshot?  Likely an earlier allocation failure creating it. */
708                 return;
709         }
710
711         extra = ast_str_create(20);
712         if (!extra) {
713                 return;
714         }
715
716         channel_event_string = ast_manager_build_channel_state_string(obj->snapshot);
717         if (!channel_event_string) {
718                 ast_free(extra);
719                 return;
720         }
721
722         cause = ast_json_object_get(obj->blob, "cause");
723         if (cause) {
724                 ast_str_append(&extra, 0,
725                         "Cause: %jd\r\n",
726                         ast_json_integer_get(cause));
727         }
728
729         is_soft = ast_json_is_true(ast_json_object_get(obj->blob, "soft"));
730         if (is_soft) {
731                 manager_event = "SoftHangupRequest";
732         }
733
734         manager_event(EVENT_FLAG_CALL, manager_event,
735                 "%s%s",
736                 ast_str_buffer(channel_event_string),
737                 ast_str_buffer(extra));
738
739         ast_free(channel_event_string);
740         ast_free(extra);
741 }
742
743 static void channel_chanspy_stop_cb(void *data, struct stasis_subscription *sub,
744                 struct stasis_message *message)
745 {
746         RAII_VAR(struct ast_str *, spyer_channel_string, NULL, ast_free);
747         struct ast_channel_snapshot *spyer;
748         struct ast_multi_channel_blob *payload = stasis_message_data(message);
749
750         spyer = ast_multi_channel_blob_get_channel(payload, "spyer_channel");
751         if (!spyer) {
752                 ast_log(AST_LOG_WARNING, "Received ChanSpy Start event with no spyer channel!\n");
753                 return;
754         }
755
756         spyer_channel_string = ast_manager_build_channel_state_string_prefix(spyer, "Spyer");
757         if (!spyer_channel_string) {
758                 return;
759         }
760
761         manager_event(EVENT_FLAG_CALL, "ChanSpyStop",
762                       "%s",
763                       ast_str_buffer(spyer_channel_string));
764 }
765
766 static void channel_chanspy_start_cb(void *data, struct stasis_subscription *sub,
767                 struct stasis_message *message)
768 {
769         RAII_VAR(struct ast_str *, spyer_channel_string, NULL, ast_free);
770         RAII_VAR(struct ast_str *, spyee_channel_string, NULL, ast_free);
771         struct ast_channel_snapshot *spyer;
772         struct ast_channel_snapshot *spyee;
773         struct ast_multi_channel_blob *payload = stasis_message_data(message);
774
775         spyer = ast_multi_channel_blob_get_channel(payload, "spyer_channel");
776         if (!spyer) {
777                 ast_log(AST_LOG_WARNING, "Received ChanSpy Start event with no spyer channel!\n");
778                 return;
779         }
780         spyee = ast_multi_channel_blob_get_channel(payload, "spyee_channel");
781         if (!spyee) {
782                 ast_log(AST_LOG_WARNING, "Received ChanSpy Start event with no spyee channel!\n");
783                 return;
784         }
785
786         spyer_channel_string = ast_manager_build_channel_state_string_prefix(spyer, "Spyer");
787         if (!spyer_channel_string) {
788                 return;
789         }
790         spyee_channel_string = ast_manager_build_channel_state_string_prefix(spyee, "Spyee");
791         if (!spyee_channel_string) {
792                 return;
793         }
794
795         manager_event(EVENT_FLAG_CALL, "ChanSpyStart",
796                       "%s%s",
797                       ast_str_buffer(spyer_channel_string),
798                       ast_str_buffer(spyee_channel_string));
799 }
800
801 static void channel_dtmf_begin_cb(void *data, struct stasis_subscription *sub,
802         struct stasis_message *message)
803 {
804         struct ast_channel_blob *obj = stasis_message_data(message);
805         RAII_VAR(struct ast_str *, channel_event_string, NULL, ast_free);
806         const char *digit =
807                 ast_json_string_get(ast_json_object_get(obj->blob, "digit"));
808         const char *direction =
809                 ast_json_string_get(ast_json_object_get(obj->blob, "direction"));
810
811         channel_event_string = ast_manager_build_channel_state_string(obj->snapshot);
812
813         if (!channel_event_string) {
814                 return;
815         }
816
817         /*** DOCUMENTATION
818                 <managerEventInstance>
819                         <synopsis>Raised when a DTMF digit has started on a channel.</synopsis>
820                                 <syntax>
821                                         <channel_snapshot/>
822                                         <parameter name="Digit">
823                                                 <para>DTMF digit received or transmitted (0-9, A-E, # or *</para>
824                                         </parameter>
825                                         <parameter name="Direction">
826                                                 <enumlist>
827                                                         <enum name="Received"/>
828                                                         <enum name="Sent"/>
829                                                 </enumlist>
830                                         </parameter>
831                                 </syntax>
832                 </managerEventInstance>
833         ***/
834         manager_event(EVENT_FLAG_DTMF, "DTMFBegin",
835                 "%s"
836                 "Digit: %s\r\n"
837                 "Direction: %s\r\n",
838                 ast_str_buffer(channel_event_string),
839                 digit, direction);
840 }
841
842 static void channel_dtmf_end_cb(void *data, struct stasis_subscription *sub,
843         struct stasis_message *message)
844 {
845         struct ast_channel_blob *obj = stasis_message_data(message);
846         RAII_VAR(struct ast_str *, channel_event_string, NULL, ast_free);
847         const char *digit =
848                 ast_json_string_get(ast_json_object_get(obj->blob, "digit"));
849         const char *direction =
850                 ast_json_string_get(ast_json_object_get(obj->blob, "direction"));
851         long duration_ms =
852                 ast_json_integer_get(ast_json_object_get(obj->blob, "duration_ms"));
853
854         channel_event_string = ast_manager_build_channel_state_string(obj->snapshot);
855
856         if (!channel_event_string) {
857                 return;
858         }
859
860         /*** DOCUMENTATION
861                 <managerEventInstance>
862                         <synopsis>Raised when a DTMF digit has ended on a channel.</synopsis>
863                                 <syntax>
864                                         <channel_snapshot/>
865                                         <parameter name="Digit">
866                                                 <para>DTMF digit received or transmitted (0-9, A-E, # or *</para>
867                                         </parameter>
868                                         <parameter name="DurationMs">
869                                                 <para>Duration (in milliseconds) DTMF was sent/received</para>
870                                         </parameter>
871                                         <parameter name="Direction">
872                                                 <enumlist>
873                                                         <enum name="Received"/>
874                                                         <enum name="Sent"/>
875                                                 </enumlist>
876                                         </parameter>
877                                 </syntax>
878                 </managerEventInstance>
879         ***/
880         manager_event(EVENT_FLAG_DTMF, "DTMFEnd",
881                 "%s"
882                 "Digit: %s\r\n"
883                 "DurationMs: %ld\r\n"
884                 "Direction: %s\r\n",
885                 ast_str_buffer(channel_event_string),
886                 digit, duration_ms, direction);
887 }
888
889 static void channel_hangup_handler_cb(void *data, struct stasis_subscription *sub,
890                 struct stasis_message *message)
891 {
892         RAII_VAR(struct ast_str *, channel_event_string, NULL, ast_free);
893         struct ast_channel_blob *payload = stasis_message_data(message);
894         const char *action = ast_json_string_get(ast_json_object_get(payload->blob, "type"));
895         const char *handler = ast_json_string_get(ast_json_object_get(payload->blob, "handler"));
896         const char *event;
897
898         channel_event_string = ast_manager_build_channel_state_string(payload->snapshot);
899
900         if (!channel_event_string) {
901                 return;
902         }
903
904         if (!strcmp(action, "type")) {
905                 event = "HangupHandlerRun";
906         } else if (!strcmp(action, "type")) {
907                 event = "HangupHandlerPop";
908         } else if (!strcmp(action, "type")) {
909                 event = "HangupHandlerPush";
910         } else {
911                 return;
912         }
913         manager_event(EVENT_FLAG_DIALPLAN, event,
914                 "%s"
915                 "Handler: %s\r\n",
916                 ast_str_buffer(channel_event_string),
917                 handler);
918 }
919
920 static void channel_fax_cb(void *data, struct stasis_subscription *sub,
921                 struct stasis_message *message)
922 {
923         RAII_VAR(struct ast_str *, channel_event_string, NULL, ast_free);
924         RAII_VAR(struct ast_str *, event_buffer, ast_str_create(256), ast_free);
925         struct ast_channel_blob *payload = stasis_message_data(message);
926         const char *type = ast_json_string_get(ast_json_object_get(payload->blob, "type"));
927         struct ast_json *operation = ast_json_object_get(payload->blob, "operation");
928         struct ast_json *status = ast_json_object_get(payload->blob, "status");
929         struct ast_json *local_station_id = ast_json_object_get(payload->blob, "local_station_id");
930         struct ast_json *remote_station_id = ast_json_object_get(payload->blob, "remote_station_id");
931         struct ast_json *fax_pages = ast_json_object_get(payload->blob, "fax_pages");
932         struct ast_json *fax_resolution = ast_json_object_get(payload->blob, "fax_resolution");
933         struct ast_json *fax_bitrate = ast_json_object_get(payload->blob, "fax_bitrate");
934         struct ast_json *filenames = ast_json_object_get(payload->blob, "filenames");
935         const char *event;
936         size_t array_len;
937         size_t i;
938
939         if (!event_buffer) {
940                 return;
941         }
942
943         channel_event_string = ast_manager_build_channel_state_string(payload->snapshot);
944         if (!channel_event_string) {
945                 return;
946         }
947
948         if (!strcmp(type, "status")) {
949                 event = "FAXStatus";
950         } else if (!strcmp(type, "receive")) {
951                 event = "ReceiveFAX";
952         } else if (!strcmp(type, "send")) {
953                 event = "SendFAX";
954         } else {
955                 return;
956         }
957
958         if (operation) {
959                 ast_str_append(&event_buffer, 0, "Operation: %s\r\n", ast_json_string_get(operation));
960         }
961         if (status) {
962                 ast_str_append(&event_buffer, 0, "Status: %s\r\n", ast_json_string_get(status));
963         }
964         if (local_station_id) {
965                 ast_str_append(&event_buffer, 0, "LocalStationID: %s\r\n", ast_json_string_get(local_station_id));
966         }
967         if (remote_station_id) {
968                 ast_str_append(&event_buffer, 0, "RemoteStationID: %s\r\n", ast_json_string_get(remote_station_id));
969         }
970         if (fax_pages) {
971                 ast_str_append(&event_buffer, 0, "PagesTransferred: %s\r\n", ast_json_string_get(fax_pages));
972         }
973         if (fax_resolution) {
974                 ast_str_append(&event_buffer, 0, "Resolution: %s\r\n", ast_json_string_get(fax_resolution));
975         }
976         if (fax_bitrate) {
977                 ast_str_append(&event_buffer, 0, "TransferRate: %s\r\n", ast_json_string_get(fax_bitrate));
978         }
979         if (filenames) {
980                 array_len = ast_json_array_size(filenames);
981                 for (i = 0; i < array_len; i++) {
982                         ast_str_append(&event_buffer, 0, "FileName: %s\r\n", ast_json_string_get(ast_json_array_get(filenames, i)));
983                 }
984         }
985
986         manager_event(EVENT_FLAG_CALL, event,
987                 "%s"
988                 "%s",
989                 ast_str_buffer(channel_event_string),
990                 ast_str_buffer(event_buffer));
991 }
992
993 static void channel_moh_start_cb(void *data, struct stasis_subscription *sub,
994                 struct stasis_message *message)
995 {
996         struct ast_channel_blob *payload = stasis_message_data(message);
997         struct ast_json *blob = payload->blob;
998         RAII_VAR(struct ast_str *, channel_event_string, NULL, ast_free);
999
1000         channel_event_string = ast_manager_build_channel_state_string(payload->snapshot);
1001         if (!channel_event_string) {
1002                 return;
1003         }
1004
1005         manager_event(EVENT_FLAG_CALL, "MusicOnHoldStart",
1006                 "%s"
1007                 "Class: %s\r\n",
1008                 ast_str_buffer(channel_event_string),
1009                 ast_json_string_get(ast_json_object_get(blob, "class")));
1010
1011 }
1012
1013 static void channel_moh_stop_cb(void *data, struct stasis_subscription *sub,
1014                 struct stasis_message *message)
1015 {
1016         struct ast_channel_blob *payload = stasis_message_data(message);
1017
1018         publish_basic_channel_event("MusicOnHoldStop", EVENT_FLAG_CALL, payload->snapshot);
1019 }
1020
1021 static void channel_monitor_start_cb(void *data, struct stasis_subscription *sub,
1022                 struct stasis_message *message)
1023 {
1024         struct ast_channel_blob *payload = stasis_message_data(message);
1025
1026         publish_basic_channel_event("MonitorStart", EVENT_FLAG_CALL, payload->snapshot);
1027 }
1028
1029 static void channel_monitor_stop_cb(void *data, struct stasis_subscription *sub,
1030                 struct stasis_message *message)
1031 {
1032         struct ast_channel_blob *payload = stasis_message_data(message);
1033
1034         publish_basic_channel_event("MonitorStop", EVENT_FLAG_CALL, payload->snapshot);
1035 }
1036
1037 /*!
1038  * \brief Callback processing messages for channel dialing
1039  */
1040 static void channel_dial_cb(void *data, struct stasis_subscription *sub,
1041         struct stasis_message *message)
1042 {
1043         struct ast_multi_channel_blob *obj = stasis_message_data(message);
1044         const char *dialstatus;
1045         const char *dialstring;
1046         const char *forward;
1047         struct ast_channel_snapshot *caller;
1048         struct ast_channel_snapshot *peer;
1049         RAII_VAR(struct ast_str *, caller_event_string, NULL, ast_free);
1050         RAII_VAR(struct ast_str *, peer_event_string, NULL, ast_free);
1051
1052         caller = ast_multi_channel_blob_get_channel(obj, "caller");
1053         peer = ast_multi_channel_blob_get_channel(obj, "peer");
1054
1055         /* Peer is required - otherwise, who are we dialing? */
1056         ast_assert(peer != NULL);
1057         peer_event_string = ast_manager_build_channel_state_string_prefix(peer, "Dest");
1058         if (!peer_event_string) {
1059                 return;
1060         }
1061
1062         if (caller && !(caller_event_string = ast_manager_build_channel_state_string(caller))) {
1063                 return;
1064         }
1065
1066         dialstatus = ast_json_string_get(ast_json_object_get(ast_multi_channel_blob_get_json(obj), "dialstatus"));
1067         dialstring = ast_json_string_get(ast_json_object_get(ast_multi_channel_blob_get_json(obj), "dialstring"));
1068         forward = ast_json_string_get(ast_json_object_get(ast_multi_channel_blob_get_json(obj), "forward"));
1069         if (ast_strlen_zero(dialstatus)) {
1070                 manager_event(EVENT_FLAG_CALL, "DialBegin",
1071                                 "%s"
1072                                 "%s"
1073                                 "DialString: %s\r\n",
1074                                 caller_event_string ? ast_str_buffer(caller_event_string) : "",
1075                                 ast_str_buffer(peer_event_string),
1076                                 S_OR(dialstring, "unknown"));
1077         } else {
1078                 int forwarded = !ast_strlen_zero(forward);
1079
1080                 manager_event(EVENT_FLAG_CALL, "DialEnd",
1081                                 "%s"
1082                                 "%s"
1083                                 "%s%s%s"
1084                                 "DialStatus: %s\r\n",
1085                                 caller_event_string ? ast_str_buffer(caller_event_string) : "",
1086                                 ast_str_buffer(peer_event_string),
1087                                 forwarded ? "Forward: " : "", S_OR(forward, ""), forwarded ? "\r\n" : "",
1088                                 S_OR(dialstatus, "unknown"));
1089         }
1090
1091 }
1092
1093 static void channel_hold_cb(void *data, struct stasis_subscription *sub,
1094         struct stasis_message *message)
1095 {
1096         struct ast_channel_blob *obj = stasis_message_data(message);
1097         struct ast_str *musicclass_string = ast_str_create(32);
1098         struct ast_str *channel_event_string;
1099
1100         if (!musicclass_string) {
1101                 return;
1102         }
1103
1104         channel_event_string = ast_manager_build_channel_state_string(obj->snapshot);
1105         if (!channel_event_string) {
1106                 ast_free(musicclass_string);
1107                 return;
1108         }
1109
1110         if (obj->blob) {
1111                 const char *musicclass;
1112
1113                 musicclass = ast_json_string_get(ast_json_object_get(obj->blob, "musicclass"));
1114
1115                 if (!ast_strlen_zero(musicclass)) {
1116                         ast_str_set(&musicclass_string, 0, "MusicClass: %s\r\n", musicclass);
1117                 }
1118         }
1119
1120         manager_event(EVENT_FLAG_CALL, "Hold",
1121                 "%s"
1122                 "%s",
1123                 ast_str_buffer(channel_event_string),
1124                 ast_str_buffer(musicclass_string));
1125
1126         ast_free(musicclass_string);
1127         ast_free(channel_event_string);
1128 }
1129
1130 static void channel_unhold_cb(void *data, struct stasis_subscription *sub,
1131         struct stasis_message *message)
1132 {
1133         struct ast_channel_blob *obj = stasis_message_data(message);
1134         struct ast_str *channel_event_string;
1135
1136         channel_event_string = ast_manager_build_channel_state_string(obj->snapshot);
1137         if (!channel_event_string) {
1138                 return;
1139         }
1140
1141         manager_event(EVENT_FLAG_CALL, "Unhold",
1142                 "%s",
1143                 ast_str_buffer(channel_event_string));
1144
1145         ast_free(channel_event_string);
1146 }
1147
1148 static void manager_channels_shutdown(void)
1149 {
1150         stasis_forward_cancel(topic_forwarder);
1151         topic_forwarder = NULL;
1152 }
1153
1154 int manager_channels_init(void)
1155 {
1156         int ret = 0;
1157         struct stasis_topic *manager_topic;
1158         struct stasis_topic *channel_topic;
1159         struct stasis_message_router *message_router;
1160
1161         manager_topic = ast_manager_get_topic();
1162         if (!manager_topic) {
1163                 return -1;
1164         }
1165         message_router = ast_manager_get_message_router();
1166         if (!message_router) {
1167                 return -1;
1168         }
1169         channel_topic = ast_channel_topic_all_cached();
1170         if (!channel_topic) {
1171                 return -1;
1172         }
1173
1174         topic_forwarder = stasis_forward_all(channel_topic, manager_topic);
1175         if (!topic_forwarder) {
1176                 return -1;
1177         }
1178
1179         ast_register_cleanup(manager_channels_shutdown);
1180
1181         ret |= stasis_message_router_add_cache_update(message_router,
1182                 ast_channel_snapshot_type(), channel_snapshot_update, NULL);
1183
1184         ret |= stasis_message_router_add(message_router,
1185                 ast_channel_dtmf_begin_type(), channel_dtmf_begin_cb, NULL);
1186
1187         ret |= stasis_message_router_add(message_router,
1188                 ast_channel_dtmf_end_type(), channel_dtmf_end_cb, NULL);
1189
1190         ret |= stasis_message_router_add(message_router,
1191                 ast_channel_hangup_request_type(), channel_hangup_request_cb,
1192                 NULL);
1193
1194         ret |= stasis_message_router_add(message_router,
1195                 ast_channel_dial_type(), channel_dial_cb, NULL);
1196
1197         ret |= stasis_message_router_add(message_router,
1198                 ast_channel_hold_type(), channel_hold_cb, NULL);
1199
1200         ret |= stasis_message_router_add(message_router,
1201                 ast_channel_unhold_type(), channel_unhold_cb, NULL);
1202
1203         ret |= stasis_message_router_add(message_router,
1204                 ast_channel_fax_type(), channel_fax_cb, NULL);
1205
1206         ret |= stasis_message_router_add(message_router,
1207                 ast_channel_chanspy_start_type(), channel_chanspy_start_cb,
1208                 NULL);
1209
1210         ret |= stasis_message_router_add(message_router,
1211                 ast_channel_chanspy_stop_type(), channel_chanspy_stop_cb, NULL);
1212
1213         ret |= stasis_message_router_add(message_router,
1214                 ast_channel_hangup_handler_type(), channel_hangup_handler_cb,
1215                 NULL);
1216
1217         ret |= stasis_message_router_add(message_router,
1218                 ast_channel_moh_start_type(), channel_moh_start_cb, NULL);
1219
1220         ret |= stasis_message_router_add(message_router,
1221                 ast_channel_moh_stop_type(), channel_moh_stop_cb, NULL);
1222
1223         ret |= stasis_message_router_add(message_router,
1224                 ast_channel_monitor_start_type(), channel_monitor_start_cb,
1225                 NULL);
1226
1227         ret |= stasis_message_router_add(message_router,
1228                 ast_channel_monitor_stop_type(), channel_monitor_stop_cb, NULL);
1229
1230         /* If somehow we failed to add any routes, just shut down the whole
1231          * thing and fail it.
1232          */
1233         if (ret) {
1234                 manager_channels_shutdown();
1235                 return -1;
1236         }
1237
1238         return 0;
1239 }
1240