Merge "Bridge system: Fix memory leaks and double frees on impart failure."
[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         RAII_VAR(struct ast_str *, extra, NULL, ast_free);
701         RAII_VAR(struct ast_str *, channel_event_string, NULL, ast_free);
702         struct ast_json *cause;
703         int is_soft;
704         char *manager_event = "HangupRequest";
705
706         extra = ast_str_create(20);
707         if (!extra) {
708                 return;
709         }
710
711         channel_event_string = ast_manager_build_channel_state_string(obj->snapshot);
712
713         if (!channel_event_string) {
714                 return;
715         }
716
717         cause = ast_json_object_get(obj->blob, "cause");
718         if (cause) {
719                 ast_str_append(&extra, 0,
720                                "Cause: %jd\r\n",
721                                ast_json_integer_get(cause));
722         }
723
724         is_soft = ast_json_is_true(ast_json_object_get(obj->blob, "soft"));
725         if (is_soft) {
726                 manager_event = "SoftHangupRequest";
727         }
728
729         manager_event(EVENT_FLAG_CALL, manager_event,
730                       "%s%s",
731                       ast_str_buffer(channel_event_string),
732                       ast_str_buffer(extra));
733 }
734
735 static void channel_chanspy_stop_cb(void *data, struct stasis_subscription *sub,
736                 struct stasis_message *message)
737 {
738         RAII_VAR(struct ast_str *, spyer_channel_string, NULL, ast_free);
739         struct ast_channel_snapshot *spyer;
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
748         spyer_channel_string = ast_manager_build_channel_state_string_prefix(spyer, "Spyer");
749         if (!spyer_channel_string) {
750                 return;
751         }
752
753         manager_event(EVENT_FLAG_CALL, "ChanSpyStop",
754                       "%s",
755                       ast_str_buffer(spyer_channel_string));
756 }
757
758 static void channel_chanspy_start_cb(void *data, struct stasis_subscription *sub,
759                 struct stasis_message *message)
760 {
761         RAII_VAR(struct ast_str *, spyer_channel_string, NULL, ast_free);
762         RAII_VAR(struct ast_str *, spyee_channel_string, NULL, ast_free);
763         struct ast_channel_snapshot *spyer;
764         struct ast_channel_snapshot *spyee;
765         struct ast_multi_channel_blob *payload = stasis_message_data(message);
766
767         spyer = ast_multi_channel_blob_get_channel(payload, "spyer_channel");
768         if (!spyer) {
769                 ast_log(AST_LOG_WARNING, "Received ChanSpy Start event with no spyer channel!\n");
770                 return;
771         }
772         spyee = ast_multi_channel_blob_get_channel(payload, "spyee_channel");
773         if (!spyee) {
774                 ast_log(AST_LOG_WARNING, "Received ChanSpy Start event with no spyee channel!\n");
775                 return;
776         }
777
778         spyer_channel_string = ast_manager_build_channel_state_string_prefix(spyer, "Spyer");
779         if (!spyer_channel_string) {
780                 return;
781         }
782         spyee_channel_string = ast_manager_build_channel_state_string_prefix(spyee, "Spyee");
783         if (!spyee_channel_string) {
784                 return;
785         }
786
787         manager_event(EVENT_FLAG_CALL, "ChanSpyStart",
788                       "%s%s",
789                       ast_str_buffer(spyer_channel_string),
790                       ast_str_buffer(spyee_channel_string));
791 }
792
793 static void channel_dtmf_begin_cb(void *data, struct stasis_subscription *sub,
794         struct stasis_message *message)
795 {
796         struct ast_channel_blob *obj = stasis_message_data(message);
797         RAII_VAR(struct ast_str *, channel_event_string, NULL, ast_free);
798         const char *digit =
799                 ast_json_string_get(ast_json_object_get(obj->blob, "digit"));
800         const char *direction =
801                 ast_json_string_get(ast_json_object_get(obj->blob, "direction"));
802
803         channel_event_string = ast_manager_build_channel_state_string(obj->snapshot);
804
805         if (!channel_event_string) {
806                 return;
807         }
808
809         /*** DOCUMENTATION
810                 <managerEventInstance>
811                         <synopsis>Raised when a DTMF digit has started on a channel.</synopsis>
812                                 <syntax>
813                                         <channel_snapshot/>
814                                         <parameter name="Digit">
815                                                 <para>DTMF digit received or transmitted (0-9, A-E, # or *</para>
816                                         </parameter>
817                                         <parameter name="Direction">
818                                                 <enumlist>
819                                                         <enum name="Received"/>
820                                                         <enum name="Sent"/>
821                                                 </enumlist>
822                                         </parameter>
823                                 </syntax>
824                 </managerEventInstance>
825         ***/
826         manager_event(EVENT_FLAG_DTMF, "DTMFBegin",
827                 "%s"
828                 "Digit: %s\r\n"
829                 "Direction: %s\r\n",
830                 ast_str_buffer(channel_event_string),
831                 digit, direction);
832 }
833
834 static void channel_dtmf_end_cb(void *data, struct stasis_subscription *sub,
835         struct stasis_message *message)
836 {
837         struct ast_channel_blob *obj = stasis_message_data(message);
838         RAII_VAR(struct ast_str *, channel_event_string, NULL, ast_free);
839         const char *digit =
840                 ast_json_string_get(ast_json_object_get(obj->blob, "digit"));
841         const char *direction =
842                 ast_json_string_get(ast_json_object_get(obj->blob, "direction"));
843         long duration_ms =
844                 ast_json_integer_get(ast_json_object_get(obj->blob, "duration_ms"));
845
846         channel_event_string = ast_manager_build_channel_state_string(obj->snapshot);
847
848         if (!channel_event_string) {
849                 return;
850         }
851
852         /*** DOCUMENTATION
853                 <managerEventInstance>
854                         <synopsis>Raised when a DTMF digit has ended on a channel.</synopsis>
855                                 <syntax>
856                                         <channel_snapshot/>
857                                         <parameter name="Digit">
858                                                 <para>DTMF digit received or transmitted (0-9, A-E, # or *</para>
859                                         </parameter>
860                                         <parameter name="DurationMs">
861                                                 <para>Duration (in milliseconds) DTMF was sent/received</para>
862                                         </parameter>
863                                         <parameter name="Direction">
864                                                 <enumlist>
865                                                         <enum name="Received"/>
866                                                         <enum name="Sent"/>
867                                                 </enumlist>
868                                         </parameter>
869                                 </syntax>
870                 </managerEventInstance>
871         ***/
872         manager_event(EVENT_FLAG_DTMF, "DTMFEnd",
873                 "%s"
874                 "Digit: %s\r\n"
875                 "DurationMs: %ld\r\n"
876                 "Direction: %s\r\n",
877                 ast_str_buffer(channel_event_string),
878                 digit, duration_ms, direction);
879 }
880
881 static void channel_hangup_handler_cb(void *data, struct stasis_subscription *sub,
882                 struct stasis_message *message)
883 {
884         RAII_VAR(struct ast_str *, channel_event_string, NULL, ast_free);
885         struct ast_channel_blob *payload = stasis_message_data(message);
886         const char *action = ast_json_string_get(ast_json_object_get(payload->blob, "type"));
887         const char *handler = ast_json_string_get(ast_json_object_get(payload->blob, "handler"));
888         const char *event;
889
890         channel_event_string = ast_manager_build_channel_state_string(payload->snapshot);
891
892         if (!channel_event_string) {
893                 return;
894         }
895
896         if (!strcmp(action, "type")) {
897                 event = "HangupHandlerRun";
898         } else if (!strcmp(action, "type")) {
899                 event = "HangupHandlerPop";
900         } else if (!strcmp(action, "type")) {
901                 event = "HangupHandlerPush";
902         } else {
903                 return;
904         }
905         manager_event(EVENT_FLAG_DIALPLAN, event,
906                 "%s"
907                 "Handler: %s\r\n",
908                 ast_str_buffer(channel_event_string),
909                 handler);
910 }
911
912 static void channel_fax_cb(void *data, struct stasis_subscription *sub,
913                 struct stasis_message *message)
914 {
915         RAII_VAR(struct ast_str *, channel_event_string, NULL, ast_free);
916         RAII_VAR(struct ast_str *, event_buffer, ast_str_create(256), ast_free);
917         struct ast_channel_blob *payload = stasis_message_data(message);
918         const char *type = ast_json_string_get(ast_json_object_get(payload->blob, "type"));
919         struct ast_json *operation = ast_json_object_get(payload->blob, "operation");
920         struct ast_json *status = ast_json_object_get(payload->blob, "status");
921         struct ast_json *local_station_id = ast_json_object_get(payload->blob, "local_station_id");
922         struct ast_json *remote_station_id = ast_json_object_get(payload->blob, "remote_station_id");
923         struct ast_json *fax_pages = ast_json_object_get(payload->blob, "fax_pages");
924         struct ast_json *fax_resolution = ast_json_object_get(payload->blob, "fax_resolution");
925         struct ast_json *fax_bitrate = ast_json_object_get(payload->blob, "fax_bitrate");
926         struct ast_json *filenames = ast_json_object_get(payload->blob, "filenames");
927         const char *event;
928         size_t array_len;
929         size_t i;
930
931         if (!event_buffer) {
932                 return;
933         }
934
935         channel_event_string = ast_manager_build_channel_state_string(payload->snapshot);
936         if (!channel_event_string) {
937                 return;
938         }
939
940         if (!strcmp(type, "status")) {
941                 event = "FAXStatus";
942         } else if (!strcmp(type, "receive")) {
943                 event = "ReceiveFAX";
944         } else if (!strcmp(type, "send")) {
945                 event = "SendFAX";
946         } else {
947                 return;
948         }
949
950         if (operation) {
951                 ast_str_append(&event_buffer, 0, "Operation: %s\r\n", ast_json_string_get(operation));
952         }
953         if (status) {
954                 ast_str_append(&event_buffer, 0, "Status: %s\r\n", ast_json_string_get(status));
955         }
956         if (local_station_id) {
957                 ast_str_append(&event_buffer, 0, "LocalStationID: %s\r\n", ast_json_string_get(local_station_id));
958         }
959         if (remote_station_id) {
960                 ast_str_append(&event_buffer, 0, "RemoteStationID: %s\r\n", ast_json_string_get(remote_station_id));
961         }
962         if (fax_pages) {
963                 ast_str_append(&event_buffer, 0, "PagesTransferred: %s\r\n", ast_json_string_get(fax_pages));
964         }
965         if (fax_resolution) {
966                 ast_str_append(&event_buffer, 0, "Resolution: %s\r\n", ast_json_string_get(fax_resolution));
967         }
968         if (fax_bitrate) {
969                 ast_str_append(&event_buffer, 0, "TransferRate: %s\r\n", ast_json_string_get(fax_bitrate));
970         }
971         if (filenames) {
972                 array_len = ast_json_array_size(filenames);
973                 for (i = 0; i < array_len; i++) {
974                         ast_str_append(&event_buffer, 0, "FileName: %s\r\n", ast_json_string_get(ast_json_array_get(filenames, i)));
975                 }
976         }
977
978         manager_event(EVENT_FLAG_CALL, event,
979                 "%s"
980                 "%s",
981                 ast_str_buffer(channel_event_string),
982                 ast_str_buffer(event_buffer));
983 }
984
985 static void channel_moh_start_cb(void *data, struct stasis_subscription *sub,
986                 struct stasis_message *message)
987 {
988         struct ast_channel_blob *payload = stasis_message_data(message);
989         struct ast_json *blob = payload->blob;
990         RAII_VAR(struct ast_str *, channel_event_string, NULL, ast_free);
991
992         channel_event_string = ast_manager_build_channel_state_string(payload->snapshot);
993         if (!channel_event_string) {
994                 return;
995         }
996
997         manager_event(EVENT_FLAG_CALL, "MusicOnHoldStart",
998                 "%s"
999                 "Class: %s\r\n",
1000                 ast_str_buffer(channel_event_string),
1001                 ast_json_string_get(ast_json_object_get(blob, "class")));
1002
1003 }
1004
1005 static void channel_moh_stop_cb(void *data, struct stasis_subscription *sub,
1006                 struct stasis_message *message)
1007 {
1008         struct ast_channel_blob *payload = stasis_message_data(message);
1009
1010         publish_basic_channel_event("MusicOnHoldStop", EVENT_FLAG_CALL, payload->snapshot);
1011 }
1012
1013 static void channel_monitor_start_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("MonitorStart", EVENT_FLAG_CALL, payload->snapshot);
1019 }
1020
1021 static void channel_monitor_stop_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("MonitorStop", EVENT_FLAG_CALL, payload->snapshot);
1027 }
1028
1029 /*!
1030  * \brief Callback processing messages for channel dialing
1031  */
1032 static void channel_dial_cb(void *data, struct stasis_subscription *sub,
1033         struct stasis_message *message)
1034 {
1035         struct ast_multi_channel_blob *obj = stasis_message_data(message);
1036         const char *dialstatus;
1037         const char *dialstring;
1038         const char *forward;
1039         struct ast_channel_snapshot *caller;
1040         struct ast_channel_snapshot *peer;
1041         RAII_VAR(struct ast_str *, caller_event_string, NULL, ast_free);
1042         RAII_VAR(struct ast_str *, peer_event_string, NULL, ast_free);
1043
1044         caller = ast_multi_channel_blob_get_channel(obj, "caller");
1045         peer = ast_multi_channel_blob_get_channel(obj, "peer");
1046
1047         /* Peer is required - otherwise, who are we dialing? */
1048         ast_assert(peer != NULL);
1049         peer_event_string = ast_manager_build_channel_state_string_prefix(peer, "Dest");
1050         if (!peer_event_string) {
1051                 return;
1052         }
1053
1054         if (caller && !(caller_event_string = ast_manager_build_channel_state_string(caller))) {
1055                 return;
1056         }
1057
1058         dialstatus = ast_json_string_get(ast_json_object_get(ast_multi_channel_blob_get_json(obj), "dialstatus"));
1059         dialstring = ast_json_string_get(ast_json_object_get(ast_multi_channel_blob_get_json(obj), "dialstring"));
1060         forward = ast_json_string_get(ast_json_object_get(ast_multi_channel_blob_get_json(obj), "forward"));
1061         if (ast_strlen_zero(dialstatus)) {
1062                 manager_event(EVENT_FLAG_CALL, "DialBegin",
1063                                 "%s"
1064                                 "%s"
1065                                 "DialString: %s\r\n",
1066                                 caller_event_string ? ast_str_buffer(caller_event_string) : "",
1067                                 ast_str_buffer(peer_event_string),
1068                                 S_OR(dialstring, "unknown"));
1069         } else {
1070                 int forwarded = !ast_strlen_zero(forward);
1071
1072                 manager_event(EVENT_FLAG_CALL, "DialEnd",
1073                                 "%s"
1074                                 "%s"
1075                                 "%s%s%s"
1076                                 "DialStatus: %s\r\n",
1077                                 caller_event_string ? ast_str_buffer(caller_event_string) : "",
1078                                 ast_str_buffer(peer_event_string),
1079                                 forwarded ? "Forward: " : "", S_OR(forward, ""), forwarded ? "\r\n" : "",
1080                                 S_OR(dialstatus, "unknown"));
1081         }
1082
1083 }
1084
1085 static void channel_hold_cb(void *data, struct stasis_subscription *sub,
1086         struct stasis_message *message)
1087 {
1088         struct ast_channel_blob *obj = stasis_message_data(message);
1089         struct ast_str *musicclass_string = ast_str_create(32);
1090         struct ast_str *channel_event_string;
1091
1092         if (!musicclass_string) {
1093                 return;
1094         }
1095
1096         channel_event_string = ast_manager_build_channel_state_string(obj->snapshot);
1097         if (!channel_event_string) {
1098                 ast_free(musicclass_string);
1099                 return;
1100         }
1101
1102         if (obj->blob) {
1103                 const char *musicclass;
1104
1105                 musicclass = ast_json_string_get(ast_json_object_get(obj->blob, "musicclass"));
1106
1107                 if (!ast_strlen_zero(musicclass)) {
1108                         ast_str_set(&musicclass_string, 0, "MusicClass: %s\r\n", musicclass);
1109                 }
1110         }
1111
1112         manager_event(EVENT_FLAG_CALL, "Hold",
1113                 "%s"
1114                 "%s",
1115                 ast_str_buffer(channel_event_string),
1116                 ast_str_buffer(musicclass_string));
1117
1118         ast_free(musicclass_string);
1119         ast_free(channel_event_string);
1120 }
1121
1122 static void channel_unhold_cb(void *data, struct stasis_subscription *sub,
1123         struct stasis_message *message)
1124 {
1125         struct ast_channel_blob *obj = stasis_message_data(message);
1126         struct ast_str *channel_event_string;
1127
1128         channel_event_string = ast_manager_build_channel_state_string(obj->snapshot);
1129         if (!channel_event_string) {
1130                 return;
1131         }
1132
1133         manager_event(EVENT_FLAG_CALL, "Unhold",
1134                 "%s",
1135                 ast_str_buffer(channel_event_string));
1136
1137         ast_free(channel_event_string);
1138 }
1139
1140 static void manager_channels_shutdown(void)
1141 {
1142         stasis_forward_cancel(topic_forwarder);
1143         topic_forwarder = NULL;
1144 }
1145
1146 int manager_channels_init(void)
1147 {
1148         int ret = 0;
1149         struct stasis_topic *manager_topic;
1150         struct stasis_topic *channel_topic;
1151         struct stasis_message_router *message_router;
1152
1153         manager_topic = ast_manager_get_topic();
1154         if (!manager_topic) {
1155                 return -1;
1156         }
1157         message_router = ast_manager_get_message_router();
1158         if (!message_router) {
1159                 return -1;
1160         }
1161         channel_topic = ast_channel_topic_all_cached();
1162         if (!channel_topic) {
1163                 return -1;
1164         }
1165
1166         topic_forwarder = stasis_forward_all(channel_topic, manager_topic);
1167         if (!topic_forwarder) {
1168                 return -1;
1169         }
1170
1171         ast_register_cleanup(manager_channels_shutdown);
1172
1173         ret |= stasis_message_router_add_cache_update(message_router,
1174                 ast_channel_snapshot_type(), channel_snapshot_update, NULL);
1175
1176         ret |= stasis_message_router_add(message_router,
1177                 ast_channel_dtmf_begin_type(), channel_dtmf_begin_cb, NULL);
1178
1179         ret |= stasis_message_router_add(message_router,
1180                 ast_channel_dtmf_end_type(), channel_dtmf_end_cb, NULL);
1181
1182         ret |= stasis_message_router_add(message_router,
1183                 ast_channel_hangup_request_type(), channel_hangup_request_cb,
1184                 NULL);
1185
1186         ret |= stasis_message_router_add(message_router,
1187                 ast_channel_dial_type(), channel_dial_cb, NULL);
1188
1189         ret |= stasis_message_router_add(message_router,
1190                 ast_channel_hold_type(), channel_hold_cb, NULL);
1191
1192         ret |= stasis_message_router_add(message_router,
1193                 ast_channel_unhold_type(), channel_unhold_cb, NULL);
1194
1195         ret |= stasis_message_router_add(message_router,
1196                 ast_channel_fax_type(), channel_fax_cb, NULL);
1197
1198         ret |= stasis_message_router_add(message_router,
1199                 ast_channel_chanspy_start_type(), channel_chanspy_start_cb,
1200                 NULL);
1201
1202         ret |= stasis_message_router_add(message_router,
1203                 ast_channel_chanspy_stop_type(), channel_chanspy_stop_cb, NULL);
1204
1205         ret |= stasis_message_router_add(message_router,
1206                 ast_channel_hangup_handler_type(), channel_hangup_handler_cb,
1207                 NULL);
1208
1209         ret |= stasis_message_router_add(message_router,
1210                 ast_channel_moh_start_type(), channel_moh_start_cb, NULL);
1211
1212         ret |= stasis_message_router_add(message_router,
1213                 ast_channel_moh_stop_type(), channel_moh_stop_cb, NULL);
1214
1215         ret |= stasis_message_router_add(message_router,
1216                 ast_channel_monitor_start_type(), channel_monitor_start_cb,
1217                 NULL);
1218
1219         ret |= stasis_message_router_add(message_router,
1220                 ast_channel_monitor_stop_type(), channel_monitor_stop_cb, NULL);
1221
1222         /* If somehow we failed to add any routes, just shut down the whole
1223          * thing and fail it.
1224          */
1225         if (ret) {
1226                 manager_channels_shutdown();
1227                 return -1;
1228         }
1229
1230         return 0;
1231 }
1232