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