Asterisk - The Open Source Telephony Project GIT-master-55f4e6d
manager.c
Go to the documentation of this file.
1/*
2 * Asterisk -- An open source telephony toolkit.
3 *
4 * Copyright (C) 1999 - 2006, Digium, Inc.
5 *
6 * Mark Spencer <markster@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
22 *
23 * \author Mark Spencer <markster@digium.com>
24 *
25 * OpenSSL http://www.openssl.org - for AMI/SSL
26 *
27 * At the moment this file contains a number of functions, namely:
28 *
29 * - data structures storing AMI state
30 * - AMI-related API functions, used by internal asterisk components
31 * - handlers for AMI-related CLI functions
32 * - handlers for AMI functions (available through the AMI socket)
33 * - the code for the main AMI listener thread and individual session threads
34 * - the http handlers invoked for AMI-over-HTTP by the threads in main/http.c
35 *
36 * \ref amiconf
37 */
38
39/*! \li \ref manager.c uses the configuration file \ref manager.conf and \ref users.conf
40 * \addtogroup configuration_file
41 */
42
43/*! \page manager.conf manager.conf
44 * \verbinclude manager.conf.sample
45 */
46
47/*! \page users.conf users.conf
48 * \verbinclude users.conf.sample
49 */
50
51/*** MODULEINFO
52 <support_level>core</support_level>
53 ***/
54
55#include "asterisk.h"
56
57#include "asterisk/paths.h" /* use various ast_config_AST_* */
58#include <ctype.h>
59#include <sys/time.h>
60#include <signal.h>
61#include <sys/mman.h>
62#include <sys/types.h>
63#include <regex.h>
64
65#include "asterisk/channel.h"
66#include "asterisk/file.h"
67#include "asterisk/manager.h"
68#include "asterisk/module.h"
69#include "asterisk/config.h"
70#include "asterisk/callerid.h"
71#include "asterisk/core_local.h"
72#include "asterisk/lock.h"
73#include "asterisk/cli.h"
74#include "asterisk/app.h"
75#include "asterisk/mwi.h"
76#include "asterisk/pbx.h"
77#include "asterisk/md5.h"
78#include "asterisk/acl.h"
79#include "asterisk/utils.h"
80#include "asterisk/tcptls.h"
81#include "asterisk/http.h"
85#include "asterisk/term.h"
86#include "asterisk/astobj2.h"
87#include "asterisk/features.h"
89#include "asterisk/aoc.h"
90#include "asterisk/strings.h"
96#include "asterisk/test.h"
97#include "asterisk/json.h"
98#include "asterisk/bridge.h"
100#include "asterisk/rtp_engine.h"
102#include "asterisk/translate.h"
104#include "asterisk/message.h"
105
106/*** DOCUMENTATION
107 <manager name="Ping" language="en_US">
108 <synopsis>
109 Keepalive command.
110 </synopsis>
111 <syntax>
112 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
113 </syntax>
114 <description>
115 <para>A 'Ping' action will elicit a 'Pong' response. Used to keep the
116 manager connection open.</para>
117 </description>
118 </manager>
119 <manager name="Events" language="en_US">
120 <synopsis>
121 Control Event Flow.
122 </synopsis>
123 <syntax>
124 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
125 <parameter name="EventMask" required="true">
126 <enumlist>
127 <enum name="on">
128 <para>If all events should be sent.</para>
129 </enum>
130 <enum name="off">
131 <para>If no events should be sent.</para>
132 </enum>
133 <enum name="system,call,log,...">
134 <para>To select which flags events should have to be sent.</para>
135 </enum>
136 </enumlist>
137 </parameter>
138 </syntax>
139 <description>
140 <para>Enable/Disable sending of events to this manager client.</para>
141 </description>
142 </manager>
143 <manager name="Logoff" language="en_US">
144 <synopsis>
145 Logoff Manager.
146 </synopsis>
147 <syntax>
148 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
149 </syntax>
150 <description>
151 <para>Logoff the current manager session.</para>
152 </description>
153 <see-also>
154 <ref type="manager">Login</ref>
155 </see-also>
156 </manager>
157 <manager name="Login" language="en_US">
158 <synopsis>
159 Login Manager.
160 </synopsis>
161 <syntax>
162 <parameter name="ActionID">
163 <para>ActionID for this transaction. Will be returned.</para>
164 </parameter>
165 <parameter name="Username" required="true">
166 <para>Username to login with as specified in manager.conf.</para>
167 </parameter>
168 <parameter name="AuthType">
169 <para>Authorization type. Valid values are:</para>
170 <enumlist>
171 <enum name="plain"><para>Plain text secret. (default)</para></enum>
172 <enum name="MD5"><para>MD5 hashed secret.</para></enum>
173 </enumlist>
174 </parameter>
175 <parameter name="Secret">
176 <para>Plain text secret to login with as specified in manager.conf.</para>
177 </parameter>
178 <parameter name="Key">
179 <para>Key to use with MD5 authentication. To create the key, you must
180 initialize a new MD5 hash, call the <literal>Challenge</literal> AMI action,
181 update the hash with the response, then update the hash with the secret as specified
182 in manager.conf. The key value must be the final result of the hash
183 as a 32 character lower-case hex string without any "0x" prepended.
184 See the description for an example of creating a key in Python.</para>
185 </parameter>
186 <parameter name="Events">
187 <xi:include xpointer="xpointer(/docs/manager[@name='Events']/syntax/parameter[@name='EventMask']/enumlist)" />
188 </parameter>
189 </syntax>
190 <description>
191 <para>Login Manager.</para>
192 <example title="Create an MD5 Key in Python">
193 import hashlib
194 m = hashlib.md5()
195 m.update(response_from_challenge)
196 m.update(your_secret)
197 key = m.hexdigest()
198 ## '031edd7d41651593c5fe5c006fa5752b'
199 </example>
200 </description>
201 <see-also>
202 <ref type="manager">Challenge</ref>
203 <ref type="manager">Logoff</ref>
204 </see-also>
205 </manager>
206 <manager name="Challenge" language="en_US">
207 <synopsis>
208 Generate Challenge for MD5 Auth.
209 </synopsis>
210 <syntax>
211 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
212 <parameter name="AuthType" required="true">
213 <para>Digest algorithm to use in the challenge. Valid values are:</para>
214 <enumlist>
215 <enum name="MD5" />
216 </enumlist>
217 </parameter>
218 </syntax>
219 <description>
220 <para>Generate a challenge for MD5 authentication.</para>
221 </description>
222 </manager>
223 <manager name="Hangup" language="en_US">
224 <synopsis>
225 Hangup channel.
226 </synopsis>
227 <syntax>
228 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
229 <parameter name="Channel" required="true">
230 <para>The exact channel name to be hungup, or to use a regular expression, set this parameter to: /regex/</para>
231 <para>Example exact channel: SIP/provider-0000012a</para>
232 <para>Example regular expression: /^SIP/provider-.*$/</para>
233 </parameter>
234 <parameter name="Cause">
235 <para>Numeric hangup cause.</para>
236 </parameter>
237 </syntax>
238 <description>
239 <para>Hangup a channel.</para>
240 </description>
241 </manager>
242 <manager name="Status" language="en_US">
243 <synopsis>
244 List channel status.
245 </synopsis>
246 <syntax>
247 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
248 <parameter name="Channel" required="false">
249 <para>The name of the channel to query for status.</para>
250 </parameter>
251 <parameter name="Variables">
252 <para>Comma <literal>,</literal> separated list of variable to include.</para>
253 </parameter>
254 <parameter name="AllVariables">
255 <para>If set to "true", the Status event will include all channel variables for
256 the requested channel(s).</para>
257 <enumlist>
258 <enum name="true"/>
259 <enum name="false"/>
260 </enumlist>
261 </parameter>
262 </syntax>
263 <description>
264 <para>Will return the status information of each channel along with the
265 value for the specified channel variables.</para>
266 </description>
267 <responses>
268 <list-elements>
269 <xi:include xpointer="xpointer(/docs/managerEvent[@name='Status'])" />
270 </list-elements>
271 <xi:include xpointer="xpointer(/docs/managerEvent[@name='StatusComplete'])" />
272 </responses>
273 </manager>
274 <managerEvent language="en_US" name="Status">
275 <managerEventInstance class="EVENT_FLAG_CALL">
276 <synopsis>Raised in response to a Status command.</synopsis>
277 <syntax>
278 <parameter name="ActionID" required="false"/>
279 <channel_snapshot/>
280 <parameter name="Type">
281 <para>Type of channel</para>
282 </parameter>
283 <parameter name="DNID">
284 <para>Dialed number identifier</para>
285 </parameter>
286 <parameter name="EffectiveConnectedLineNum">
287 </parameter>
288 <parameter name="EffectiveConnectedLineName">
289 </parameter>
290 <parameter name="TimeToHangup">
291 <para>Absolute lifetime of the channel</para>
292 </parameter>
293 <parameter name="BridgeID">
294 <para>Identifier of the bridge the channel is in, may be empty if not in one</para>
295 </parameter>
296 <parameter name="Application">
297 <para>Application currently executing on the channel</para>
298 </parameter>
299 <parameter name="Data">
300 <para>Data given to the currently executing channel</para>
301 </parameter>
302 <parameter name="Nativeformats">
303 <para>Media formats the connected party is willing to send or receive</para>
304 </parameter>
305 <parameter name="Readformat">
306 <para>Media formats that frames from the channel are received in</para>
307 </parameter>
308 <parameter name="Readtrans">
309 <para>Translation path for media received in native formats</para>
310 </parameter>
311 <parameter name="Writeformat">
312 <para>Media formats that frames to the channel are accepted in</para>
313 </parameter>
314 <parameter name="Writetrans">
315 <para>Translation path for media sent to the connected party</para>
316 </parameter>
317 <parameter name="Callgroup">
318 <para>Configured call group on the channel</para>
319 </parameter>
320 <parameter name="Pickupgroup">
321 <para>Configured pickup group on the channel</para>
322 </parameter>
323 <parameter name="Seconds">
324 <para>Number of seconds the channel has been active</para>
325 </parameter>
326 </syntax>
327 <see-also>
328 <ref type="manager">Status</ref>
329 </see-also>
330 </managerEventInstance>
331 </managerEvent>
332 <managerEvent language="en_US" name="StatusComplete">
333 <managerEventInstance class="EVENT_FLAG_CALL">
334 <synopsis>Raised in response to a Status command.</synopsis>
335 <syntax>
336 <parameter name="Items">
337 <para>Number of Status events returned</para>
338 </parameter>
339 </syntax>
340 <see-also>
341 <ref type="manager">Status</ref>
342 </see-also>
343 </managerEventInstance>
344 </managerEvent>
345 <manager name="Setvar" language="en_US">
346 <synopsis>
347 Sets a channel variable or function value.
348 </synopsis>
349 <syntax>
350 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
351 <parameter name="Channel">
352 <para>Channel to set variable for.</para>
353 </parameter>
354 <parameter name="Variable" required="true">
355 <para>Variable name, function or expression.</para>
356 </parameter>
357 <parameter name="Value" required="true">
358 <para>Variable or function value.</para>
359 </parameter>
360 </syntax>
361 <description>
362 <para>This command can be used to set the value of channel variables or dialplan
363 functions.</para>
364 <note>
365 <para>If a channel name is not provided then the variable is considered global.</para>
366 </note>
367 </description>
368 <see-also>
369 <ref type="manager">Getvar</ref>
370 </see-also>
371 </manager>
372 <manager name="Getvar" language="en_US">
373 <synopsis>
374 Gets a channel variable or function value.
375 </synopsis>
376 <syntax>
377 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
378 <parameter name="Channel">
379 <para>Channel to read variable from.</para>
380 </parameter>
381 <parameter name="Variable" required="true">
382 <para>Variable name, function or expression.</para>
383 </parameter>
384 </syntax>
385 <description>
386 <para>Get the value of a channel variable or function return.</para>
387 <note>
388 <para>If a channel name is not provided then the variable is considered global.</para>
389 </note>
390 </description>
391 <see-also>
392 <ref type="manager">Setvar</ref>
393 </see-also>
394 </manager>
395 <manager name="GetConfig" language="en_US">
396 <synopsis>
397 Retrieve configuration.
398 </synopsis>
399 <syntax>
400 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
401 <parameter name="Filename" required="true">
402 <para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
403 </parameter>
404 <parameter name="Category">
405 <para>Category in configuration file.</para>
406 </parameter>
407 <parameter name="Filter">
408 <para>A comma separated list of
409 <replaceable>name_regex</replaceable>=<replaceable>value_regex</replaceable>
410 expressions which will cause only categories whose variables match all expressions
411 to be considered. The special variable name <literal>TEMPLATES</literal>
412 can be used to control whether templates are included. Passing
413 <literal>include</literal> as the value will include templates
414 along with normal categories. Passing
415 <literal>restrict</literal> as the value will restrict the operation to
416 ONLY templates. Not specifying a <literal>TEMPLATES</literal> expression
417 results in the default behavior which is to not include templates.</para>
418 </parameter>
419 </syntax>
420 <description>
421 <para>This action will dump the contents of a configuration
422 file by category and contents or optionally by specified category only.
423 In the case where a category name is non-unique, a filter may be specified
424 to match only categories with matching variable values.</para>
425 </description>
426 <see-also>
427 <ref type="manager">GetConfigJSON</ref>
428 <ref type="manager">UpdateConfig</ref>
429 <ref type="manager">CreateConfig</ref>
430 <ref type="manager">ListCategories</ref>
431 </see-also>
432 </manager>
433 <manager name="GetConfigJSON" language="en_US">
434 <synopsis>
435 Retrieve configuration (JSON format).
436 </synopsis>
437 <syntax>
438 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
439 <parameter name="Filename" required="true">
440 <para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
441 </parameter>
442 <parameter name="Category">
443 <para>Category in configuration file.</para>
444 </parameter>
445 <parameter name="Filter">
446 <xi:include xpointer="xpointer(/docs/manager[@name='GetConfig']/syntax/parameter[@name='Filter']/para[1])" />
447 </parameter>
448 </syntax>
449 <description>
450 <para>This action will dump the contents of a configuration file by category
451 and contents in JSON format or optionally by specified category only.
452 This only makes sense to be used using rawman over the HTTP interface.
453 In the case where a category name is non-unique, a filter may be specified
454 to match only categories with matching variable values.</para>
455 </description>
456 <see-also>
457 <ref type="manager">GetConfig</ref>
458 <ref type="manager">UpdateConfig</ref>
459 <ref type="manager">CreateConfig</ref>
460 <ref type="manager">ListCategories</ref>
461 </see-also>
462 </manager>
463 <manager name="UpdateConfig" language="en_US">
464 <synopsis>
465 Update basic configuration.
466 </synopsis>
467 <syntax>
468 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
469 <parameter name="SrcFilename" required="true">
470 <para>Configuration filename to read (e.g. <filename>foo.conf</filename>).</para>
471 </parameter>
472 <parameter name="DstFilename" required="true">
473 <para>Configuration filename to write (e.g. <filename>foo.conf</filename>)</para>
474 </parameter>
475 <parameter name="Reload">
476 <para>Whether or not a reload should take place (or name of specific module).</para>
477 </parameter>
478 <parameter name="PreserveEffectiveContext">
479 <para>Whether the effective category contents should be preserved on template change. Default is true (pre 13.2 behavior).</para>
480 </parameter>
481 <parameter name="Action-000000">
482 <para>Action to take.</para>
483 <para>0's represent 6 digit number beginning with 000000.</para>
484 <enumlist>
485 <enum name="NewCat" />
486 <enum name="RenameCat" />
487 <enum name="DelCat" />
488 <enum name="EmptyCat" />
489 <enum name="Update" />
490 <enum name="Delete" />
491 <enum name="Append" />
492 <enum name="Insert" />
493 </enumlist>
494 </parameter>
495 <parameter name="Cat-000000">
496 <para>Category to operate on.</para>
497 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-000000']/para[2])" />
498 </parameter>
499 <parameter name="Var-000000">
500 <para>Variable to work on.</para>
501 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-000000']/para[2])" />
502 </parameter>
503 <parameter name="Value-000000">
504 <para>Value to work on.</para>
505 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-000000']/para[2])" />
506 </parameter>
507 <parameter name="Match-000000">
508 <para>Extra match required to match line.</para>
509 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-000000']/para[2])" />
510 </parameter>
511 <parameter name="Line-000000">
512 <para>Line in category to operate on (used with delete and insert actions).</para>
513 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-000000']/para[2])" />
514 </parameter>
515 <parameter name="Options-000000">
516 <para>A comma separated list of action-specific options.</para>
517 <enumlist>
518 <enum name="NewCat"><para>One or more of the following... </para>
519 <enumlist>
520 <enum name="allowdups"><para>Allow duplicate category names.</para></enum>
521 <enum name="template"><para>This category is a template.</para></enum>
522 <enum name="inherit=&quot;template[,...]&quot;"><para>Templates from which to inherit.</para></enum>
523 </enumlist>
524 </enum>
525 </enumlist>
526 <para> </para>
527 <para>The following actions share the same options...</para>
528 <enumlist>
529 <enum name="RenameCat"/>
530 <enum name="DelCat"/>
531 <enum name="EmptyCat"/>
532 <enum name="Update"/>
533 <enum name="Delete"/>
534 <enum name="Append"/>
535 <enum name="Insert"><para> </para>
536 <enumlist>
537 <enum name="catfilter=&quot;&lt;expression&gt;[,...]&quot;"><para> </para>
538 <xi:include xpointer="xpointer(/docs/manager[@name='GetConfig']/syntax/parameter[@name='Filter']/para[1])" />
539 <para><literal>catfilter</literal> is most useful when a file
540 contains multiple categories with the same name and you wish to
541 operate on specific ones instead of all of them.</para>
542 </enum>
543 </enumlist>
544 </enum>
545 </enumlist>
546 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-000000']/para[2])" />
547 </parameter>
548 </syntax>
549 <description>
550 <para>This action will modify, create, or delete configuration elements
551 in Asterisk configuration files.</para>
552 </description>
553 <see-also>
554 <ref type="manager">GetConfig</ref>
555 <ref type="manager">GetConfigJSON</ref>
556 <ref type="manager">CreateConfig</ref>
557 <ref type="manager">ListCategories</ref>
558 </see-also>
559 </manager>
560 <manager name="CreateConfig" language="en_US">
561 <synopsis>
562 Creates an empty file in the configuration directory.
563 </synopsis>
564 <syntax>
565 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
566 <parameter name="Filename" required="true">
567 <para>The configuration filename to create (e.g. <filename>foo.conf</filename>).</para>
568 </parameter>
569 </syntax>
570 <description>
571 <para>This action will create an empty file in the configuration
572 directory. This action is intended to be used before an UpdateConfig
573 action.</para>
574 </description>
575 <see-also>
576 <ref type="manager">GetConfig</ref>
577 <ref type="manager">GetConfigJSON</ref>
578 <ref type="manager">UpdateConfig</ref>
579 <ref type="manager">ListCategories</ref>
580 </see-also>
581 </manager>
582 <manager name="ListCategories" language="en_US">
583 <synopsis>
584 List categories in configuration file.
585 </synopsis>
586 <syntax>
587 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
588 <parameter name="Filename" required="true">
589 <para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
590 </parameter>
591 </syntax>
592 <description>
593 <para>This action will dump the categories in a given file.</para>
594 </description>
595 <see-also>
596 <ref type="manager">GetConfig</ref>
597 <ref type="manager">GetConfigJSON</ref>
598 <ref type="manager">UpdateConfig</ref>
599 <ref type="manager">CreateConfig</ref>
600 </see-also>
601 </manager>
602 <manager name="Redirect" language="en_US">
603 <synopsis>
604 Redirect (transfer) a call.
605 </synopsis>
606 <syntax>
607 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
608 <parameter name="Channel" required="true">
609 <para>Channel to redirect.</para>
610 </parameter>
611 <parameter name="ExtraChannel">
612 <para>Second call leg to transfer (optional).</para>
613 </parameter>
614 <parameter name="Exten" required="true">
615 <para>Extension to transfer to.</para>
616 </parameter>
617 <parameter name="ExtraExten">
618 <para>Extension to transfer extrachannel to (optional).</para>
619 </parameter>
620 <parameter name="Context" required="true">
621 <para>Context to transfer to.</para>
622 </parameter>
623 <parameter name="ExtraContext">
624 <para>Context to transfer extrachannel to (optional).</para>
625 </parameter>
626 <parameter name="Priority" required="true">
627 <para>Priority to transfer to.</para>
628 </parameter>
629 <parameter name="ExtraPriority">
630 <para>Priority to transfer extrachannel to (optional).</para>
631 </parameter>
632 </syntax>
633 <description>
634 <para>Redirect (transfer) a call.</para>
635 </description>
636 <see-also>
637 <ref type="manager">BlindTransfer</ref>
638 </see-also>
639 </manager>
640 <manager name="Atxfer" language="en_US">
641 <synopsis>
642 Attended transfer.
643 </synopsis>
644 <syntax>
645 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
646 <parameter name="Channel" required="true">
647 <para>Transferer's channel.</para>
648 </parameter>
649 <parameter name="Exten" required="true">
650 <para>Extension to transfer to.</para>
651 </parameter>
652 <parameter name="Context">
653 <para>Context to transfer to.</para>
654 </parameter>
655 </syntax>
656 <description>
657 <para>Attended transfer.</para>
658 </description>
659 <see-also>
660 <ref type="managerEvent">AttendedTransfer</ref>
661 </see-also>
662 </manager>
663 <manager name="CancelAtxfer" language="en_US">
664 <since>
665 <version>13.18.0</version>
666 <version>14.7.0</version>
667 <version>15.1.0</version>
668 <version>16.0.0</version>
669 </since>
670 <synopsis>
671 Cancel an attended transfer.
672 </synopsis>
673 <syntax>
674 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
675 <parameter name="Channel" required="true">
676 <para>The transferer channel.</para>
677 </parameter>
678 </syntax>
679 <description>
680 <para>Cancel an attended transfer. Note, this uses the configured cancel attended transfer
681 feature option (atxferabort) to cancel the transfer. If not available this action will fail.
682 </para>
683 </description>
684 <see-also>
685 <ref type="managerEvent">AttendedTransfer</ref>
686 </see-also>
687 </manager>
688 <manager name="Originate" language="en_US">
689 <synopsis>
690 Originate a call.
691 </synopsis>
692 <syntax>
693 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
694 <parameter name="Channel" required="true">
695 <para>Channel name to call.</para>
696 </parameter>
697 <parameter name="Exten">
698 <para>Extension to use (requires <literal>Context</literal> and
699 <literal>Priority</literal>)</para>
700 </parameter>
701 <parameter name="Context">
702 <para>Context to use (requires <literal>Exten</literal> and
703 <literal>Priority</literal>)</para>
704 </parameter>
705 <parameter name="Priority">
706 <para>Priority to use (requires <literal>Exten</literal> and
707 <literal>Context</literal>)</para>
708 </parameter>
709 <parameter name="Application">
710 <para>Application to execute.</para>
711 </parameter>
712 <parameter name="Data">
713 <para>Data to use (requires <literal>Application</literal>).</para>
714 </parameter>
715 <parameter name="Timeout" default="30000">
716 <para>How long to wait for call to be answered (in ms.).</para>
717 </parameter>
718 <parameter name="CallerID">
719 <para>Caller ID to be set on the outgoing channel.</para>
720 </parameter>
721 <parameter name="Variable">
722 <para>Channel variable to set, multiple Variable: headers are allowed.</para>
723 </parameter>
724 <parameter name="Account">
725 <para>Account code.</para>
726 </parameter>
727 <parameter name="EarlyMedia">
728 <para>Set to <literal>true</literal> to force call bridge on early media..</para>
729 </parameter>
730 <parameter name="Async">
731 <para>Set to <literal>true</literal> for fast origination.</para>
732 </parameter>
733 <parameter name="Codecs">
734 <para>Comma-separated list of codecs to use for this call.</para>
735 </parameter>
736 <parameter name="ChannelId">
737 <para>Channel UniqueId to be set on the channel.</para>
738 </parameter>
739 <parameter name="OtherChannelId">
740 <para>Channel UniqueId to be set on the second local channel.</para>
741 </parameter>
742 <parameter name="PreDialGoSub">
743 <para>PreDialGoSub Context,Extension,Priority to set options/headers needed before start the outgoing extension</para>
744 </parameter>
745 </syntax>
746 <description>
747 <para>Generates an outgoing call to a
748 <replaceable>Extension</replaceable>/<replaceable>Context</replaceable>/<replaceable>Priority</replaceable>
749 or <replaceable>Application</replaceable>/<replaceable>Data</replaceable></para>
750 </description>
751 <see-also>
752 <ref type="managerEvent">OriginateResponse</ref>
753 </see-also>
754 </manager>
755 <managerEvent language="en_US" name="OriginateResponse">
756 <managerEventInstance class="EVENT_FLAG_CALL">
757 <synopsis>Raised in response to an Originate command.</synopsis>
758 <syntax>
759 <parameter name="ActionID" required="false"/>
760 <parameter name="Response">
761 <enumlist>
762 <enum name="Failure"/>
763 <enum name="Success"/>
764 </enumlist>
765 </parameter>
766 <parameter name="Channel"/>
767 <parameter name="Context"/>
768 <parameter name="Exten"/>
769 <parameter name="Application"/>
770 <parameter name="Data"/>
771 <parameter name="Reason"/>
772 <parameter name="Uniqueid"/>
773 <parameter name="CallerIDNum"/>
774 <parameter name="CallerIDName"/>
775 </syntax>
776 <see-also>
777 <ref type="manager">Originate</ref>
778 </see-also>
779 </managerEventInstance>
780 </managerEvent>
781 <manager name="Command" language="en_US">
782 <synopsis>
783 Execute Asterisk CLI Command.
784 </synopsis>
785 <syntax>
786 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
787 <parameter name="Command" required="true">
788 <para>Asterisk CLI command to run.</para>
789 </parameter>
790 </syntax>
791 <description>
792 <para>Run a CLI command.</para>
793 </description>
794 </manager>
795 <manager name="ExtensionState" language="en_US">
796 <synopsis>
797 Check Extension Status.
798 </synopsis>
799 <syntax>
800 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
801 <parameter name="Exten" required="true">
802 <para>Extension to check state on.</para>
803 </parameter>
804 <parameter name="Context" required="true">
805 <para>Context for extension.</para>
806 </parameter>
807 </syntax>
808 <description>
809 <para>Report the extension state for given extension. If the extension has a hint,
810 will use devicestate to check the status of the device connected to the extension.</para>
811 <para>Will return an <literal>Extension Status</literal> message. The response will include
812 the hint for the extension and the status.</para>
813 </description>
814 <see-also>
815 <ref type="managerEvent">ExtensionStatus</ref>
816 </see-also>
817 </manager>
818 <manager name="PresenceState" language="en_US">
819 <synopsis>
820 Check Presence State
821 </synopsis>
822 <syntax>
823 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
824 <parameter name="Provider" required="true">
825 <para>Presence Provider to check the state of</para>
826 </parameter>
827 </syntax>
828 <description>
829 <para>Report the presence state for the given presence provider.</para>
830 <para>Will return a <literal>Presence State</literal> message. The response will include the
831 presence state and, if set, a presence subtype and custom message.</para>
832 </description>
833 <see-also>
834 <ref type="managerEvent">PresenceStatus</ref>
835 </see-also>
836 </manager>
837 <manager name="AbsoluteTimeout" language="en_US">
838 <synopsis>
839 Set absolute timeout.
840 </synopsis>
841 <syntax>
842 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
843 <parameter name="Channel" required="true">
844 <para>Channel name to hangup.</para>
845 </parameter>
846 <parameter name="Timeout" required="true">
847 <para>Maximum duration of the call (sec).</para>
848 </parameter>
849 </syntax>
850 <description>
851 <para>Hangup a channel after a certain time. Acknowledges set time with
852 <literal>Timeout Set</literal> message.</para>
853 </description>
854 </manager>
855 <manager name="MailboxStatus" language="en_US">
856 <synopsis>
857 Check mailbox.
858 </synopsis>
859 <syntax>
860 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
861 <parameter name="Mailbox" required="true">
862 <para>Full mailbox ID <replaceable>mailbox</replaceable>@<replaceable>vm-context</replaceable>.</para>
863 </parameter>
864 </syntax>
865 <description>
866 <para>Checks a voicemail account for status.</para>
867 <para>Returns whether there are messages waiting.</para>
868 <para>Message: Mailbox Status.</para>
869 <para>Mailbox: <replaceable>mailboxid</replaceable>.</para>
870 <para>Waiting: <literal>0</literal> if messages waiting, <literal>1</literal>
871 if no messages waiting.</para>
872 </description>
873 <see-also>
874 <ref type="manager">MailboxCount</ref>
875 </see-also>
876 </manager>
877 <manager name="MailboxCount" language="en_US">
878 <synopsis>
879 Check Mailbox Message Count.
880 </synopsis>
881 <syntax>
882 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
883 <parameter name="Mailbox" required="true">
884 <para>Full mailbox ID <replaceable>mailbox</replaceable>@<replaceable>vm-context</replaceable>.</para>
885 </parameter>
886 </syntax>
887 <description>
888 <para>Checks a voicemail account for new messages.</para>
889 <para>Returns number of urgent, new and old messages.</para>
890 <para>Message: Mailbox Message Count</para>
891 <para>Mailbox: <replaceable>mailboxid</replaceable></para>
892 <para>UrgentMessages: <replaceable>count</replaceable></para>
893 <para>NewMessages: <replaceable>count</replaceable></para>
894 <para>OldMessages: <replaceable>count</replaceable></para>
895 </description>
896 <see-also>
897 <ref type="manager">MailboxStatus</ref>
898 </see-also>
899 </manager>
900 <manager name="ListCommands" language="en_US">
901 <synopsis>
902 List available manager commands.
903 </synopsis>
904 <syntax>
905 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
906 </syntax>
907 <description>
908 <para>Returns the action name and synopsis for every action that
909 is available to the user.</para>
910 </description>
911 </manager>
912 <manager name="SendText" language="en_US">
913 <synopsis>
914 Sends a text message to channel. A content type can be optionally specified. If not set
915 it is set to an empty string allowing a custom handler to default it as it sees fit.
916 </synopsis>
917 <syntax>
918 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
919 <parameter name="Channel" required="true">
920 <para>Channel to send message to.</para>
921 </parameter>
922 <parameter name="Message" required="true">
923 <para>Message to send.</para>
924 </parameter>
925 <parameter name="Content-Type" required="false" default="">
926 <para>The type of content in the message</para>
927 </parameter>
928 </syntax>
929 <description>
930 <para>Sends A Text Message to a channel while in a call.</para>
931 </description>
932 <see-also>
933 <ref type="application">SendText</ref>
934 </see-also>
935 </manager>
936 <manager name="UserEvent" language="en_US">
937 <synopsis>
938 Send an arbitrary event.
939 </synopsis>
940 <syntax>
941 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
942 <parameter name="UserEvent" required="true">
943 <para>Event string to send.</para>
944 </parameter>
945 <parameter name="Header1">
946 <para>Content1.</para>
947 </parameter>
948 <parameter name="HeaderN">
949 <para>ContentN.</para>
950 </parameter>
951 </syntax>
952 <description>
953 <para>Send an event to manager sessions.</para>
954 </description>
955 <see-also>
956 <ref type="managerEvent">UserEvent</ref>
957 <ref type="application">UserEvent</ref>
958 </see-also>
959 </manager>
960 <manager name="WaitEvent" language="en_US">
961 <synopsis>
962 Wait for an event to occur.
963 </synopsis>
964 <syntax>
965 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
966 <parameter name="Timeout" required="true">
967 <para>Maximum time (in seconds) to wait for events, <literal>-1</literal> means forever.</para>
968 </parameter>
969 </syntax>
970 <description>
971 <para>This action will elicit a <literal>Success</literal> response. Whenever
972 a manager event is queued. Once WaitEvent has been called on an HTTP manager
973 session, events will be generated and queued.</para>
974 </description>
975 </manager>
976 <manager name="CoreSettings" language="en_US">
977 <synopsis>
978 Show PBX core settings (version etc).
979 </synopsis>
980 <syntax>
981 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
982 </syntax>
983 <description>
984 <para>Query for Core PBX settings.</para>
985 </description>
986 </manager>
987 <manager name="CoreStatus" language="en_US">
988 <synopsis>
989 Show PBX core status variables.
990 </synopsis>
991 <syntax>
992 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
993 </syntax>
994 <description>
995 <para>Query for Core PBX status.</para>
996 </description>
997 </manager>
998 <manager name="Reload" language="en_US">
999 <synopsis>
1000 Send a reload event.
1001 </synopsis>
1002 <syntax>
1003 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
1004 <parameter name="Module">
1005 <para>Name of the module to reload.</para>
1006 </parameter>
1007 </syntax>
1008 <description>
1009 <para>Send a reload event.</para>
1010 </description>
1011 <see-also>
1012 <ref type="manager">ModuleLoad</ref>
1013 </see-also>
1014 </manager>
1015 <managerEvent language="en_US" name="CoreShowChannel">
1016 <managerEventInstance class="EVENT_FLAG_CALL">
1017 <synopsis>Raised in response to a CoreShowChannels command.</synopsis>
1018 <syntax>
1019 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
1020 <channel_snapshot/>
1021 <parameter name="BridgeId">
1022 <para>Identifier of the bridge the channel is in, may be empty if not in one</para>
1023 </parameter>
1024 <parameter name="Application">
1025 <para>Application currently executing on the channel</para>
1026 </parameter>
1027 <parameter name="ApplicationData">
1028 <para>Data given to the currently executing application</para>
1029 </parameter>
1030 <parameter name="Duration">
1031 <para>The amount of time the channel has existed</para>
1032 </parameter>
1033 </syntax>
1034 <see-also>
1035 <ref type="manager">CoreShowChannels</ref>
1036 <ref type="managerEvent">CoreShowChannelsComplete</ref>
1037 </see-also>
1038 </managerEventInstance>
1039 </managerEvent>
1040 <managerEvent language="en_US" name="CoreShowChannelsComplete">
1041 <managerEventInstance class="EVENT_FLAG_CALL">
1042 <synopsis>Raised at the end of the CoreShowChannel list produced by the CoreShowChannels command.</synopsis>
1043 <syntax>
1044 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
1045 <parameter name="EventList">
1046 <para>Conveys the status of the command reponse list</para>
1047 </parameter>
1048 <parameter name="ListItems">
1049 <para>The total number of list items produced</para>
1050 </parameter>
1051 </syntax>
1052 <see-also>
1053 <ref type="manager">CoreShowChannels</ref>
1054 <ref type="managerEvent">CoreShowChannel</ref>
1055 </see-also>
1056 </managerEventInstance>
1057 </managerEvent>
1058 <manager name="CoreShowChannels" language="en_US">
1059 <synopsis>
1060 List currently active channels.
1061 </synopsis>
1062 <syntax>
1063 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
1064 </syntax>
1065 <description>
1066 <para>List currently defined channels and some information about them.</para>
1067 </description>
1068 <responses>
1069 <list-elements>
1070 <xi:include xpointer="xpointer(/docs/managerEvent[@name='CoreShowChannel'])" />
1071 </list-elements>
1072 <xi:include xpointer="xpointer(/docs/managerEvent[@name='CoreShowChannelsComplete'])" />
1073 </responses>
1074 </manager>
1075 <managerEvent language="en_US" name="CoreShowChannelMapComplete">
1076 <managerEventInstance class="EVENT_FLAG_CALL">
1077 <synopsis>Raised at the end of the CoreShowChannelMap list produced by the CoreShowChannelMap command.</synopsis>
1078 <syntax>
1079 <parameter name="EventList">
1080 <para>Conveys the status of the command response list</para>
1081 </parameter>
1082 <parameter name="ListItems">
1083 <para>The total number of list items produced</para>
1084 </parameter>
1085 </syntax>
1086 </managerEventInstance>
1087 </managerEvent>
1088 <manager name="CoreShowChannelMap" language="en_US">
1089 <synopsis>
1090 List all channels connected to the specified channel.
1091 </synopsis>
1092 <syntax>
1093 <parameter name="Channel">
1094 <para>The channel to get the mapping for. Requires a channel name.</para>
1095 </parameter>
1096 </syntax>
1097 <description>
1098 <para>List all channels currently connected to the specified channel. This can be any channel, including
1099 Local channels, and Local channels will be followed through to their other half.</para>
1100 </description>
1101 </manager>
1102 <manager name="LoggerRotate" language="en_US">
1103 <synopsis>
1104 Reload and rotate the Asterisk logger.
1105 </synopsis>
1106 <syntax>
1107 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
1108 </syntax>
1109 <description>
1110 <para>Reload and rotate the logger. Analogous to the CLI command 'logger rotate'.</para>
1111 </description>
1112 </manager>
1113 <manager name="ModuleLoad" language="en_US">
1114 <synopsis>
1115 Module management.
1116 </synopsis>
1117 <syntax>
1118 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
1119 <parameter name="Module">
1120 <para>Asterisk module name (including .so extension) or subsystem identifier:</para>
1121 <enumlist>
1122 <enum name="cdr" />
1123 <enum name="dnsmgr" />
1124 <enum name="extconfig" />
1125 <enum name="enum" />
1126 <enum name="acl" />
1127 <enum name="manager" />
1128 <enum name="http" />
1129 <enum name="logger" />
1130 <enum name="features" />
1131 <enum name="dsp" />
1132 <enum name="udptl" />
1133 <enum name="indications" />
1134 <enum name="cel" />
1135 <enum name="plc" />
1136 </enumlist>
1137 </parameter>
1138 <parameter name="LoadType" required="true">
1139 <para>The operation to be done on module. Subsystem identifiers may only
1140 be reloaded.</para>
1141 <enumlist>
1142 <enum name="load" />
1143 <enum name="unload" />
1144 <enum name="reload" />
1145 <enum name="refresh">
1146 <para>Completely unload and load again a specified module.</para>
1147 </enum>
1148 </enumlist>
1149 <para>If no module is specified for a <literal>reload</literal> loadtype,
1150 all modules are reloaded.</para>
1151 </parameter>
1152 <parameter name="Recursive" required="false">
1153 <para>For <literal>refresh</literal> operations, attempt to recursively
1154 unload any other modules that are dependent on this module, if that would
1155 allow it to successfully unload, and load them again afterwards.</para>
1156 </parameter>
1157 </syntax>
1158 <description>
1159 <para>Loads, unloads or reloads an Asterisk module in a running system.</para>
1160 </description>
1161 <see-also>
1162 <ref type="manager">Reload</ref>
1163 <ref type="manager">ModuleCheck</ref>
1164 </see-also>
1165 </manager>
1166 <manager name="ModuleCheck" language="en_US">
1167 <synopsis>
1168 Check if module is loaded.
1169 </synopsis>
1170 <syntax>
1171 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
1172 <parameter name="Module" required="true">
1173 <para>Asterisk module name (not including extension).</para>
1174 </parameter>
1175 </syntax>
1176 <description>
1177 <para>Checks if Asterisk module is loaded. Will return Success/Failure.
1178 An empty Version header is also returned (which doesn't contain
1179 the module revision number).</para>
1180 </description>
1181 <see-also>
1182 <ref type="manager">ModuleLoad</ref>
1183 </see-also>
1184 </manager>
1185 <manager name="AOCMessage" language="en_US">
1186 <synopsis>
1187 Generate an Advice of Charge message on a channel.
1188 </synopsis>
1189 <syntax>
1190 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
1191 <parameter name="Channel">
1192 <para>Channel name to generate the AOC message on.
1193 This value is required unless ChannelPrefix is given.</para>
1194 </parameter>
1195 <parameter name="ChannelPrefix">
1196 <para>Partial channel prefix. By using this option one can match the beginning part
1197 of a channel name without having to put the entire name in. For example
1198 if a channel name is SIP/snom-00000001 and this value is set to SIP/snom, then
1199 that channel matches and the message will be sent. Note however that only
1200 the first matched channel has the message sent on it. </para>
1201 </parameter>
1202 <parameter name="MsgType" required="true">
1203 <para>Defines what type of AOC message to create, AOC-S, AOC-D or AOC-E</para>
1204 <enumlist>
1205 <enum name="S" />
1206 <enum name="D" />
1207 <enum name="E" />
1208 </enumlist>
1209 </parameter>
1210 <parameter name="ChargeType">
1211 <para>Defines what kind of charge this message represents for AOC-D and AOC-E.</para>
1212 <enumlist>
1213 <enum name="NA" />
1214 <enum name="FREE" />
1215 <enum name="Currency" />
1216 <enum name="Unit" />
1217 </enumlist>
1218 </parameter>
1219 <parameter name="UnitAmount(0)">
1220 <para>This represents the amount of units charged. The ETSI AOC standard specifies that
1221 this value along with the optional UnitType value are entries in a list. To accommodate this
1222 these values take an index value starting at 0 which can be used to generate this list of
1223 unit entries. For Example, If two unit entires were required this could be achieved by setting the
1224 paramter UnitAmount(0)=1234 and UnitAmount(1)=5678. Note that UnitAmount at index 0 is
1225 required when ChargeType=Unit, all other entries in the list are optional.
1226 </para>
1227 </parameter>
1228 <parameter name="UnitType(0)">
1229 <para>Defines the type of unit. ETSI AOC standard specifies this as an integer
1230 value between 1 and 16, but this value is left open to accept any positive
1231 integer. Like the UnitAmount parameter, this value represents a list entry
1232 and has an index parameter that starts at 0.
1233 </para>
1234 </parameter>
1235 <parameter name="CurrencyName">
1236 <para>Specifies the currency's name. Note that this value is truncated after 10 characters.</para>
1237 </parameter>
1238 <parameter name="CurrencyAmount">
1239 <para>Specifies the charge unit amount as a positive integer.
1240 This value is required when ChargeType==Currency (AOC-D or AOC-E) or
1241 RateType==Duration/Flat/Volume (AOC-S).</para>
1242 </parameter>
1243 <parameter name="CurrencyMultiplier">
1244 <para>Specifies the currency multiplier.
1245 This value is required when CurrencyAmount is given.</para>
1246 <enumlist>
1247 <enum name="OneThousandth" />
1248 <enum name="OneHundredth" />
1249 <enum name="OneTenth" />
1250 <enum name="One" />
1251 <enum name="Ten" />
1252 <enum name="Hundred" />
1253 <enum name="Thousand" />
1254 </enumlist>
1255 </parameter>
1256 <parameter name="TotalType" default="Total">
1257 <para>Defines what kind of AOC-D total is represented.</para>
1258 <enumlist>
1259 <enum name="Total" />
1260 <enum name="SubTotal" />
1261 </enumlist>
1262 </parameter>
1263 <parameter name="AOCBillingId">
1264 <para>Represents a billing ID associated with an AOC-D or AOC-E message. Note
1265 that only the first 3 items of the enum are valid AOC-D billing IDs</para>
1266 <enumlist>
1267 <enum name="Normal" />
1268 <enum name="ReverseCharge" />
1269 <enum name="CreditCard" />
1270 <enum name="CallFwdUnconditional" />
1271 <enum name="CallFwdBusy" />
1272 <enum name="CallFwdNoReply" />
1273 <enum name="CallDeflection" />
1274 <enum name="CallTransfer" />
1275 </enumlist>
1276 </parameter>
1277 <parameter name="ChargingAssociationId">
1278 <para>Charging association identifier. This is optional for AOC-E and can be
1279 set to any value between -32768 and 32767</para>
1280 </parameter>
1281 <parameter name="ChargingAssociationNumber">
1282 <para>Represents the charging association party number. This value is optional
1283 for AOC-E.</para>
1284 </parameter>
1285 <parameter name="ChargingAssociationPlan">
1286 <para>Integer representing the charging plan associated with the ChargingAssociationNumber.
1287 The value is bits 7 through 1 of the Q.931 octet containing the type-of-number and
1288 numbering-plan-identification fields.</para>
1289 </parameter>
1290 <parameter name="ChargedItem">
1291 <para>Defines what part of the call is charged in AOC-S. Usually this is set to
1292 BasicCommunication, which refers to the time after the call is answered, but establishment
1293 (CallAttempt) or successful establishment (CallSetup) of a call can also be used.
1294 Other options are available, but these generally do not carry enough information to actually
1295 calculate the price of a call.
1296 It is possible to have multiple ChargedItem entries for a single call -- for example to
1297 charge for both the establishment of the call and the actual call. In this case, each
1298 ChargedItem is described by a ChargedItem: header and all other headers that follow it up to
1299 the next ChargedItem: header.</para>
1300 <enumlist>
1301 <enum name="NA" />
1302 <enum name="SpecialArrangement" />
1303 <enum name="BasicCommunication" />
1304 <enum name="CallAttempt" />
1305 <enum name="CallSetup" />
1306 <enum name="UserUserInfo" />
1307 <enum name="SupplementaryService" />
1308 </enumlist>
1309 </parameter>
1310 <parameter name="RateType">
1311 <para>Defines how an AOC-S ChargedItem is charged.
1312 The Duration option is only available when ChargedItem==BasicCommunication.</para>
1313 <enumlist>
1314 <enum name="NA" />
1315 <enum name="Free" />
1316 <enum name="FreeFromBeginning" />
1317 <enum name="Duration" />
1318 <enum name="Flat" />
1319 <enum name="Volume" />
1320 <enum name="SpecialCode" />
1321 </enumlist>
1322 </parameter>
1323 <parameter name="Time">
1324 <para>Specifies a positive integer which is the amount of time is paid for by one
1325 CurrencyAmount.
1326 This value is required when RateType==Duration.</para>
1327 </parameter>
1328 <parameter name="TimeScale">
1329 <para>Specifies the time multiplier.
1330 This value is required when Time is given.</para>
1331 <enumlist>
1332 <enum name="OneHundredthSecond" />
1333 <enum name="OneTenthSecond" />
1334 <enum name="Second" />
1335 <enum name="TenSeconds" />
1336 <enum name="Minute" />
1337 <enum name="Hour" />
1338 <enum name="Day" />
1339 </enumlist>
1340 </parameter>
1341 <parameter name="Granularity">
1342 <para>Specifies a positive integer which is the size of the charged time increments.
1343 This value is optional when RateType==Duration and ChargingType==StepFunction.</para>
1344 </parameter>
1345 <parameter name="GranularityTimeScale">
1346 <para>Specifies the granularity time multiplier.
1347 This value is required when Granularity is given.</para>
1348 <enumlist>
1349 <enum name="OneHundredthSecond" />
1350 <enum name="OneTenthSecond" />
1351 <enum name="Second" />
1352 <enum name="TenSeconds" />
1353 <enum name="Minute" />
1354 <enum name="Hour" />
1355 <enum name="Day" />
1356 </enumlist>
1357 </parameter>
1358 <parameter name="ChargingType">
1359 <para>Specifies whether the charge increases continuously with time or in increments of
1360 Time or, if provided, Granularity.
1361 This value is required when RateType==Duration.</para>
1362 <enumlist>
1363 <enum name="ContinuousCharging" />
1364 <enum name="StepFunction" />
1365 </enumlist>
1366 </parameter>
1367 <parameter name="VolumeUnit">
1368 <para>Specifies the quantity of which one unit is paid for by one CurrencyAmount.
1369 This value is required when RateType==Volume.</para>
1370 <enumlist>
1371 <enum name="Octet" />
1372 <enum name="Segment" />
1373 <enum name="Message" />
1374 </enumlist>
1375 </parameter>
1376 <parameter name="Code">
1377 <para>Specifies the charging code, which can be set to a value between 1 and 10.
1378 This value is required when ChargedItem==SpecialArrangement or RateType==SpecialCode.</para>
1379 </parameter>
1380 </syntax>
1381 <description>
1382 <para>Generates an AOC-S, AOC-D or AOC-E message on a channel.</para>
1383 </description>
1384 <see-also>
1385 <ref type="managerEvent">AOC-S</ref>
1386 <ref type="managerEvent">AOC-D</ref>
1387 <ref type="managerEvent">AOC-E</ref>
1388 </see-also>
1389 </manager>
1390 <function name="AMI_CLIENT" language="en_US">
1391 <synopsis>
1392 Checks attributes of manager accounts
1393 </synopsis>
1394 <syntax>
1395 <parameter name="loginname" required="true">
1396 <para>Login name, specified in manager.conf</para>
1397 </parameter>
1398 <parameter name="field" required="true">
1399 <para>The manager account attribute to return</para>
1400 <enumlist>
1401 <enum name="sessions"><para>The number of sessions for this AMI account</para></enum>
1402 </enumlist>
1403 </parameter>
1404 </syntax>
1405 <description>
1406 <para>
1407 Currently, the only supported parameter is "sessions" which will return the current number of
1408 active sessions for this AMI account.
1409 </para>
1410 </description>
1411 </function>
1412 <manager name="Filter" language="en_US">
1413 <synopsis>
1414 Dynamically add filters for the current manager session.
1415 </synopsis>
1416 <syntax>
1417 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
1418 <parameter name="Operation">
1419 <enumlist>
1420 <enum name="Add">
1421 <para>Add a filter.</para>
1422 </enum>
1423 </enumlist>
1424 </parameter>
1425 <parameter name="Filter">
1426 <para>Filters can be whitelist or blacklist</para>
1427 <para>Example whitelist filter: "Event: Newchannel"</para>
1428 <para>Example blacklist filter: "!Channel: DAHDI.*"</para>
1429 <para>This filter option is used to whitelist or blacklist events per user to be
1430 reported with regular expressions and are allowed if both the regex matches
1431 and the user has read access as defined in manager.conf. Filters are assumed to be for whitelisting
1432 unless preceeded by an exclamation point, which marks it as being black.
1433 Evaluation of the filters is as follows:</para>
1434 <para>- If no filters are configured all events are reported as normal.</para>
1435 <para>- If there are white filters only: implied black all filter processed first, then white filters.</para>
1436 <para>- If there are black filters only: implied white all filter processed first, then black filters.</para>
1437 <para>- If there are both white and black filters: implied black all filter processed first, then white
1438 filters, and lastly black filters.</para>
1439 </parameter>
1440 </syntax>
1441 <description>
1442 <para>The filters added are only used for the current session.
1443 Once the connection is closed the filters are removed.</para>
1444 <para>This comand requires the system permission because
1445 this command can be used to create filters that may bypass
1446 filters defined in manager.conf</para>
1447 </description>
1448 </manager>
1449 <manager name="BlindTransfer" language="en_US">
1450 <synopsis>
1451 Blind transfer channel(s) to the given destination
1452 </synopsis>
1453 <syntax>
1454 <parameter name="Channel" required="true">
1455 </parameter>
1456 <parameter name="Context">
1457 </parameter>
1458 <parameter name="Exten">
1459 </parameter>
1460 </syntax>
1461 <description>
1462 <para>Redirect all channels currently bridged to the specified channel to the specified destination.</para>
1463 </description>
1464 <see-also>
1465 <ref type="manager">Redirect</ref>
1466 <ref type="managerEvent">BlindTransfer</ref>
1467 </see-also>
1468 </manager>
1469 <managerEvent name="ExtensionStatus" language="en_US">
1470 <managerEventInstance class="EVENT_FLAG_CALL">
1471 <synopsis>Raised when a hint changes due to a device state change.</synopsis>
1472 <syntax>
1473 <parameter name="Exten">
1474 <para>Name of the extension.</para>
1475 </parameter>
1476 <parameter name="Context">
1477 <para>Context that owns the extension.</para>
1478 </parameter>
1479 <parameter name="Hint">
1480 <para>Hint set for the extension</para>
1481 </parameter>
1482 <parameter name="Status">
1483 <para>Numerical value of the extension status. Extension
1484 status is determined by the combined device state of all items
1485 contained in the hint.</para>
1486 <enumlist>
1487 <enum name="-2">
1488 <para>The extension was removed from the dialplan.</para>
1489 </enum>
1490 <enum name="-1">
1491 <para>The extension's hint was removed from the dialplan.</para>
1492 </enum>
1493 <enum name="0">
1494 <para><literal>Idle</literal> - Related device(s) are in an idle
1495 state.</para>
1496 </enum>
1497 <enum name="1">
1498 <para><literal>InUse</literal> - Related device(s) are in active
1499 calls but may take more calls.</para>
1500 </enum>
1501 <enum name="2">
1502 <para><literal>Busy</literal> - Related device(s) are in active
1503 calls and may not take any more calls.</para>
1504 </enum>
1505 <enum name="4">
1506 <para><literal>Unavailable</literal> - Related device(s) are
1507 not reachable.</para>
1508 </enum>
1509 <enum name="8">
1510 <para><literal>Ringing</literal> - Related device(s) are
1511 currently ringing.</para>
1512 </enum>
1513 <enum name="9">
1514 <para><literal>InUse&amp;Ringing</literal> - Related device(s)
1515 are currently ringing and in active calls.</para>
1516 </enum>
1517 <enum name="16">
1518 <para><literal>Hold</literal> - Related device(s) are
1519 currently on hold.</para>
1520 </enum>
1521 <enum name="17">
1522 <para><literal>InUse&amp;Hold</literal> - Related device(s)
1523 are currently on hold and in active calls.</para>
1524 </enum>
1525 </enumlist>
1526 </parameter>
1527 <parameter name="StatusText">
1528 <para>Text representation of <literal>Status</literal>.</para>
1529 <enumlist>
1530 <enum name="Idle" />
1531 <enum name="InUse" />
1532 <enum name="Busy" />
1533 <enum name="Unavailable" />
1534 <enum name="Ringing" />
1535 <enum name="InUse&amp;Ringing" />
1536 <enum name="Hold" />
1537 <enum name="InUse&amp;Hold" />
1538 <enum name="Unknown">
1539 <para>Status does not match any of the above values.</para>
1540 </enum>
1541 </enumlist>
1542 </parameter>
1543 </syntax>
1544 <see-also>
1545 <ref type="manager">ExtensionState</ref>
1546 </see-also>
1547 </managerEventInstance>
1548 </managerEvent>
1549 <managerEvent name="PresenceStatus" language="en_US">
1550 <managerEventInstance class="EVENT_FLAG_CALL">
1551 <synopsis>Raised when a hint changes due to a presence state change.</synopsis>
1552 <syntax>
1553 <parameter name="Exten" />
1554 <parameter name="Context" />
1555 <parameter name="Hint" />
1556 <parameter name="Status" />
1557 <parameter name="Subtype" />
1558 <parameter name="Message" />
1559 </syntax>
1560 <see-also>
1561 <ref type="manager">PresenceState</ref>
1562 </see-also>
1563 </managerEventInstance>
1564 </managerEvent>
1565 ***/
1566
1567/*! \addtogroup Group_AMI AMI functions
1568*/
1569/*! @{
1570 Doxygen group */
1571
1586
1591};
1592
1593/*!
1594 * Linked list of events.
1595 * Global events are appended to the list by append_event().
1596 * The usecount is the number of stored pointers to the element,
1597 * excluding the list pointers. So an element that is only in
1598 * the list has a usecount of 0, not 1.
1599 *
1600 * Clients have a pointer to the last event processed, and for each
1601 * of these clients we track the usecount of the elements.
1602 * If we have a pointer to an entry in the list, it is safe to navigate
1603 * it forward because elements will not be deleted, but only appended.
1604 * The worst that can happen is seeing the pointer still NULL.
1605 *
1606 * When the usecount of an element drops to 0, and the element is the
1607 * first in the list, we can remove it. Removal is done within the
1608 * main thread, which is woken up for the purpose.
1609 *
1610 * For simplicity of implementation, we make sure the list is never empty.
1611 */
1613 int usecount; /*!< # of clients who still need the event */
1615 unsigned int seq; /*!< sequence number */
1616 struct timeval tv; /*!< When event was allocated */
1617 AST_RWLIST_ENTRY(eventqent) eq_next;
1618 char eventdata[1]; /*!< really variable size, allocated by append_event() */
1619};
1620
1622
1623static int displayconnects = 1;
1624static int allowmultiplelogin = 1;
1626static int httptimeout = 60;
1628static int manager_enabled = 0;
1629static int subscribed = 0;
1630static int webmanager_enabled = 0;
1631static int manager_debug = 0; /*!< enable some debugging code in the manager */
1632static int authtimeout;
1633static int authlimit;
1636
1637#define DEFAULT_REALM "asterisk"
1638static char global_realm[MAXHOSTNAMELEN]; /*!< Default realm */
1639
1640static int unauth_sessions = 0;
1642
1643/*! \brief A \ref stasis_topic that all topics AMI cares about will be forwarded to */
1645
1646/*! \brief The \ref stasis_message_router for all \ref stasis messages */
1648
1649/*! \brief The \ref stasis_subscription for forwarding the RTP topic to the AMI topic */
1651
1652/*! \brief The \ref stasis_subscription for forwarding the Security topic to the AMI topic */
1654
1655/*!
1656 * \brief Set to true (non-zero) to globally allow all dangerous AMI actions to run
1657 */
1659
1660#ifdef TEST_FRAMEWORK
1661/*! \brief The \ref stasis_subscription for forwarding the Test topic to the AMI topic */
1662static struct stasis_forward *test_suite_forwarder;
1663#endif
1664
1665#define MGR_SHOW_TERMINAL_WIDTH 80
1666
1667#define MAX_VARS 128
1668
1669/*! \brief Fake event class used to end sessions at shutdown */
1670#define EVENT_FLAG_SHUTDOWN -1
1671
1672/*! \brief
1673 * Descriptor for a manager session, either on the AMI socket or over HTTP.
1674 *
1675 * \note
1676 * AMI session have managerid == 0; the entry is created upon a connect,
1677 * and destroyed with the socket.
1678 * HTTP sessions have managerid != 0, the value is used as a search key
1679 * to lookup sessions (using the mansession_id cookie, or nonce key from
1680 * Digest Authentication http header).
1681 */
1682#define MAX_BLACKLIST_CMD_LEN 2
1683static const struct {
1685} command_blacklist[] = {
1686 {{ "module", "load", NULL }},
1687 {{ "module", "unload", NULL }},
1688 {{ "restart", "gracefully", NULL }},
1690
1691static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
1692
1694{
1695 if (!acl_change_sub) {
1700 }
1701}
1702
1704{
1706}
1707
1708/* In order to understand what the heck is going on with the
1709 * mansession_session and mansession structs, we need to have a bit of a history
1710 * lesson.
1711 *
1712 * In the beginning, there was the mansession. The mansession contained data that was
1713 * intrinsic to a manager session, such as the time that it started, the name of the logged-in
1714 * user, etc. In addition to these parameters were the f and fd parameters. For typical manager
1715 * sessions, these were used to represent the TCP socket over which the AMI session was taking
1716 * place. It makes perfect sense for these fields to be a part of the session-specific data since
1717 * the session actually defines this information.
1718 *
1719 * Then came the HTTP AMI sessions. With these, the f and fd fields need to be opened and closed
1720 * for every single action that occurs. Thus the f and fd fields aren't really specific to the session
1721 * but rather to the action that is being executed. Because a single session may execute many commands
1722 * at once, some sort of safety needed to be added in order to be sure that we did not end up with fd
1723 * leaks from one action overwriting the f and fd fields used by a previous action before the previous action
1724 * has had a chance to properly close its handles.
1725 *
1726 * The initial idea to solve this was to use thread synchronization, but this prevented multiple actions
1727 * from being run at the same time in a single session. Some manager actions may block for a long time, thus
1728 * creating a large queue of actions to execute. In addition, this fix did not address the basic architectural
1729 * issue that for HTTP manager sessions, the f and fd variables are not really a part of the session, but are
1730 * part of the action instead.
1731 *
1732 * The new idea was to create a structure on the stack for each HTTP Manager action. This structure would
1733 * contain the action-specific information, such as which file to write to. In order to maintain expectations
1734 * of action handlers and not have to change the public API of the manager code, we would need to name this
1735 * new stacked structure 'mansession' and contain within it the old mansession struct that we used to use.
1736 * We renamed the old mansession struct 'mansession_session' to hopefully convey that what is in this structure
1737 * is session-specific data. The structure that it is wrapped in, called a 'mansession' really contains action-specific
1738 * data.
1739 */
1741 /*! \todo XXX need to document which fields it is protecting */
1742 struct ast_sockaddr addr; /*!< address we are connecting from */
1743 struct ast_iostream *stream; /*!< AMI stream */
1744 int inuse; /*!< number of HTTP sessions using this entry */
1745 int needdestroy; /*!< Whether an HTTP session should be destroyed */
1746 pthread_t waiting_thread; /*!< Sleeping thread using this descriptor */
1747 uint32_t managerid; /*!< Unique manager identifier, 0 for AMI sessions */
1748 time_t sessionstart; /*!< Session start time */
1749 struct timeval sessionstart_tv; /*!< Session start time */
1750 time_t sessiontimeout; /*!< Session timeout if HTTP */
1751 char username[80]; /*!< Logged in username */
1752 char challenge[10]; /*!< Authentication challenge */
1753 int authenticated; /*!< Authentication status */
1754 int readperm; /*!< Authorization for reading */
1755 int writeperm; /*!< Authorization for writing */
1756 char inbuf[1025]; /*!< Buffer - we use the extra byte to add a '\\0' and simplify parsing */
1757 int inlen; /*!< number of buffered bytes */
1758 struct ao2_container *whitefilters; /*!< Manager event filters - white list */
1759 struct ao2_container *blackfilters; /*!< Manager event filters - black list */
1760 struct ast_variable *chanvars; /*!< Channel variables to set for originate */
1761 int send_events; /*!< XXX what ? */
1762 struct eventqent *last_ev; /*!< last event processed. */
1763 int writetimeout; /*!< Timeout for ast_carefulwrite() */
1765 int pending_event; /*!< Pending events indicator in case when waiting_thread is NULL */
1766 time_t noncetime; /*!< Timer for nonce value expiration */
1767 unsigned long oldnonce; /*!< Stale nonce value */
1768 unsigned long nc; /*!< incremental nonce counter */
1769 unsigned int kicked:1; /*!< Flag set if session is forcibly kicked */
1770 ast_mutex_t notify_lock; /*!< Lock for notifying this session of events */
1773};
1774
1779
1780/*! \brief In case you didn't read that giant block of text above the mansession_session struct, the
1781 * \ref mansession is named this solely to keep the API the same in Asterisk. This structure really
1782 * represents data that is different from Manager action to Manager action. The mansession_session pointer
1783 * contained within points to session-specific data.
1784 */
1790 unsigned int write_error:1;
1793};
1794
1795/*! Active manager connection sessions container. */
1796static AO2_GLOBAL_OBJ_STATIC(mgr_sessions);
1797
1798/*! \brief user descriptor, as read from the config file.
1799 *
1800 * \note It is still missing some fields -- e.g. we can have multiple permit and deny
1801 * lines which are not supported here, and readperm/writeperm/writetimeout
1802 * are not stored.
1803 */
1805 char username[80];
1806 char *secret; /*!< Secret for logging in */
1807 int readperm; /*!< Authorization for reading */
1808 int writeperm; /*!< Authorization for writing */
1809 int writetimeout; /*!< Per user Timeout for ast_carefulwrite() */
1810 int displayconnects; /*!< XXX unused */
1811 int allowmultiplelogin; /*!< Per user option*/
1812 int keep; /*!< mark entries created on a reload */
1813 struct ao2_container *whitefilters; /*!< Manager event filters - white list */
1814 struct ao2_container *blackfilters; /*!< Manager event filters - black list */
1815 struct ast_acl_list *acl; /*!< ACL setting */
1816 char *a1_hash; /*!< precalculated A1 for Digest auth */
1817 struct ast_variable *chanvars; /*!< Channel variables to set for originate */
1819};
1820
1821/*! \brief list of users found in the config file */
1823
1824/*! \brief list of actions registered */
1826
1827/*! \brief list of hooks registered */
1829
1830#ifdef AST_XML_DOCS
1831/*! \brief A container of event documentation nodes */
1832static AO2_GLOBAL_OBJ_STATIC(event_docs);
1833#endif
1834
1835static int __attribute__((format(printf, 9, 0))) __manager_event_sessions(
1836 struct ao2_container *sessions,
1837 int category,
1838 const char *event,
1839 int chancount,
1840 struct ast_channel **chans,
1841 const char *file,
1842 int line,
1843 const char *func,
1844 const char *fmt,
1845 ...);
1846static enum add_filter_result manager_add_filter(const char *filter_pattern, struct ao2_container *whitefilters, struct ao2_container *blackfilters);
1847
1848static int match_filter(struct mansession *s, char *eventdata);
1849
1850/*!
1851 * @{ \brief Define AMI message types.
1852 */
1854/*! @} */
1855
1856/*!
1857 * \internal
1858 * \brief Find a registered action object.
1859 *
1860 * \param name Name of AMI action to find.
1861 *
1862 * \return Reffed action found or NULL
1863 */
1864static struct manager_action *action_find(const char *name)
1865{
1866 struct manager_action *act;
1867
1869 AST_RWLIST_TRAVERSE(&actions, act, list) {
1870 if (!strcasecmp(name, act->action)) {
1871 ao2_t_ref(act, +1, "found action object");
1872 break;
1873 }
1874 }
1876
1877 return act;
1878}
1879
1881{
1882 return manager_topic;
1883}
1884
1886{
1887 return stasis_router;
1888}
1889
1890static void manager_json_value_str_append(struct ast_json *value, const char *key,
1891 struct ast_str **res)
1892{
1893 switch (ast_json_typeof(value)) {
1894 case AST_JSON_STRING:
1895 ast_str_append(res, 0, "%s: %s\r\n", key, ast_json_string_get(value));
1896 break;
1897 case AST_JSON_INTEGER:
1898 ast_str_append(res, 0, "%s: %jd\r\n", key, ast_json_integer_get(value));
1899 break;
1900 case AST_JSON_TRUE:
1901 ast_str_append(res, 0, "%s: True\r\n", key);
1902 break;
1903 case AST_JSON_FALSE:
1904 ast_str_append(res, 0, "%s: False\r\n", key);
1905 break;
1906 default:
1907 ast_str_append(res, 0, "%s: \r\n", key);
1908 break;
1909 }
1910}
1911
1912static void manager_json_to_ast_str(struct ast_json *obj, const char *key,
1913 struct ast_str **res, key_exclusion_cb exclusion_cb);
1914
1915static void manager_json_array_with_key(struct ast_json *obj, const char* key,
1916 size_t index, struct ast_str **res,
1917 key_exclusion_cb exclusion_cb)
1918{
1919 struct ast_str *key_str = ast_str_alloca(64);
1920 ast_str_set(&key_str, 0, "%s(%zu)", key, index);
1922 res, exclusion_cb);
1923}
1924
1925static void manager_json_obj_with_key(struct ast_json *obj, const char* key,
1926 const char *parent_key, struct ast_str **res,
1927 key_exclusion_cb exclusion_cb)
1928{
1929 if (parent_key) {
1930 struct ast_str *key_str = ast_str_alloca(64);
1931 ast_str_set(&key_str, 0, "%s/%s", parent_key, key);
1933 res, exclusion_cb);
1934 return;
1935 }
1936
1937 manager_json_to_ast_str(obj, key, res, exclusion_cb);
1938}
1939
1940void manager_json_to_ast_str(struct ast_json *obj, const char *key,
1941 struct ast_str **res, key_exclusion_cb exclusion_cb)
1942{
1943 struct ast_json_iter *i;
1944
1945 /* If obj or res is not given, just return */
1946 if (!obj || !res) {
1947 return;
1948 }
1949
1950 if (!*res && !(*res = ast_str_create(1024))) {
1951 return;
1952 }
1953
1954 if (exclusion_cb && key && exclusion_cb(key)) {
1955 return;
1956 }
1957
1958 if (ast_json_typeof(obj) != AST_JSON_OBJECT &&
1960 manager_json_value_str_append(obj, key, res);
1961 return;
1962 }
1963
1964 if (ast_json_typeof(obj) == AST_JSON_ARRAY) {
1965 size_t j;
1966 for (j = 0; j < ast_json_array_size(obj); ++j) {
1968 key, j, res, exclusion_cb);
1969 }
1970 return;
1971 }
1972
1973 for (i = ast_json_object_iter(obj); i;
1974 i = ast_json_object_iter_next(obj, i)) {
1977 key, res, exclusion_cb);
1978 }
1979}
1980
1982{
1983 struct ast_str *res = ast_str_create(1024);
1984
1985 if (!ast_json_is_null(blob)) {
1986 manager_json_to_ast_str(blob, NULL, &res, exclusion_cb);
1987 }
1988
1989 return res;
1990}
1991
1992#define manager_event_sessions(sessions, category, event, contents , ...) \
1993 __manager_event_sessions(sessions, category, event, 0, NULL, __FILE__, __LINE__, __PRETTY_FUNCTION__, contents , ## __VA_ARGS__)
1994
1995#define any_manager_listeners(sessions) \
1996 ((sessions && ao2_container_count(sessions)) || !AST_RWLIST_EMPTY(&manager_hooks))
1997
1998static void manager_default_msg_cb(void *data, struct stasis_subscription *sub,
1999 struct stasis_message *message)
2000{
2001 struct ao2_container *sessions;
2002 struct ast_manager_event_blob *ev;
2003
2005 /* Not an AMI message; disregard */
2006 return;
2007 }
2008
2009 sessions = ao2_global_obj_ref(mgr_sessions);
2011 /* Nobody is listening */
2013 return;
2014 }
2015
2017 if (!ev) {
2018 /* Conversion failure */
2020 return;
2021 }
2022
2024 "%s", ev->extra_fields);
2025 ao2_ref(ev, -1);
2027}
2028
2029static void manager_generic_msg_cb(void *data, struct stasis_subscription *sub,
2030 struct stasis_message *message)
2031{
2032 struct ast_json_payload *payload;
2033 int class_type;
2034 const char *type;
2035 struct ast_json *event;
2036 struct ast_str *event_buffer;
2037 struct ao2_container *sessions;
2038
2039 sessions = ao2_global_obj_ref(mgr_sessions);
2041 /* Nobody is listening */
2043 return;
2044 }
2045
2046 payload = stasis_message_data(message);
2047 class_type = ast_json_integer_get(ast_json_object_get(payload->json, "class_type"));
2048 type = ast_json_string_get(ast_json_object_get(payload->json, "type"));
2049 event = ast_json_object_get(payload->json, "event");
2050
2052 if (!event_buffer) {
2053 ast_log(AST_LOG_WARNING, "Error while creating payload for event %s\n", type);
2055 return;
2056 }
2058 "%s", ast_str_buffer(event_buffer));
2059 ast_free(event_buffer);
2061}
2062
2063void ast_manager_publish_event(const char *type, int class_type, struct ast_json *obj)
2064{
2065 RAII_VAR(struct ast_json *, event_info, NULL, ast_json_unref);
2066 RAII_VAR(struct ast_json_payload *, payload, NULL, ao2_cleanup);
2068
2069 if (!obj || !ast_manager_get_generic_type()) {
2070 return;
2071 }
2072
2073 ast_json_ref(obj);
2074 event_info = ast_json_pack("{s: s, s: i, s: o}",
2075 "type", type,
2076 "class_type", class_type,
2077 "event", obj);
2078 if (!event_info) {
2079 return;
2080 }
2081
2082 payload = ast_json_payload_create(event_info);
2083 if (!payload) {
2084 return;
2085 }
2087 if (!message) {
2088 return;
2089 }
2091}
2092
2093/*! \brief Add a custom hook to be called when an event is fired */
2095{
2099}
2100
2101/*! \brief Delete a custom hook to be called when an event is fired */
2103{
2105 AST_RWLIST_REMOVE(&manager_hooks, hook, list);
2107}
2108
2110{
2111 return manager_enabled;
2112}
2113
2115{
2117}
2118
2119/*!
2120 * Grab a reference to the last event, update usecount as needed.
2121 * Can handle a NULL pointer.
2122 */
2123static struct eventqent *grab_last(void)
2124{
2125 struct eventqent *ret;
2126
2129 /* the list is never empty now, but may become so when
2130 * we optimize it in the future, so be prepared.
2131 */
2132 if (ret) {
2134 }
2136 return ret;
2137}
2138
2139/*!
2140 * Purge unused events. Remove elements from the head
2141 * as long as their usecount is 0 and there is a next element.
2142 */
2143static void purge_events(void)
2144{
2145 struct eventqent *ev;
2146 struct timeval now = ast_tvnow();
2147
2149 while ( (ev = AST_RWLIST_FIRST(&all_events)) &&
2150 ev->usecount == 0 && AST_RWLIST_NEXT(ev, eq_next)) {
2152 ast_free(ev);
2153 }
2154
2156 /* Never release the last event */
2157 if (!AST_RWLIST_NEXT(ev, eq_next)) {
2158 break;
2159 }
2160
2161 /* 2.5 times whatever the HTTP timeout is (maximum 2.5 hours) is the maximum time that we will definitely cache an event */
2162 if (ev->usecount == 0 && ast_tvdiff_sec(now, ev->tv) > (httptimeout > 3600 ? 3600 : httptimeout) * 2.5) {
2164 ast_free(ev);
2165 }
2166 }
2169}
2170
2171/*!
2172 * helper functions to convert back and forth between
2173 * string and numeric representation of set of flags
2174 */
2175static const struct permalias {
2176 int num;
2177 const char *label;
2178} perms[] = {
2179 { EVENT_FLAG_SYSTEM, "system" },
2180 { EVENT_FLAG_CALL, "call" },
2181 { EVENT_FLAG_LOG, "log" },
2182 { EVENT_FLAG_VERBOSE, "verbose" },
2183 { EVENT_FLAG_COMMAND, "command" },
2184 { EVENT_FLAG_AGENT, "agent" },
2185 { EVENT_FLAG_USER, "user" },
2186 { EVENT_FLAG_CONFIG, "config" },
2187 { EVENT_FLAG_DTMF, "dtmf" },
2188 { EVENT_FLAG_REPORTING, "reporting" },
2189 { EVENT_FLAG_CDR, "cdr" },
2190 { EVENT_FLAG_DIALPLAN, "dialplan" },
2191 { EVENT_FLAG_ORIGINATE, "originate" },
2192 { EVENT_FLAG_AGI, "agi" },
2193 { EVENT_FLAG_CC, "cc" },
2194 { EVENT_FLAG_AOC, "aoc" },
2195 { EVENT_FLAG_TEST, "test" },
2196 { EVENT_FLAG_SECURITY, "security" },
2197 { EVENT_FLAG_MESSAGE, "message" },
2198 { INT_MAX, "all" },
2199 { 0, "none" },
2201
2202/*! Maximum string length of the AMI authority permission string buildable from perms[]. */
2203#define MAX_AUTH_PERM_STRING 150
2204
2205/*! \brief Checks to see if a string which can be used to evaluate functions should be rejected */
2206static int function_capable_string_allowed_with_auths(const char *evaluating, int writepermlist)
2207{
2208 if (!(writepermlist & EVENT_FLAG_SYSTEM)
2209 && (
2210 strstr(evaluating, "SHELL") || /* NoOp(${SHELL(rm -rf /)}) */
2211 strstr(evaluating, "EVAL") /* NoOp(${EVAL(${some_var_containing_SHELL})}) */
2212 )) {
2213 return 0;
2214 }
2215 return 1;
2216}
2217
2218/*! \brief Convert authority code to a list of options for a user. This will only
2219 * display those authority codes that have an explicit match on authority */
2220static const char *user_authority_to_str(int authority, struct ast_str **res)
2221{
2222 int i;
2223 char *sep = "";
2224
2225 ast_str_reset(*res);
2226 for (i = 0; i < ARRAY_LEN(perms) - 1; i++) {
2227 if ((authority & perms[i].num) == perms[i].num) {
2228 ast_str_append(res, 0, "%s%s", sep, perms[i].label);
2229 sep = ",";
2230 }
2231 }
2232
2233 if (ast_str_strlen(*res) == 0) {
2234 /* replace empty string with something sensible */
2235 ast_str_append(res, 0, "<none>");
2236 }
2237
2238 return ast_str_buffer(*res);
2239}
2240
2241
2242/*! \brief Convert authority code to a list of options. Note that the EVENT_FLAG_ALL
2243 * authority will always be returned. */
2244static const char *authority_to_str(int authority, struct ast_str **res)
2245{
2246 int i;
2247 char *sep = "";
2248
2249 ast_str_reset(*res);
2250 if (authority != EVENT_FLAG_SHUTDOWN) {
2251 for (i = 0; i < ARRAY_LEN(perms) - 1; i++) {
2252 if (authority & perms[i].num) {
2253 ast_str_append(res, 0, "%s%s", sep, perms[i].label);
2254 sep = ",";
2255 }
2256 }
2257 }
2258
2259 if (ast_str_strlen(*res) == 0) {
2260 /* replace empty string with something sensible */
2261 ast_str_append(res, 0, "<none>");
2262 }
2263
2264 return ast_str_buffer(*res);
2265}
2266
2267/*! Tells you if smallstr exists inside bigstr
2268 which is delim by delim and uses no buf or stringsep
2269 ast_instring("this|that|more","this",'|') == 1;
2270
2271 feel free to move this to app.c -anthm */
2272static int ast_instring(const char *bigstr, const char *smallstr, const char delim)
2273{
2274 const char *val = bigstr, *next;
2275
2276 do {
2277 if ((next = strchr(val, delim))) {
2278 if (!strncmp(val, smallstr, (next - val))) {
2279 return 1;
2280 } else {
2281 continue;
2282 }
2283 } else {
2284 return !strcmp(smallstr, val);
2285 }
2286 } while (*(val = (next + 1)));
2287
2288 return 0;
2289}
2290
2291static int get_perm(const char *instr)
2292{
2293 int x = 0, ret = 0;
2294
2295 if (!instr) {
2296 return 0;
2297 }
2298
2299 for (x = 0; x < ARRAY_LEN(perms); x++) {
2300 if (ast_instring(instr, perms[x].label, ',')) {
2301 ret |= perms[x].num;
2302 }
2303 }
2304
2305 return ret;
2306}
2307
2308/*!
2309 * A number returns itself, false returns 0, true returns all flags,
2310 * other strings return the flags that are set.
2311 */
2312static int strings_to_mask(const char *string)
2313{
2314 const char *p;
2315
2316 if (ast_strlen_zero(string)) {
2317 return -1;
2318 }
2319
2320 for (p = string; *p; p++) {
2321 if (*p < '0' || *p > '9') {
2322 break;
2323 }
2324 }
2325 if (!*p) { /* all digits */
2326 return atoi(string);
2327 }
2328 if (ast_false(string)) {
2329 return 0;
2330 }
2331 if (ast_true(string)) { /* all permissions */
2332 int x, ret = 0;
2333 for (x = 0; x < ARRAY_LEN(perms); x++) {
2334 ret |= perms[x].num;
2335 }
2336 return ret;
2337 }
2338 return get_perm(string);
2339}
2340
2341/*! \brief Unreference manager session object.
2342 If no more references, then go ahead and delete it */
2344{
2345 int refcount = ao2_ref(s, -1);
2346 if (manager_debug) {
2347 ast_debug(1, "Mansession: %p refcount now %d\n", s, refcount - 1);
2348 }
2349 return NULL;
2350}
2351
2352static void event_filter_destructor(void *obj)
2353{
2354 regex_t *regex_filter = obj;
2355 regfree(regex_filter);
2356}
2357
2358static void session_destructor(void *obj)
2359{
2360 struct mansession_session *session = obj;
2361 struct eventqent *eqe = session->last_ev;
2362 struct ast_datastore *datastore;
2363
2364 /* Get rid of each of the data stores on the session */
2365 while ((datastore = AST_LIST_REMOVE_HEAD(&session->datastores, entry))) {
2366 /* Free the data store */
2367 ast_datastore_free(datastore);
2368 }
2369
2370 if (eqe) {
2372 }
2373 if (session->chanvars) {
2374 ast_variables_destroy(session->chanvars);
2375 }
2376
2377 if (session->whitefilters) {
2378 ao2_t_ref(session->whitefilters, -1, "decrement ref for white container, should be last one");
2379 }
2380
2381 if (session->blackfilters) {
2382 ao2_t_ref(session->blackfilters, -1, "decrement ref for black container, should be last one");
2383 }
2384
2385 ast_mutex_destroy(&session->notify_lock);
2386}
2387
2388/*! \brief Allocate manager session structure and add it to the list of sessions */
2390{
2391 struct ao2_container *sessions;
2392 struct mansession_session *newsession;
2393
2394 newsession = ao2_alloc(sizeof(*newsession), session_destructor);
2395 if (!newsession) {
2396 return NULL;
2397 }
2398
2401 if (!newsession->whitefilters || !newsession->blackfilters) {
2402 ao2_ref(newsession, -1);
2403 return NULL;
2404 }
2405
2406 newsession->waiting_thread = AST_PTHREADT_NULL;
2407 newsession->writetimeout = 100;
2408 newsession->send_events = -1;
2409 ast_sockaddr_copy(&newsession->addr, addr);
2410
2411 ast_mutex_init(&newsession->notify_lock);
2412
2413 sessions = ao2_global_obj_ref(mgr_sessions);
2414 if (sessions) {
2415 ao2_link(sessions, newsession);
2416 ao2_ref(sessions, -1);
2417 }
2418
2419 return newsession;
2420}
2421
2422static int mansession_cmp_fn(void *obj, void *arg, int flags)
2423{
2424 struct mansession_session *s = obj;
2425 char *str = arg;
2426 return !strcasecmp(s->username, str) ? CMP_MATCH : 0;
2427}
2428
2430{
2431 struct ao2_container *sessions;
2432
2433 sessions = ao2_global_obj_ref(mgr_sessions);
2434 if (sessions) {
2435 ao2_unlink(sessions, s);
2436 ao2_ref(sessions, -1);
2437 }
2439}
2440
2441
2442static int check_manager_session_inuse(const char *name)
2443{
2444 struct ao2_container *sessions;
2446 int inuse = 0;
2447
2448 sessions = ao2_global_obj_ref(mgr_sessions);
2449 if (sessions) {
2450 session = ao2_find(sessions, (char *) name, 0);
2451 ao2_ref(sessions, -1);
2452 if (session) {
2454 inuse = 1;
2455 }
2456 }
2457 return inuse;
2458}
2459
2460
2461/*!
2462 * lookup an entry in the list of registered users.
2463 * must be called with the list lock held.
2464 */
2466{
2467 struct ast_manager_user *user = NULL;
2468
2469 AST_RWLIST_TRAVERSE(&users, user, list) {
2470 if (!strcasecmp(user->username, name)) {
2471 break;
2472 }
2473 }
2474
2475 return user;
2476}
2477
2478/*! \brief Get displayconnects config option.
2479 * \param session manager session to get parameter from.
2480 * \return displayconnects config option value.
2481 */
2483{
2484 struct ast_manager_user *user = NULL;
2485 int ret = 0;
2486
2488 if ((user = get_manager_by_name_locked(session->username))) {
2489 ret = user->displayconnects;
2490 }
2492
2493 return ret;
2494}
2495
2496#ifdef AST_XML_DOCS
2497static void print_event_instance(struct ast_cli_args *a, struct ast_xml_doc_item *instance);
2498#endif
2499
2500static char *handle_showmancmd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2501{
2502 struct manager_action *cur;
2503 struct ast_str *authority;
2504 int num;
2505 int l;
2506 const char *auth_str;
2507#ifdef AST_XML_DOCS
2508 char syntax_title[64], description_title[64], synopsis_title[64], seealso_title[64];
2509 char arguments_title[64], privilege_title[64], final_response_title[64], list_responses_title[64];
2510#endif
2511
2512 switch (cmd) {
2513 case CLI_INIT:
2514 e->command = "manager show command";
2515 e->usage =
2516 "Usage: manager show command <actionname> [<actionname> [<actionname> [...]]]\n"
2517 " Shows the detailed description for a specific Asterisk manager interface command.\n";
2518 return NULL;
2519 case CLI_GENERATE:
2520 l = strlen(a->word);
2522 AST_RWLIST_TRAVERSE(&actions, cur, list) {
2523 if (!strncasecmp(a->word, cur->action, l)) {
2525 break;
2526 }
2527 }
2528 }
2530 return NULL;
2531 }
2532 if (a->argc < 4) {
2533 return CLI_SHOWUSAGE;
2534 }
2535
2537
2538#ifdef AST_XML_DOCS
2539 /* setup the titles */
2540 term_color(synopsis_title, "[Synopsis]\n", COLOR_MAGENTA, 0, 40);
2541 term_color(description_title, "[Description]\n", COLOR_MAGENTA, 0, 40);
2542 term_color(syntax_title, "[Syntax]\n", COLOR_MAGENTA, 0, 40);
2543 term_color(seealso_title, "[See Also]\n", COLOR_MAGENTA, 0, 40);
2544 term_color(arguments_title, "[Arguments]\n", COLOR_MAGENTA, 0, 40);
2545 term_color(privilege_title, "[Privilege]\n", COLOR_MAGENTA, 0, 40);
2546 term_color(final_response_title, "[Final Response]\n", COLOR_MAGENTA, 0, 40);
2547 term_color(list_responses_title, "[List Responses]\n", COLOR_MAGENTA, 0, 40);
2548#endif
2549
2551 AST_RWLIST_TRAVERSE(&actions, cur, list) {
2552 for (num = 3; num < a->argc; num++) {
2553 if (!strcasecmp(cur->action, a->argv[num])) {
2554 auth_str = authority_to_str(cur->authority, &authority);
2555
2556#ifdef AST_XML_DOCS
2557 if (cur->docsrc == AST_XML_DOC) {
2558 char *syntax = ast_xmldoc_printable(S_OR(cur->syntax, "Not available"), 1);
2559 char *synopsis = ast_xmldoc_printable(S_OR(cur->synopsis, "Not available"), 1);
2560 char *description = ast_xmldoc_printable(S_OR(cur->description, "Not available"), 1);
2561 char *arguments = ast_xmldoc_printable(S_OR(cur->arguments, "Not available"), 1);
2562 char *seealso = ast_xmldoc_printable(S_OR(cur->seealso, "Not available"), 1);
2563 char *privilege = ast_xmldoc_printable(S_OR(auth_str, "Not available"), 1);
2564 char *responses = ast_xmldoc_printable("None", 1);
2565
2566 if (!syntax || !synopsis || !description || !arguments
2567 || !seealso || !privilege || !responses) {
2568 ast_free(syntax);
2570 ast_free(description);
2571 ast_free(arguments);
2572 ast_free(seealso);
2573 ast_free(privilege);
2574 ast_free(responses);
2575 ast_cli(a->fd, "Allocation failure.\n");
2577
2578 return CLI_FAILURE;
2579 }
2580
2581 ast_cli(a->fd, "%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n\n%s",
2582 syntax_title, syntax,
2583 synopsis_title, synopsis,
2584 description_title, description,
2585 arguments_title, arguments,
2586 seealso_title, seealso,
2587 privilege_title, privilege,
2588 list_responses_title);
2589
2590 if (!cur->list_responses) {
2591 ast_cli(a->fd, "%s\n\n", responses);
2592 } else {
2593 struct ast_xml_doc_item *temp;
2594 for (temp = cur->list_responses; temp; temp = AST_LIST_NEXT(temp, next)) {
2595 ast_cli(a->fd, "Event: %s\n", temp->name);
2596 print_event_instance(a, temp);
2597 }
2598 }
2599
2600 ast_cli(a->fd, "%s", final_response_title);
2601
2602 if (!cur->final_response) {
2603 ast_cli(a->fd, "%s\n\n", responses);
2604 } else {
2605 ast_cli(a->fd, "Event: %s\n", cur->final_response->name);
2607 }
2608
2614 ast_free(privilege);
2615 ast_free(responses);
2616 } else
2617#endif
2618 {
2619 ast_cli(a->fd, "Action: %s\nSynopsis: %s\nPrivilege: %s\n%s\n",
2620 cur->action, cur->synopsis,
2621 auth_str,
2622 S_OR(cur->description, ""));
2623 }
2624 }
2625 }
2626 }
2628
2629 return CLI_SUCCESS;
2630}
2631
2632static char *handle_mandebug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2633{
2634 switch (cmd) {
2635 case CLI_INIT:
2636 e->command = "manager set debug [on|off]";
2637 e->usage = "Usage: manager set debug [on|off]\n Show, enable, disable debugging of the manager code.\n";
2638 return NULL;
2639 case CLI_GENERATE:
2640 return NULL;
2641 }
2642
2643 if (a->argc == 3) {
2644 ast_cli(a->fd, "manager debug is %s\n", manager_debug? "on" : "off");
2645 } else if (a->argc == 4) {
2646 if (!strcasecmp(a->argv[3], "on")) {
2647 manager_debug = 1;
2648 } else if (!strcasecmp(a->argv[3], "off")) {
2649 manager_debug = 0;
2650 } else {
2651 return CLI_SHOWUSAGE;
2652 }
2653 }
2654 return CLI_SUCCESS;
2655}
2656
2657static char *handle_showmanager(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2658{
2659 struct ast_manager_user *user = NULL;
2660 int l;
2661 struct ast_str *rauthority = ast_str_alloca(MAX_AUTH_PERM_STRING);
2662 struct ast_str *wauthority = ast_str_alloca(MAX_AUTH_PERM_STRING);
2663 struct ast_variable *v;
2664
2665 switch (cmd) {
2666 case CLI_INIT:
2667 e->command = "manager show user";
2668 e->usage =
2669 " Usage: manager show user <user>\n"
2670 " Display all information related to the manager user specified.\n";
2671 return NULL;
2672 case CLI_GENERATE:
2673 l = strlen(a->word);
2674 if (a->pos != 3) {
2675 return NULL;
2676 }
2678 AST_RWLIST_TRAVERSE(&users, user, list) {
2679 if (!strncasecmp(a->word, user->username, l)) {
2680 if (ast_cli_completion_add(ast_strdup(user->username))) {
2681 break;
2682 }
2683 }
2684 }
2686 return NULL;
2687 }
2688
2689 if (a->argc != 4) {
2690 return CLI_SHOWUSAGE;
2691 }
2692
2694
2695 if (!(user = get_manager_by_name_locked(a->argv[3]))) {
2696 ast_cli(a->fd, "There is no manager called %s\n", a->argv[3]);
2698 return CLI_SUCCESS;
2699 }
2700
2701 ast_cli(a->fd, "\n");
2702 ast_cli(a->fd,
2703 " username: %s\n"
2704 " secret: %s\n"
2705 " ACL: %s\n"
2706 " read perm: %s\n"
2707 " write perm: %s\n"
2708 " displayconnects: %s\n"
2709 "allowmultiplelogin: %s\n",
2710 S_OR(user->username, "(N/A)"),
2711 (user->secret ? "<Set>" : "(N/A)"),
2712 ((user->acl && !ast_acl_list_is_empty(user->acl)) ? "yes" : "no"),
2713 user_authority_to_str(user->readperm, &rauthority),
2714 user_authority_to_str(user->writeperm, &wauthority),
2715 (user->displayconnects ? "yes" : "no"),
2716 (user->allowmultiplelogin ? "yes" : "no"));
2717 ast_cli(a->fd, " Variables: \n");
2718 for (v = user->chanvars ; v ; v = v->next) {
2719 ast_cli(a->fd, " %s = %s\n", v->name, v->value);
2720 }
2721 if (!ast_acl_list_is_empty(user->acl)) {
2722 ast_acl_output(a->fd, user->acl, NULL);
2723 }
2724
2726
2727 return CLI_SUCCESS;
2728}
2729
2730static char *handle_showmanagers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2731{
2732 struct ast_manager_user *user = NULL;
2733 int count_amu = 0;
2734 switch (cmd) {
2735 case CLI_INIT:
2736 e->command = "manager show users";
2737 e->usage =
2738 "Usage: manager show users\n"
2739 " Prints a listing of all managers that are currently configured on that\n"
2740 " system.\n";
2741 return NULL;
2742 case CLI_GENERATE:
2743 return NULL;
2744 }
2745 if (a->argc != 3) {
2746 return CLI_SHOWUSAGE;
2747 }
2748
2750
2751 /* If there are no users, print out something along those lines */
2752 if (AST_RWLIST_EMPTY(&users)) {
2753 ast_cli(a->fd, "There are no manager users.\n");
2755 return CLI_SUCCESS;
2756 }
2757
2758 ast_cli(a->fd, "\nusername\n--------\n");
2759
2760 AST_RWLIST_TRAVERSE(&users, user, list) {
2761 ast_cli(a->fd, "%s\n", user->username);
2762 count_amu++;
2763 }
2764
2766
2767 ast_cli(a->fd,"-------------------\n"
2768 "%d manager users configured.\n", count_amu);
2769 return CLI_SUCCESS;
2770}
2771
2772/*! \brief CLI command manager list commands */
2773static char *handle_showmancmds(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2774{
2775 struct manager_action *cur;
2776 int name_len = 1;
2777 int space_remaining;
2778#define HSMC_FORMAT " %-*.*s %-.*s\n"
2779 switch (cmd) {
2780 case CLI_INIT:
2781 e->command = "manager show commands";
2782 e->usage =
2783 "Usage: manager show commands\n"
2784 " Prints a listing of all the available Asterisk manager interface commands.\n";
2785 return NULL;
2786 case CLI_GENERATE:
2787 return NULL;
2788 }
2789
2791 AST_RWLIST_TRAVERSE(&actions, cur, list) {
2792 int incoming_len = strlen(cur->action);
2793 if (incoming_len > name_len) {
2794 name_len = incoming_len;
2795 }
2796 }
2797
2798 space_remaining = MGR_SHOW_TERMINAL_WIDTH - name_len - 4;
2799 if (space_remaining < 0) {
2800 space_remaining = 0;
2801 }
2802
2803 ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, "Action", space_remaining, "Synopsis");
2804 ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, "------", space_remaining, "--------");
2805
2806 AST_RWLIST_TRAVERSE(&actions, cur, list) {
2807 ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, cur->action, space_remaining, cur->synopsis);
2808 }
2810
2811 return CLI_SUCCESS;
2812}
2813
2814/*! \brief CLI command manager kick session */
2815static char *handle_kickmanconn(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2816{
2817 struct ao2_container *sessions;
2819 struct ao2_iterator i;
2820 int fd = -1;
2821 int found = 0;
2822
2823 switch (cmd) {
2824 case CLI_INIT:
2825 e->command = "manager kick session";
2826 e->usage =
2827 "Usage: manager kick session <file descriptor>\n"
2828 " Kick an active Asterisk Manager Interface session\n";
2829 return NULL;
2830 case CLI_GENERATE:
2831 return NULL;
2832 }
2833
2834 if (a->argc != 4) {
2835 return CLI_SHOWUSAGE;
2836 }
2837
2838 fd = atoi(a->argv[3]);
2839 if (fd <= 0) { /* STDOUT won't be a valid AMI fd either */
2840 ast_cli(a->fd, "Invalid AMI file descriptor: %s\n", a->argv[3]);
2841 return CLI_FAILURE;
2842 }
2843
2844 sessions = ao2_global_obj_ref(mgr_sessions);
2845 if (sessions) {
2847 ao2_ref(sessions, -1);
2848 while ((session = ao2_iterator_next(&i))) {
2850 if (session->stream) {
2851 if (ast_iostream_get_fd(session->stream) == fd) {
2852 if (session->kicked) {
2853 ast_cli(a->fd, "Manager session using file descriptor %d has already been kicked\n", fd);
2856 break;
2857 }
2858 fd = ast_iostream_get_fd(session->stream);
2859 found = fd;
2860 ast_cli(a->fd, "Kicking manager session connected using file descriptor %d\n", fd);
2861 ast_mutex_lock(&session->notify_lock);
2862 session->kicked = 1;
2863 if (session->waiting_thread != AST_PTHREADT_NULL) {
2864 pthread_kill(session->waiting_thread, SIGURG);
2865 }
2866 ast_mutex_unlock(&session->notify_lock);
2869 break;
2870 }
2871 }
2874 }
2876 }
2877
2878 if (!found) {
2879 ast_cli(a->fd, "No manager session found using file descriptor %d\n", fd);
2880 }
2881 return CLI_SUCCESS;
2882}
2883
2884/*! \brief CLI command manager list connected */
2885static char *handle_showmanconn(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2886{
2887 struct ao2_container *sessions;
2889 time_t now = time(NULL);
2890#define HSMCONN_FORMAT1 " %-15.15s %-55.55s %-10.10s %-10.10s %-8.8s %-8.8s %-10.10s %-10.10s\n"
2891#define HSMCONN_FORMAT2 " %-15.15s %-55.55s %-10d %-10d %-8d %-8d %-10.10d %-10.10d\n"
2892 int count = 0;
2893 struct ao2_iterator i;
2894
2895 switch (cmd) {
2896 case CLI_INIT:
2897 e->command = "manager show connected";
2898 e->usage =
2899 "Usage: manager show connected\n"
2900 " Prints a listing of the users that are currently connected to the\n"
2901 "Asterisk manager interface.\n";
2902 return NULL;
2903 case CLI_GENERATE:
2904 return NULL;
2905 }
2906
2907 ast_cli(a->fd, HSMCONN_FORMAT1, "Username", "IP Address", "Start", "Elapsed", "FileDes", "HttpCnt", "ReadPerms", "WritePerms");
2908
2909 sessions = ao2_global_obj_ref(mgr_sessions);
2910 if (sessions) {
2912 ao2_ref(sessions, -1);
2913 while ((session = ao2_iterator_next(&i))) {
2915 ast_cli(a->fd, HSMCONN_FORMAT2, session->username,
2917 (int) (session->sessionstart),
2918 (int) (now - session->sessionstart),
2919 session->stream ? ast_iostream_get_fd(session->stream) : -1,
2920 session->inuse,
2921 session->readperm,
2922 session->writeperm);
2923 count++;
2926 }
2928 }
2929 ast_cli(a->fd, "%d users connected.\n", count);
2930
2931 return CLI_SUCCESS;
2932}
2933
2934/*! \brief CLI command manager list eventq */
2935/* Should change to "manager show connected" */
2936static char *handle_showmaneventq(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2937{
2938 struct eventqent *s;
2939 switch (cmd) {
2940 case CLI_INIT:
2941 e->command = "manager show eventq";
2942 e->usage =
2943 "Usage: manager show eventq\n"
2944 " Prints a listing of all events pending in the Asterisk manger\n"
2945 "event queue.\n";
2946 return NULL;
2947 case CLI_GENERATE:
2948 return NULL;
2949 }
2951 AST_RWLIST_TRAVERSE(&all_events, s, eq_next) {
2952 ast_cli(a->fd, "Usecount: %d\n", s->usecount);
2953 ast_cli(a->fd, "Category: %d\n", s->category);
2954 ast_cli(a->fd, "Event:\n%s", s->eventdata);
2955 }
2957
2958 return CLI_SUCCESS;
2959}
2960
2961static int reload_module(void);
2962
2963/*! \brief CLI command manager reload */
2964static char *handle_manager_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2965{
2966 switch (cmd) {
2967 case CLI_INIT:
2968 e->command = "manager reload";
2969 e->usage =
2970 "Usage: manager reload\n"
2971 " Reloads the manager configuration.\n";
2972 return NULL;
2973 case CLI_GENERATE:
2974 return NULL;
2975 }
2976 if (a->argc > 2) {
2977 return CLI_SHOWUSAGE;
2978 }
2979 reload_module();
2980 return CLI_SUCCESS;
2981}
2982
2983static struct eventqent *advance_event(struct eventqent *e)
2984{
2985 struct eventqent *next;
2986
2988 if ((next = AST_RWLIST_NEXT(e, eq_next))) {
2991 }
2993 return next;
2994}
2995
2996#define GET_HEADER_FIRST_MATCH 0
2997#define GET_HEADER_LAST_MATCH 1
2998#define GET_HEADER_SKIP_EMPTY 2
2999
3000/*!
3001 * \brief Return a matching header value.
3002 *
3003 * \details
3004 * Generic function to return either the first or the last
3005 * matching header from a list of variables, possibly skipping
3006 * empty strings.
3007 *
3008 * \note At the moment there is only one use of this function in
3009 * this file, so we make it static.
3010 *
3011 * \note Never returns NULL.
3012 */
3013static const char *__astman_get_header(const struct message *m, char *var, int mode)
3014{
3015 int x, l = strlen(var);
3016 const char *result = "";
3017
3018 if (!m) {
3019 return result;
3020 }
3021
3022 for (x = 0; x < m->hdrcount; x++) {
3023 const char *h = m->headers[x];
3024 if (!strncasecmp(var, h, l) && h[l] == ':') {
3025 const char *value = h + l + 1;
3026 value = ast_skip_blanks(value); /* ignore leading spaces in the value */
3027 /* found a potential candidate */
3028 if ((mode & GET_HEADER_SKIP_EMPTY) && ast_strlen_zero(value)) {
3029 continue; /* not interesting */
3030 }
3031 if (mode & GET_HEADER_LAST_MATCH) {
3032 result = value; /* record the last match so far */
3033 } else {
3034 return value;
3035 }
3036 }
3037 }
3038
3039 return result;
3040}
3041
3042/*!
3043 * \brief Return the first matching variable from an array.
3044 *
3045 * \note This is the legacy function and is implemented in
3046 * therms of __astman_get_header().
3047 *
3048 * \note Never returns NULL.
3049 */
3050const char *astman_get_header(const struct message *m, char *var)
3051{
3053}
3054
3055/*!
3056 * \brief Append additional headers into the message structure from params.
3057 *
3058 * \note You likely want to initialize m->hdrcount to 0 before calling this.
3059 */
3060static void astman_append_headers(struct message *m, const struct ast_variable *params)
3061{
3062 const struct ast_variable *v;
3063
3064 for (v = params; v && m->hdrcount < ARRAY_LEN(m->headers); v = v->next) {
3065 if (ast_asprintf((char**)&m->headers[m->hdrcount], "%s: %s", v->name, v->value) > -1) {
3066 ++m->hdrcount;
3067 }
3068 }
3069}
3070
3071/*!
3072 * \brief Free headers inside message structure, but not the message structure itself.
3073 */
3074static void astman_free_headers(struct message *m)
3075{
3076 while (m->hdrcount) {
3077 --m->hdrcount;
3078 ast_free((void *) m->headers[m->hdrcount]);
3079 m->headers[m->hdrcount] = NULL;
3080 }
3081}
3082
3083/*!
3084 * \internal
3085 * \brief Process one "Variable:" header value string.
3086 *
3087 * \param head Current list of AMI variables to get new values added.
3088 * \param hdr_val Header value string to process.
3089 *
3090 * \return New variable list head.
3091 */
3092static struct ast_variable *man_do_variable_value(struct ast_variable *head, const char *hdr_val)
3093{
3094 char *parse;
3096 AST_APP_ARG(vars)[64];
3097 );
3098
3099 hdr_val = ast_skip_blanks(hdr_val); /* ignore leading spaces in the value */
3100 parse = ast_strdupa(hdr_val);
3101
3102 /* Break the header value string into name=val pair items. */
3104 if (args.argc) {
3105 int y;
3106
3107 /* Process each name=val pair item. */
3108 for (y = 0; y < args.argc; y++) {
3109 struct ast_variable *cur;
3110 char *var;
3111 char *val;
3112
3113 if (!args.vars[y]) {
3114 continue;
3115 }
3116 var = val = args.vars[y];
3117 strsep(&val, "=");
3118
3119 /* XXX We may wish to trim whitespace from the strings. */
3120 if (!val || ast_strlen_zero(var)) {
3121 continue;
3122 }
3123
3124 /* Create new variable list node and prepend it to the list. */
3125 cur = ast_variable_new(var, val, "");
3126 if (cur) {
3127 cur->next = head;
3128 head = cur;
3129 }
3130 }
3131 }
3132
3133 return head;
3134}
3135
3137{
3139}
3140
3143{
3144 int varlen;
3145 int x;
3146 struct ast_variable *head = NULL;
3147
3148 static const char var_hdr[] = "Variable:";
3149
3150 /* Process all "Variable:" headers. */
3151 varlen = strlen(var_hdr);
3152 for (x = 0; x < m->hdrcount; x++) {
3153 if (strncasecmp(var_hdr, m->headers[x], varlen)) {
3154 continue;
3155 }
3156 head = man_do_variable_value(head, m->headers[x] + varlen);
3157 }
3158
3159 if (order == ORDER_NATURAL) {
3160 head = ast_variables_reverse(head);
3161 }
3162
3163 return head;
3164}
3165
3166/*! \brief access for hooks to send action messages to ami */
3167int ast_hook_send_action(struct manager_custom_hook *hook, const char *msg)
3168{
3169 const char *action;
3170 int ret = 0;
3171 struct manager_action *act_found;
3172 struct mansession s = {.session = NULL, };
3173 struct message m = { 0 };
3174 char *dup_str;
3175 char *src;
3176 int x = 0;
3177 int curlen;
3178
3179 if (hook == NULL) {
3180 return -1;
3181 }
3182
3183 /* Create our own copy of the AMI action msg string. */
3184 src = dup_str = ast_strdup(msg);
3185 if (!dup_str) {
3186 return -1;
3187 }
3188
3189 /* convert msg string to message struct */
3190 curlen = strlen(src);
3191 for (x = 0; x < curlen; x++) {
3192 int cr; /* set if we have \r */
3193 if (src[x] == '\r' && x+1 < curlen && src[x+1] == '\n')
3194 cr = 2; /* Found. Update length to include \r\n */
3195 else if (src[x] == '\n')
3196 cr = 1; /* also accept \n only */
3197 else
3198 continue;
3199 /* don't keep empty lines */
3200 if (x && m.hdrcount < ARRAY_LEN(m.headers)) {
3201 /* ... but trim \r\n and terminate the header string */
3202 src[x] = '\0';
3203 m.headers[m.hdrcount++] = src;
3204 }
3205 x += cr;
3206 curlen -= x; /* remaining size */
3207 src += x; /* update pointer */
3208 x = -1; /* reset loop */
3209 }
3210
3211 action = astman_get_header(&m, "Action");
3212
3213 do {
3214 if (!strcasecmp(action, "login")) {
3215 break;
3216 }
3217
3218 act_found = action_find(action);
3219 if (!act_found) {
3220 break;
3221 }
3222
3223 /*
3224 * we have to simulate a session for this action request
3225 * to be able to pass it down for processing
3226 * This is necessary to meet the previous design of manager.c
3227 */
3228 s.hook = hook;
3229
3230 ret = -1;
3231 ao2_lock(act_found);
3232 if (act_found->registered && act_found->func) {
3233 struct ast_module *mod_ref = ast_module_running_ref(act_found->module);
3234
3235 ao2_unlock(act_found);
3236 /* If the action is in a module it must be running. */
3237 if (!act_found->module || mod_ref) {
3238 ret = act_found->func(&s, &m);
3239 ast_module_unref(mod_ref);
3240 }
3241 } else {
3242 ao2_unlock(act_found);
3243 }
3244 ao2_t_ref(act_found, -1, "done with found action object");
3245 } while (0);
3246
3247 ast_free(dup_str);
3248 return ret;
3249}
3250
3251/*!
3252 * helper function to send a string to the socket.
3253 * Return -1 on error (e.g. buffer full).
3254 */
3255static int send_string(struct mansession *s, char *string)
3256{
3257 struct ast_iostream *stream;
3258 int len, res;
3259
3260 /* It's a result from one of the hook's action invocation */
3261 if (s->hook) {
3262 /*
3263 * to send responses, we're using the same function
3264 * as for receiving events. We call the event "HookResponse"
3265 */
3266 s->hook->helper(EVENT_FLAG_HOOKRESPONSE, "HookResponse", string);
3267 return 0;
3268 }
3269
3270 stream = s->stream ? s->stream : s->session->stream;
3271
3272 len = strlen(string);
3274 res = ast_iostream_write(stream, string, len);
3276
3277 if (res < len) {
3278 s->write_error = 1;
3279 }
3280
3281 return res;
3282}
3283
3284/*!
3285 * \brief thread local buffer for astman_append
3286 *
3287 * \note This can not be defined within the astman_append() function
3288 * because it declares a couple of functions that get used to
3289 * initialize the thread local storage key.
3290 */
3292
3294
3295/*! \brief initial allocated size for the astman_append_buf and astman_send_*_va */
3296#define ASTMAN_APPEND_BUF_INITSIZE 256
3297
3298static void astman_flush(struct mansession *s, struct ast_str *buf)
3299{
3300 if (s->hook || (s->tcptls_session && s->tcptls_session->stream)) {
3302 } else {
3303 ast_verbose("No connection stream in astman_append, should not happen\n");
3304 }
3305}
3306
3307/*!
3308 * utility functions for creating AMI replies
3309 */
3310void astman_append(struct mansession *s, const char *fmt, ...)
3311{
3312 int res;
3313 va_list ap;
3314 struct ast_str *buf;
3315
3317 return;
3318 }
3319
3320 va_start(ap, fmt);
3321 res = ast_str_set_va(&buf, 0, fmt, ap);
3322 va_end(ap);
3323 if (res == AST_DYNSTR_BUILD_FAILED) {
3324 return;
3325 }
3326
3327 if (s->hook || (s->tcptls_session != NULL && s->tcptls_session->stream != NULL)) {
3329 } else {
3330 ast_verbose("No connection stream in astman_append, should not happen\n");
3331 }
3332}
3333
3334/*! \note NOTE: XXX this comment is unclear and possibly wrong.
3335 Callers of astman_send_error(), astman_send_response() or astman_send_ack() must EITHER
3336 hold the session lock _or_ be running in an action callback (in which case s->session->busy will
3337 be non-zero). In either of these cases, there is no need to lock-protect the session's
3338 fd, since no other output will be sent (events will be queued), and no input will
3339 be read until either the current action finishes or get_input() obtains the session
3340 lock.
3341 */
3342
3343/*! \todo XXX MSG_MOREDATA should go to a header file. */
3344#define MSG_MOREDATA ((char *)astman_send_response)
3345
3346/*! \brief send a response with an optional message,
3347 * and terminate it with an empty line.
3348 * m is used only to grab the 'ActionID' field.
3349 *
3350 * Use the explicit constant MSG_MOREDATA to remove the empty line.
3351 * XXX MSG_MOREDATA should go to a header file.
3352 */
3353static void astman_send_response_full(struct mansession *s, const struct message *m, char *resp, char *msg, char *listflag)
3354{
3355 const char *id = astman_get_header(m, "ActionID");
3356 struct ast_str *buf;
3357
3359 if (!buf) {
3360 return;
3361 }
3362
3363 ast_str_set(&buf, 0, "Response: %s\r\n", resp);
3364
3365 if (!ast_strlen_zero(id)) {
3366 ast_str_append(&buf, 0, "ActionID: %s\r\n", id);
3367 }
3368
3369 if (listflag) {
3370 /* Start, complete, cancelled */
3371 ast_str_append(&buf, 0, "EventList: %s\r\n", listflag);
3372 }
3373
3374 if (msg != MSG_MOREDATA) {
3375 if (msg) {
3376 ast_str_append(&buf, 0, "Message: %s\r\n", msg);
3377 }
3378 ast_str_append(&buf, 0, "\r\n");
3379 }
3380
3381 astman_flush(s, buf);
3382}
3383
3384void astman_send_response(struct mansession *s, const struct message *m, char *resp, char *msg)
3385{
3386 astman_send_response_full(s, m, resp, msg, NULL);
3387}
3388
3389void astman_send_error(struct mansession *s, const struct message *m, char *error)
3390{
3391 astman_send_response_full(s, m, "Error", error, NULL);
3392}
3393
3394void astman_send_error_va(struct mansession *s, const struct message *m, const char *fmt, ...)
3395{
3396 int res;
3397 va_list ap;
3398 struct ast_str *buf;
3399 char *msg;
3400
3402 return;
3403 }
3404
3405 va_start(ap, fmt);
3406 res = ast_str_set_va(&buf, 0, fmt, ap);
3407 va_end(ap);
3408 if (res == AST_DYNSTR_BUILD_FAILED) {
3409 return;
3410 }
3411
3412 /* astman_append will use the same underlying buffer, so copy the message out
3413 * before sending the response */
3414 msg = ast_str_buffer(buf);
3415 if (msg) {
3416 msg = ast_strdupa(msg);
3417 }
3418 astman_send_response_full(s, m, "Error", msg, NULL);
3419}
3420
3421void astman_send_ack(struct mansession *s, const struct message *m, char *msg)
3422{
3423 astman_send_response_full(s, m, "Success", msg, NULL);
3424}
3425
3426static void astman_start_ack(struct mansession *s, const struct message *m)
3427{
3428 astman_send_response_full(s, m, "Success", MSG_MOREDATA, NULL);
3429}
3430
3431void astman_send_listack(struct mansession *s, const struct message *m, char *msg, char *listflag)
3432{
3433 astman_send_response_full(s, m, "Success", msg, listflag);
3434}
3435
3436static struct ast_str *astman_send_list_complete_start_common(struct mansession *s, const struct message *m, const char *event_name, int count)
3437{
3438 const char *id = astman_get_header(m, "ActionID");
3439 struct ast_str *buf;
3440
3442 if (!buf) {
3443 return NULL;
3444 }
3445
3446 ast_str_set(&buf, 0, "Event: %s\r\n", event_name);
3447 if (!ast_strlen_zero(id)) {
3448 ast_str_append(&buf, 0, "ActionID: %s\r\n", id);
3449 }
3450 ast_str_append(&buf, 0,
3451 "EventList: Complete\r\n"
3452 "ListItems: %d\r\n",
3453 count);
3454
3455 return buf;
3456}
3457
3458static void astman_send_list_complete(struct mansession *s, const struct message *m, const char *event_name, int count)
3459{
3460 struct ast_str *buf = astman_send_list_complete_start_common(s, m, event_name, count);
3461 if (buf) {
3462 ast_str_append(&buf, 0, "\r\n");
3463 astman_flush(s, buf);
3464 }
3465}
3466
3467void astman_send_list_complete_start(struct mansession *s, const struct message *m, const char *event_name, int count)
3468{
3469 struct ast_str *buf = astman_send_list_complete_start_common(s, m, event_name, count);
3470 if (buf) {
3471 astman_flush(s, buf);
3472 }
3473}
3474
3476{
3477 astman_append(s, "\r\n");
3478}
3479
3480/*! \brief Lock the 'mansession' structure. */
3481static void mansession_lock(struct mansession *s)
3482{
3483 ast_mutex_lock(&s->lock);
3484}
3485
3486/*! \brief Unlock the 'mansession' structure. */
3487static void mansession_unlock(struct mansession *s)
3488{
3490}
3491
3492/*! \brief
3493 Rather than braindead on,off this now can also accept a specific int mask value
3494 or a ',' delim list of mask strings (the same as manager.conf) -anthm
3495*/
3496static int set_eventmask(struct mansession *s, const char *eventmask)
3497{
3498 int maskint = strings_to_mask(eventmask);
3499
3500 ao2_lock(s->session);
3501 if (maskint >= 0) {
3502 s->session->send_events = maskint;
3503 }
3504 ao2_unlock(s->session);
3505
3506 return maskint;
3507}
3508
3510{
3513}
3514
3515static void report_invalid_user(const struct mansession *s, const char *username)
3516{
3517 char session_id[32];
3518 struct ast_security_event_inval_acct_id inval_acct_id = {
3521 .common.service = "AMI",
3522 .common.account_id = username,
3523 .common.session_tv = &s->session->sessionstart_tv,
3524 .common.local_addr = {
3525 .addr = &s->tcptls_session->parent->local_address,
3526 .transport = mansession_get_transport(s),
3527 },
3528 .common.remote_addr = {
3529 .addr = &s->session->addr,
3530 .transport = mansession_get_transport(s),
3531 },
3532 .common.session_id = session_id,
3533 };
3534
3535 snprintf(session_id, sizeof(session_id), "%p", s);
3536
3537 ast_security_event_report(AST_SEC_EVT(&inval_acct_id));
3538}
3539
3540static void report_failed_acl(const struct mansession *s, const char *username)
3541{
3542 char session_id[32];
3543 struct ast_security_event_failed_acl failed_acl_event = {
3545 .common.version = AST_SECURITY_EVENT_FAILED_ACL_VERSION,
3546 .common.service = "AMI",
3547 .common.account_id = username,
3548 .common.session_tv = &s->session->sessionstart_tv,
3549 .common.local_addr = {
3550 .addr = &s->tcptls_session->parent->local_address,
3551 .transport = mansession_get_transport(s),
3552 },
3553 .common.remote_addr = {
3554 .addr = &s->session->addr,
3555 .transport = mansession_get_transport(s),
3556 },
3557 .common.session_id = session_id,
3558 };
3559
3560 snprintf(session_id, sizeof(session_id), "%p", s->session);
3561
3562 ast_security_event_report(AST_SEC_EVT(&failed_acl_event));
3563}
3564
3565static void report_inval_password(const struct mansession *s, const char *username)
3566{
3567 char session_id[32];
3568 struct ast_security_event_inval_password inval_password = {
3571 .common.service = "AMI",
3572 .common.account_id = username,
3573 .common.session_tv = &s->session->sessionstart_tv,
3574 .common.local_addr = {
3575 .addr = &s->tcptls_session->parent->local_address,
3576 .transport = mansession_get_transport(s),
3577 },
3578 .common.remote_addr = {
3579 .addr = &s->session->addr,
3580 .transport = mansession_get_transport(s),
3581 },
3582 .common.session_id = session_id,
3583 };
3584
3585 snprintf(session_id, sizeof(session_id), "%p", s->session);
3586
3587 ast_security_event_report(AST_SEC_EVT(&inval_password));
3588}
3589
3590static void report_auth_success(const struct mansession *s)
3591{
3592 char session_id[32];
3593 struct ast_security_event_successful_auth successful_auth = {
3596 .common.service = "AMI",
3597 .common.account_id = s->session->username,
3598 .common.session_tv = &s->session->sessionstart_tv,
3599 .common.local_addr = {
3600 .addr = &s->tcptls_session->parent->local_address,
3601 .transport = mansession_get_transport(s),
3602 },
3603 .common.remote_addr = {
3604 .addr = &s->session->addr,
3605 .transport = mansession_get_transport(s),
3606 },
3607 .common.session_id = session_id,
3608 };
3609
3610 snprintf(session_id, sizeof(session_id), "%p", s->session);
3611
3612 ast_security_event_report(AST_SEC_EVT(&successful_auth));
3613}
3614
3615static void report_req_not_allowed(const struct mansession *s, const char *action)
3616{
3617 char session_id[32];
3618 char request_type[64];
3619 struct ast_security_event_req_not_allowed req_not_allowed = {
3622 .common.service = "AMI",
3623 .common.account_id = s->session->username,
3624 .common.session_tv = &s->session->sessionstart_tv,
3625 .common.local_addr = {
3626 .addr = &s->tcptls_session->parent->local_address,
3627 .transport = mansession_get_transport(s),
3628 },
3629 .common.remote_addr = {
3630 .addr = &s->session->addr,
3631 .transport = mansession_get_transport(s),
3632 },
3633 .common.session_id = session_id,
3634
3635 .request_type = request_type,
3636 };
3637
3638 snprintf(session_id, sizeof(session_id), "%p", s->session);
3639 snprintf(request_type, sizeof(request_type), "Action: %s", action);
3640
3641 ast_security_event_report(AST_SEC_EVT(&req_not_allowed));
3642}
3643
3644static void report_req_bad_format(const struct mansession *s, const char *action)
3645{
3646 char session_id[32];
3647 char request_type[64];
3648 struct ast_security_event_req_bad_format req_bad_format = {
3651 .common.service = "AMI",
3652 .common.account_id = s->session->username,
3653 .common.session_tv = &s->session->sessionstart_tv,
3654 .common.local_addr = {
3655 .addr = &s->tcptls_session->parent->local_address,
3656 .transport = mansession_get_transport(s),
3657 },
3658 .common.remote_addr = {
3659 .addr = &s->session->addr,
3660 .transport = mansession_get_transport(s),
3661 },
3662 .common.session_id = session_id,
3663
3664 .request_type = request_type,
3665 };
3666
3667 snprintf(session_id, sizeof(session_id), "%p", s->session);
3668 snprintf(request_type, sizeof(request_type), "Action: %s", action);
3669
3670 ast_security_event_report(AST_SEC_EVT(&req_bad_format));
3671}
3672
3674 const char *response, const char *expected_response)
3675{
3676 char session_id[32];
3677 struct ast_security_event_chal_resp_failed chal_resp_failed = {
3680 .common.service = "AMI",
3681 .common.account_id = s->session->username,
3682 .common.session_tv = &s->session->sessionstart_tv,
3683 .common.local_addr = {
3684 .addr = &s->tcptls_session->parent->local_address,
3685 .transport = mansession_get_transport(s),
3686 },
3687 .common.remote_addr = {
3688 .addr = &s->session->addr,
3689 .transport = mansession_get_transport(s),
3690 },
3691 .common.session_id = session_id,
3692
3693 .challenge = s->session->challenge,
3694 .response = response,
3695 .expected_response = expected_response,
3696 };
3697
3698 snprintf(session_id, sizeof(session_id), "%p", s->session);
3699
3700 ast_security_event_report(AST_SEC_EVT(&chal_resp_failed));
3701}
3702
3703static void report_session_limit(const struct mansession *s)
3704{
3705 char session_id[32];
3707 .common.event_type = AST_SECURITY_EVENT_SESSION_LIMIT,
3709 .common.service = "AMI",
3710 .common.account_id = s->session->username,
3711 .common.session_tv = &s->session->sessionstart_tv,
3712 .common.local_addr = {
3713 .addr = &s->tcptls_session->parent->local_address,
3714 .transport = mansession_get_transport(s),
3715 },
3716 .common.remote_addr = {
3717 .addr = &s->session->addr,
3718 .transport = mansession_get_transport(s),
3719 },
3720 .common.session_id = session_id,
3721 };
3722
3723 snprintf(session_id, sizeof(session_id), "%p", s->session);
3724
3726}
3727
3728/*
3729 * Here we start with action_ handlers for AMI actions,
3730 * and the internal functions used by them.
3731 * Generally, the handlers are called action_foo()
3732 */
3733
3734/* helper function for action_login() */
3735static int authenticate(struct mansession *s, const struct message *m)
3736{
3737 const char *username = astman_get_header(m, "Username");
3738 const char *password = astman_get_header(m, "Secret");
3739 int error = -1;
3740 struct ast_manager_user *user = NULL;
3741 regex_t *regex_filter;
3742 struct ao2_iterator filter_iter;
3743
3744 if (ast_strlen_zero(username)) { /* missing username */
3745 return -1;
3746 }
3747
3748 /* locate user in locked state */
3750
3751 if (!(user = get_manager_by_name_locked(username))) {
3752 report_invalid_user(s, username);
3753 ast_log(LOG_NOTICE, "%s tried to authenticate with nonexistent user '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
3754 } else if (user->acl && (ast_apply_acl(user->acl, &s->session->addr, "Manager User ACL: ") == AST_SENSE_DENY)) {
3755 report_failed_acl(s, username);
3756 ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
3757 } else if (!strcasecmp(astman_get_header(m, "AuthType"), "MD5")) {
3758 const char *key = astman_get_header(m, "Key");
3759 if (!ast_strlen_zero(key) && !ast_strlen_zero(s->session->challenge) && user->secret) {
3760 int x;
3761 int len = 0;
3762 char md5key[256] = "";
3763 struct MD5Context md5;
3764 unsigned char digest[16];
3765
3766 MD5Init(&md5);
3767 MD5Update(&md5, (unsigned char *) s->session->challenge, strlen(s->session->challenge));
3768 MD5Update(&md5, (unsigned char *) user->secret, strlen(user->secret));
3769 MD5Final(digest, &md5);
3770 for (x = 0; x < 16; x++)
3771 len += sprintf(md5key + len, "%02hhx", digest[x]);
3772 if (!strcmp(md5key, key)) {
3773 error = 0;
3774 } else {
3775 report_failed_challenge_response(s, key, md5key);
3776 }
3777 } else {
3778 ast_debug(1, "MD5 authentication is not possible. challenge: '%s'\n",
3779 S_OR(s->session->challenge, ""));
3780 }
3781 } else if (user->secret) {
3782 if (!strcmp(password, user->secret)) {
3783 error = 0;
3784 } else {
3785 report_inval_password(s, username);
3786 }
3787 }
3788
3789 if (error) {
3790 ast_log(LOG_NOTICE, "%s failed to authenticate as '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
3792 return -1;
3793 }
3794
3795 /* auth complete */
3796
3797 /* All of the user parameters are copied to the session so that in the event
3798 * of a reload and a configuration change, the session parameters are not
3799 * changed. */
3800 ast_copy_string(s->session->username, username, sizeof(s->session->username));
3801 s->session->readperm = user->readperm;
3802 s->session->writeperm = user->writeperm;
3803 s->session->writetimeout = user->writetimeout;
3804 if (user->chanvars) {
3805 s->session->chanvars = ast_variables_dup(user->chanvars);
3806 }
3807
3808 filter_iter = ao2_iterator_init(user->whitefilters, 0);
3809 while ((regex_filter = ao2_iterator_next(&filter_iter))) {
3810 ao2_t_link(s->session->whitefilters, regex_filter, "add white user filter to session");
3811 ao2_t_ref(regex_filter, -1, "remove iterator ref");
3812 }
3813 ao2_iterator_destroy(&filter_iter);
3814
3815 filter_iter = ao2_iterator_init(user->blackfilters, 0);
3816 while ((regex_filter = ao2_iterator_next(&filter_iter))) {
3817 ao2_t_link(s->session->blackfilters, regex_filter, "add black user filter to session");
3818 ao2_t_ref(regex_filter, -1, "remove iterator ref");
3819 }
3820 ao2_iterator_destroy(&filter_iter);
3821
3822 s->session->sessionstart = time(NULL);
3824 set_eventmask(s, astman_get_header(m, "Events"));
3825
3827
3829 return 0;
3830}
3831
3832static int action_ping(struct mansession *s, const struct message *m)
3833{
3834 const char *actionid = astman_get_header(m, "ActionID");
3835 struct timeval now = ast_tvnow();
3836
3837 astman_append(s, "Response: Success\r\n");
3838 if (!ast_strlen_zero(actionid)){
3839 astman_append(s, "ActionID: %s\r\n", actionid);
3840 }
3842 s,
3843 "Ping: Pong\r\n"
3844 "Timestamp: %ld.%06lu\r\n"
3845 "\r\n",
3846 (long) now.tv_sec, (unsigned long) now.tv_usec);
3847 return 0;
3848}
3849
3850void astman_live_dangerously(int new_live_dangerously)
3851{
3852 if (new_live_dangerously && !live_dangerously)
3853 {
3854 ast_log(LOG_WARNING, "Manager Configuration load protection disabled.\n");
3855 }
3856
3857 if (!new_live_dangerously && live_dangerously)
3858 {
3859 ast_log(LOG_NOTICE, "Manager Configuration load protection enabled.\n");
3860 }
3861 live_dangerously = new_live_dangerously;
3862}
3863
3864/**
3865 * \brief Check if a file is restricted or not
3866 *
3867 * \return 0 on success
3868 * \return 1 on restricted file
3869 * \return -1 on failure
3870 */
3871static int restrictedFile(const char *filename)
3872{
3873 char *stripped_filename;
3874 RAII_VAR(char *, path, NULL, ast_free);
3875 RAII_VAR(char *, real_path, NULL, ast_std_free);
3876
3877 if (live_dangerously) {
3878 return 0;
3879 }
3880
3881 stripped_filename = ast_strip(ast_strdupa(filename));
3882
3883 /* If the file path starts with '/', don't prepend ast_config_AST_CONFIG_DIR */
3884 if (stripped_filename[0] == '/') {
3885 real_path = realpath(stripped_filename, NULL);
3886 } else {
3887 if (ast_asprintf(&path, "%s/%s", ast_config_AST_CONFIG_DIR, stripped_filename) == -1) {
3888 return -1;
3889 }
3890 real_path = realpath(path, NULL);
3891 }
3892
3893 if (!real_path) {
3894 return -1;
3895 }
3896
3897 if (!ast_begins_with(real_path, ast_config_AST_CONFIG_DIR)) {
3898 return 1;
3899 }
3900
3901 return 0;
3902}
3903
3904static int action_getconfig(struct mansession *s, const struct message *m)
3905{
3906 struct ast_config *cfg;
3907 const char *fn = astman_get_header(m, "Filename");
3908 const char *category = astman_get_header(m, "Category");
3909 const char *filter = astman_get_header(m, "Filter");
3910 const char *category_name;
3911 int catcount = 0;
3912 int lineno = 0;
3913 int ret = 0;
3914 struct ast_category *cur_category = NULL;
3915 struct ast_variable *v;
3916 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
3917
3918 if (ast_strlen_zero(fn)) {
3919 astman_send_error(s, m, "Filename not specified");
3920 return 0;
3921 }
3922
3923 ret = restrictedFile(fn);
3924 if (ret == 1) {
3925 astman_send_error(s, m, "File requires escalated priveledges");
3926 return 0;
3927 } else if (ret == -1) {
3928 astman_send_error(s, m, "Config file not found");
3929 return 0;
3930 }
3931
3932 cfg = ast_config_load2(fn, "manager", config_flags);
3933 if (cfg == CONFIG_STATUS_FILEMISSING) {
3934 astman_send_error(s, m, "Config file not found");
3935 return 0;
3936 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
3937 astman_send_error(s, m, "Config file has invalid format");
3938 return 0;
3939 }
3940
3941 astman_start_ack(s, m);
3942 while ((cur_category = ast_category_browse_filtered(cfg, category, cur_category, filter))) {
3943 struct ast_str *templates;
3944
3945 category_name = ast_category_get_name(cur_category);
3946 lineno = 0;
3947 astman_append(s, "Category-%06d: %s\r\n", catcount, category_name);
3948
3949 if (ast_category_is_template(cur_category)) {
3950 astman_append(s, "IsTemplate-%06d: %d\r\n", catcount, 1);
3951 }
3952
3953 if ((templates = ast_category_get_templates(cur_category))
3954 && ast_str_strlen(templates) > 0) {
3955 astman_append(s, "Templates-%06d: %s\r\n", catcount, ast_str_buffer(templates));
3957 }
3958
3959 for (v = ast_category_first(cur_category); v; v = v->next) {
3960 astman_append(s, "Line-%06d-%06d: %s=%s\r\n", catcount, lineno++, v->name, v->value);
3961 }
3962
3963 catcount++;
3964 }
3965
3966 if (!ast_strlen_zero(category) && catcount == 0) { /* TODO: actually, a config with no categories doesn't even get loaded */
3967 astman_append(s, "No categories found\r\n");
3968 }
3969
3970 ast_config_destroy(cfg);
3971 astman_append(s, "\r\n");
3972
3973 return 0;
3974}
3975
3976static int action_listcategories(struct mansession *s, const struct message *m)
3977{
3978 struct ast_config *cfg;
3979 const char *fn = astman_get_header(m, "Filename");
3980 const char *match = astman_get_header(m, "Match");
3981 struct ast_category *category = NULL;
3982 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
3983 int catcount = 0;
3984
3985 if (ast_strlen_zero(fn)) {
3986 astman_send_error(s, m, "Filename not specified");
3987 return 0;
3988 }
3989
3990 if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
3991 astman_send_error(s, m, "Config file not found");
3992 return 0;
3993 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
3994 astman_send_error(s, m, "Config file has invalid format");
3995 return 0;
3996 }
3997
3998 astman_start_ack(s, m);
3999 while ((category = ast_category_browse_filtered(cfg, NULL, category, match))) {
4000 astman_append(s, "Category-%06d: %s\r\n", catcount, ast_category_get_name(category));
4001 catcount++;
4002 }
4003
4004 if (catcount == 0) { /* TODO: actually, a config with no categories doesn't even get loaded */
4005 astman_append(s, "Error: no categories found\r\n");
4006 }
4007
4008 ast_config_destroy(cfg);
4009 astman_append(s, "\r\n");
4010
4011 return 0;
4012}
4013
4014/*! The amount of space in out must be at least ( 2 * strlen(in) + 1 ) */
4015static void json_escape(char *out, const char *in)
4016{
4017 for (; *in; in++) {
4018 if (*in == '\\' || *in == '\"') {
4019 *out++ = '\\';
4020 }
4021 *out++ = *in;
4022 }
4023 *out = '\0';
4024}
4025
4026/*!
4027 * \internal
4028 * \brief Append a JSON escaped string to the manager stream.
4029 *
4030 * \param s AMI stream to append a string.
4031 * \param str String to append to the stream after JSON escaping it.
4032 */
4033static void astman_append_json(struct mansession *s, const char *str)
4034{
4035 char *buf;
4036
4037 buf = ast_alloca(2 * strlen(str) + 1);
4039 astman_append(s, "%s", buf);
4040}
4041
4042static int action_getconfigjson(struct mansession *s, const struct message *m)
4043{
4044 struct ast_config *cfg;
4045 const char *fn = astman_get_header(m, "Filename");
4046 const char *filter = astman_get_header(m, "Filter");
4047 const char *category = astman_get_header(m, "Category");
4048 struct ast_category *cur_category = NULL;
4049 const char *category_name;
4050 struct ast_variable *v;
4051 int comma1 = 0;
4052 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
4053
4054 if (ast_strlen_zero(fn)) {
4055 astman_send_error(s, m, "Filename not specified");
4056 return 0;
4057 }
4058
4059 if (restrictedFile(fn)) {
4060 astman_send_error(s, m, "File requires escalated priveledges");
4061 return 0;
4062 }
4063
4064 if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
4065 astman_send_error(s, m, "Config file not found");
4066 return 0;
4067 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
4068 astman_send_error(s, m, "Config file has invalid format");
4069 return 0;
4070 }
4071
4072 astman_start_ack(s, m);
4073 astman_append(s, "JSON: {");
4074 while ((cur_category = ast_category_browse_filtered(cfg, category, cur_category, filter))) {
4075 int comma2 = 0;
4076 struct ast_str *templates;
4077
4078 category_name = ast_category_get_name(cur_category);
4079 astman_append(s, "%s\"", comma1 ? "," : "");
4080 astman_append_json(s, category_name);
4081 astman_append(s, "\":{");
4082 comma1 = 1;
4083
4084 if (ast_category_is_template(cur_category)) {
4085 astman_append(s, "\"istemplate\":1");
4086 comma2 = 1;
4087 }
4088
4089 if ((templates = ast_category_get_templates(cur_category))
4090 && ast_str_strlen(templates) > 0) {
4091 astman_append(s, "%s", comma2 ? "," : "");
4092 astman_append(s, "\"templates\":\"%s\"", ast_str_buffer(templates));
4094 comma2 = 1;
4095 }
4096
4097 for (v = ast_category_first(cur_category); v; v = v->next) {
4098 astman_append(s, "%s\"", comma2 ? "," : "");
4099 astman_append_json(s, v->name);
4100 astman_append(s, "\":\"");
4102 astman_append(s, "\"");
4103 comma2 = 1;
4104 }
4105
4106 astman_append(s, "}");
4107 }
4108 astman_append(s, "}\r\n\r\n");
4109
4110 ast_config_destroy(cfg);
4111
4112 return 0;
4113}
4114
4115/*! \brief helper function for action_updateconfig */
4116static enum error_type handle_updates(struct mansession *s, const struct message *m, struct ast_config *cfg, const char *dfn)
4117{
4118 int x;
4119 char hdr[40];
4120 const char *action, *cat, *var, *value, *match, *line, *options;
4121 struct ast_variable *v;
4122 struct ast_str *str1 = ast_str_create(16), *str2 = ast_str_create(16);
4123 enum error_type result = 0;
4124
4125 for (x = 0; x < 100000; x++) { /* 100000 = the max number of allowed updates + 1 */
4126 unsigned int object = 0;
4127 char *dupoptions;
4128 int allowdups = 0;
4129 int istemplate = 0;
4130 int ignoreerror = 0;
4131 RAII_VAR(char *, inherit, NULL, ast_free);
4132 RAII_VAR(char *, catfilter, NULL, ast_free);
4133 char *token;
4134 int foundvar = 0;
4135 int foundcat = 0;
4136 struct ast_category *category = NULL;
4137
4138 snprintf(hdr, sizeof(hdr), "Action-%06d", x);
4139 action = astman_get_header(m, hdr);
4140 if (ast_strlen_zero(action)) /* breaks the for loop if no action header */
4141 break; /* this could cause problems if actions come in misnumbered */
4142
4143 snprintf(hdr, sizeof(hdr), "Cat-%06d", x);
4144 cat = astman_get_header(m, hdr);
4145 if (ast_strlen_zero(cat)) { /* every action needs a category */
4147 break;
4148 }
4149
4150 snprintf(hdr, sizeof(hdr), "Var-%06d", x);
4151 var = astman_get_header(m, hdr);
4152
4153 snprintf(hdr, sizeof(hdr), "Value-%06d", x);
4154 value = astman_get_header(m, hdr);
4155
4156 if (!ast_strlen_zero(value) && *value == '>') {
4157 object = 1;
4158 value++;
4159 }
4160
4161 snprintf(hdr, sizeof(hdr), "Match-%06d", x);
4162 match = astman_get_header(m, hdr);
4163
4164 snprintf(hdr, sizeof(hdr), "Line-%06d", x);
4165 line = astman_get_header(m, hdr);
4166
4167 snprintf(hdr, sizeof(hdr), "Options-%06d", x);
4168 options = astman_get_header(m, hdr);
4169 if (!ast_strlen_zero(options)) {
4170 char copy[strlen(options) + 1];
4171 strcpy(copy, options); /* safe */
4172 dupoptions = copy;
4173 while ((token = ast_strsep(&dupoptions, ',', AST_STRSEP_STRIP))) {
4174 if (!strcasecmp("allowdups", token)) {
4175 allowdups = 1;
4176 continue;
4177 }
4178 if (!strcasecmp("template", token)) {
4179 istemplate = 1;
4180 continue;
4181 }
4182 if (!strcasecmp("ignoreerror", token)) {
4183 ignoreerror = 1;
4184 continue;
4185 }
4186 if (ast_begins_with(token, "inherit")) {
4187 char *c = ast_strsep(&token, '=', AST_STRSEP_STRIP);
4188 c = ast_strsep(&token, '=', AST_STRSEP_STRIP);
4189 if (c) {
4190 inherit = ast_strdup(c);
4191 }
4192 continue;
4193 }
4194 if (ast_begins_with(token, "catfilter")) {
4195 char *c = ast_strsep(&token, '=', AST_STRSEP_STRIP);
4196 c = ast_strsep(&token, '=', AST_STRSEP_STRIP);
4197 if (c) {
4198 catfilter = ast_strdup(c);
4199 }
4200 continue;
4201 }
4202 }
4203 }
4204
4205 if (!strcasecmp(action, "newcat")) {
4206 struct ast_category *template;
4207 char *tmpl_name = NULL;
4208
4209 if (!allowdups) {
4210 if (ast_category_get(cfg, cat, "TEMPLATES=include")) {
4211 if (ignoreerror) {
4212 continue;
4213 } else {
4214 result = FAILURE_NEWCAT; /* already exist */
4215 break;
4216 }
4217 }
4218 }
4219
4220 if (istemplate) {
4221 category = ast_category_new_template(cat, dfn, -1);
4222 } else {
4223 category = ast_category_new(cat, dfn, -1);
4224 }
4225
4226 if (!category) {
4228 break;
4229 }
4230
4231 if (inherit) {
4232 while ((tmpl_name = ast_strsep(&inherit, ',', AST_STRSEP_STRIP))) {
4233 if ((template = ast_category_get(cfg, tmpl_name, "TEMPLATES=restrict"))) {
4234 if (ast_category_inherit(category, template)) {
4236 break;
4237 }
4238 } else {
4239 ast_category_destroy(category);
4240 category = NULL;
4241 result = FAILURE_TEMPLATE; /* template not found */
4242 break;
4243 }
4244 }
4245 }
4246
4247 if (category != NULL) {
4248 if (ast_strlen_zero(match)) {
4249 ast_category_append(cfg, category);
4250 } else {
4251 if (ast_category_insert(cfg, category, match)) {
4252 ast_category_destroy(category);
4254 break;
4255 }
4256 }
4257 }
4258 } else if (!strcasecmp(action, "renamecat")) {
4259 if (ast_strlen_zero(value)) {
4261 break;
4262 }
4263
4264 foundcat = 0;
4265 while ((category = ast_category_browse_filtered(cfg, cat, category, catfilter))) {
4266 ast_category_rename(category, value);
4267 foundcat = 1;
4268 }
4269
4270 if (!foundcat) {
4272 break;
4273 }
4274 } else if (!strcasecmp(action, "delcat")) {
4275 foundcat = 0;
4276 while ((category = ast_category_browse_filtered(cfg, cat, category, catfilter))) {
4277 category = ast_category_delete(cfg, category);
4278 foundcat = 1;
4279 }
4280
4281 if (!foundcat && !ignoreerror) {
4283 break;
4284 }
4285 } else if (!strcasecmp(action, "emptycat")) {
4286 foundcat = 0;
4287 while ((category = ast_category_browse_filtered(cfg, cat, category, catfilter))) {
4288 ast_category_empty(category);
4289 foundcat = 1;
4290 }
4291
4292 if (!foundcat) {
4294 break;
4295 }
4296 } else if (!strcasecmp(action, "update")) {
4297 if (ast_strlen_zero(var)) {
4299 break;
4300 }
4301
4302 foundcat = 0;
4303 foundvar = 0;
4304 while ((category = ast_category_browse_filtered(cfg, cat, category, catfilter))) {
4305 if (!ast_variable_update(category, var, value, match, object)) {
4306 foundvar = 1;
4307 }
4308 foundcat = 1;
4309 }
4310
4311 if (!foundcat) {
4313 break;
4314 }
4315
4316 if (!foundvar) {
4318 break;
4319 }
4320 } else if (!strcasecmp(action, "delete")) {
4321 if ((ast_strlen_zero(var) && ast_strlen_zero(line))) {
4323 break;
4324 }
4325
4326 foundcat = 0;
4327 foundvar = 0;
4328 while ((category = ast_category_browse_filtered(cfg, cat, category, catfilter))) {
4329 if (!ast_variable_delete(category, var, match, line)) {
4330 foundvar = 1;
4331 }
4332 foundcat = 1;
4333 }
4334
4335 if (!foundcat) {
4337 break;
4338 }
4339
4340 if (!foundvar && !ignoreerror) {
4342 break;
4343 }
4344 } else if (!strcasecmp(action, "append")) {
4345 if (ast_strlen_zero(var)) {
4347 break;
4348 }
4349
4350 foundcat = 0;
4351 while ((category = ast_category_browse_filtered(cfg, cat, category, catfilter))) {
4352 if (!(v = ast_variable_new(var, value, dfn))) {
4354 break;
4355 }
4356 if (object || (match && !strcasecmp(match, "object"))) {
4357 v->object = 1;
4358 }
4359 ast_variable_append(category, v);
4360 foundcat = 1;
4361 }
4362
4363 if (!foundcat) {
4365 break;
4366 }
4367 } else if (!strcasecmp(action, "insert")) {
4368 if (ast_strlen_zero(var) || ast_strlen_zero(line)) {
4370 break;
4371 }
4372
4373 foundcat = 0;
4374 while ((category = ast_category_browse_filtered(cfg, cat, category, catfilter))) {
4375 if (!(v = ast_variable_new(var, value, dfn))) {
4377 break;
4378 }
4379 ast_variable_insert(category, v, line);
4380 foundcat = 1;
4381 }
4382
4383 if (!foundcat) {
4385 break;
4386 }
4387 }
4388 else {
4389 ast_log(LOG_WARNING, "Action-%06d: %s not handled\n", x, action);
4391 break;
4392 }
4393 }
4394 ast_free(str1);
4395 ast_free(str2);
4396 return result;
4397}
4398
4399static int action_updateconfig(struct mansession *s, const struct message *m)
4400{
4401 struct ast_config *cfg;
4402 const char *sfn = astman_get_header(m, "SrcFilename");
4403 const char *dfn = astman_get_header(m, "DstFilename");
4404 int res;
4405 const char *rld = astman_get_header(m, "Reload");
4406 int preserve_effective_context = CONFIG_SAVE_FLAG_PRESERVE_EFFECTIVE_CONTEXT;
4407 const char *preserve_effective_context_string = astman_get_header(m, "PreserveEffectiveContext");
4408 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
4409 enum error_type result;
4410
4411 if (ast_strlen_zero(sfn) || ast_strlen_zero(dfn)) {
4412 astman_send_error(s, m, "Filename not specified");
4413 return 0;
4414 }
4415 if (restrictedFile(sfn) || restrictedFile(dfn)) {
4416 astman_send_error(s, m, "File requires escalated priveledges");
4417 return 0;
4418 }
4419 if (!(cfg = ast_config_load2(sfn, "manager", config_flags))) {
4420 astman_send_error(s, m, "Config file not found");
4421 return 0;
4422 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
4423 astman_send_error(s, m, "Config file has invalid format");
4424 return 0;
4425 }
4426 result = handle_updates(s, m, cfg, dfn);
4427 if (!result) {
4428 ast_include_rename(cfg, sfn, dfn); /* change the include references from dfn to sfn, so things match up */
4429 if (!ast_strlen_zero(preserve_effective_context_string) && !ast_true(preserve_effective_context_string)) {
4430 preserve_effective_context = CONFIG_SAVE_FLAG_NONE;
4431 }
4432 res = ast_config_text_file_save2(dfn, cfg, "Manager", preserve_effective_context);
4433 ast_config_destroy(cfg);
4434 if (res) {
4435 astman_send_error(s, m, "Save of config failed");
4436 return 0;
4437 }
4438 astman_send_ack(s, m, NULL);
4439 if (!ast_strlen_zero(rld)) {
4440 if (ast_true(rld)) {
4441 ast_module_reload(NULL); /* Reload everything */
4442 } else if (!ast_false(rld)) {
4443 ast_module_reload(rld); /* Reload the specific module */
4444 }
4445 }
4446 } else {
4447 ast_config_destroy(cfg);
4448 switch(result) {
4449 case UNKNOWN_ACTION:
4450 astman_send_error(s, m, "Unknown action command");
4451 break;
4452 case UNKNOWN_CATEGORY:
4453 astman_send_error(s, m, "Given category does not exist");
4454 break;
4456 astman_send_error(s, m, "Category not specified");
4457 break;
4459 astman_send_error(s, m, "Problem with category, value, or line (if required)");
4460 break;
4461 case FAILURE_ALLOCATION:
4462 astman_send_error(s, m, "Memory allocation failure, this should not happen");
4463 break;
4464 case FAILURE_NEWCAT:
4465 astman_send_error(s, m, "Create category did not complete successfully");
4466 break;
4467 case FAILURE_DELCAT:
4468 astman_send_error(s, m, "Delete category did not complete successfully");
4469 break;
4470 case FAILURE_EMPTYCAT:
4471 astman_send_error(s, m, "Empty category did not complete successfully");
4472 break;
4473 case FAILURE_UPDATE:
4474 astman_send_error(s, m, "Update did not complete successfully");
4475 break;
4476 case FAILURE_DELETE:
4477 astman_send_error(s, m, "Delete did not complete successfully");
4478 break;
4479 case FAILURE_APPEND:
4480 astman_send_error(s, m, "Append did not complete successfully");
4481 break;
4482 case FAILURE_TEMPLATE:
4483 astman_send_error(s, m, "Template category not found");
4484 break;
4485 }
4486 }
4487 return 0;
4488}
4489
4490static int action_createconfig(struct mansession *s, const struct message *m)
4491{
4492 int fd;
4493 const char *fn = astman_get_header(m, "Filename");
4494 struct ast_str *filepath = ast_str_alloca(PATH_MAX);
4495 ast_str_set(&filepath, 0, "%s/", ast_config_AST_CONFIG_DIR);
4496 ast_str_append(&filepath, 0, "%s", fn);
4497
4498 if ((fd = open(ast_str_buffer(filepath), O_CREAT | O_EXCL, AST_FILE_MODE)) != -1) {
4499 close(fd);
4500 astman_send_ack(s, m, "New configuration file created successfully");
4501 } else {
4502 astman_send_error(s, m, strerror(errno));
4503 }
4504
4505 return 0;
4506}
4507
4508static int action_waitevent(struct mansession *s, const struct message *m)
4509{
4510 const char *timeouts = astman_get_header(m, "Timeout");
4511 int timeout = -1;
4512 int x;
4513 int needexit = 0;
4514 const char *id = astman_get_header(m, "ActionID");
4515 char idText[256];
4516
4517 if (!ast_strlen_zero(id)) {
4518 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
4519 } else {
4520 idText[0] = '\0';
4521 }
4522
4523 if (!ast_strlen_zero(timeouts)) {
4524 sscanf(timeouts, "%30i", &timeout);
4525 if (timeout < -1) {
4526 timeout = -1;
4527 }
4528 /* XXX maybe put an upper bound, or prevent the use of 0 ? */
4529 }
4530
4533 pthread_kill(s->session->waiting_thread, SIGURG);
4534 }
4536
4537 ao2_lock(s->session);
4538
4539 if (s->session->managerid) { /* AMI-over-HTTP session */
4540 /*
4541 * Make sure the timeout is within the expire time of the session,
4542 * as the client will likely abort the request if it does not see
4543 * data coming after some amount of time.
4544 */
4545 time_t now = time(NULL);
4546 int max = s->session->sessiontimeout - now - 10;
4547
4548 if (max < 0) { /* We are already late. Strange but possible. */
4549 max = 0;
4550 }
4551 if (timeout < 0 || timeout > max) {
4552 timeout = max;
4553 }
4554 if (!s->session->send_events) { /* make sure we record events */
4555 s->session->send_events = -1;
4556 }
4557 }
4558 ao2_unlock(s->session);
4559
4561 s->session->waiting_thread = pthread_self(); /* let new events wake up this thread */
4563 ast_debug(1, "Starting waiting for an event!\n");
4564
4565 for (x = 0; x < timeout || timeout < 0; x++) {
4566 ao2_lock(s->session);
4567 if (AST_RWLIST_NEXT(s->session->last_ev, eq_next)) {
4568 needexit = 1;
4569 }
4570 if (s->session->needdestroy) {
4571 needexit = 1;
4572 }
4573 ao2_unlock(s->session);
4574 /* We can have multiple HTTP session point to the same mansession entry.
4575 * The way we deal with it is not very nice: newcomers kick out the previous
4576 * HTTP session. XXX this needs to be improved.
4577 */
4579 if (s->session->waiting_thread != pthread_self()) {
4580 needexit = 1;
4581 }
4583 if (needexit) {
4584 break;
4585 }
4586 if (s->session->managerid == 0) { /* AMI session */
4588 break;
4589 }
4590 } else { /* HTTP session */
4591 sleep(1);
4592 }
4593 }
4594 ast_debug(1, "Finished waiting for an event!\n");
4595
4597 if (s->session->waiting_thread == pthread_self()) {
4598 struct eventqent *eqe = s->session->last_ev;
4599
4602
4603 ao2_lock(s->session);
4604 astman_send_response(s, m, "Success", "Waiting for Event completed.");
4605 while ((eqe = advance_event(eqe))) {
4606 if (((s->session->readperm & eqe->category) == eqe->category)
4607 && ((s->session->send_events & eqe->category) == eqe->category)
4608 && match_filter(s, eqe->eventdata)) {
4609 astman_append(s, "%s", eqe->eventdata);
4610 }
4611 s->session->last_ev = eqe;
4612 }
4613 astman_append(s,
4614 "Event: WaitEventComplete\r\n"
4615 "%s"
4616 "\r\n", idText);
4617 ao2_unlock(s->session);
4618 } else {
4620 ast_debug(1, "Abandoning event request!\n");
4621 }
4622
4623 return 0;
4624}
4625
4626static int action_listcommands(struct mansession *s, const struct message *m)
4627{
4628 struct manager_action *cur;
4630
4631 astman_start_ack(s, m);
4633 AST_RWLIST_TRAVERSE(&actions, cur, list) {
4634 if ((s->session->writeperm & cur->authority) || cur->authority == 0) {
4635 astman_append(s, "%s: %s (Priv: %s)\r\n",
4636 cur->action, cur->synopsis, authority_to_str(cur->authority, &temp));
4637 }
4638 }
4640 astman_append(s, "\r\n");
4641
4642 return 0;
4643}
4644
4645static int action_events(struct mansession *s, const struct message *m)
4646{
4647 const char *mask = astman_get_header(m, "EventMask");
4648 int res, x;
4649 const char *id = astman_get_header(m, "ActionID");
4650 char id_text[256];
4651
4652 if (!ast_strlen_zero(id)) {
4653 snprintf(id_text, sizeof(id_text), "ActionID: %s\r\n", id);
4654 } else {
4655 id_text[0] = '\0';
4656 }
4657
4658 res = set_eventmask(s, mask);
4660 /* if this option is set we should not return a response on
4661 * error, or when all events are set */
4662
4663 if (res > 0) {
4664 for (x = 0; x < ARRAY_LEN(perms); x++) {
4665 if (!strcasecmp(perms[x].label, "all") && res == perms[x].num) {
4666 return 0;
4667 }
4668 }
4669 astman_append(s, "Response: Success\r\n%s"
4670 "Events: On\r\n\r\n", id_text);
4671 } else if (res == 0)
4672 astman_append(s, "Response: Success\r\n%s"
4673 "Events: Off\r\n\r\n", id_text);
4674 return 0;
4675 }
4676
4677 if (res > 0)
4678 astman_append(s, "Response: Success\r\n%s"
4679 "Events: On\r\n\r\n", id_text);
4680 else if (res == 0)
4681 astman_append(s, "Response: Success\r\n%s"
4682 "Events: Off\r\n\r\n", id_text);
4683 else
4684 astman_send_error(s, m, "Invalid event mask");
4685
4686 return 0;
4687}
4688
4689static int action_logoff(struct mansession *s, const struct message *m)
4690{
4691 astman_send_response(s, m, "Goodbye", "Thanks for all the fish.");
4692 return -1;
4693}
4694
4695static int action_login(struct mansession *s, const struct message *m)
4696{
4697
4698 /* still authenticated - don't process again */
4699 if (s->session->authenticated) {
4700 astman_send_ack(s, m, "Already authenticated");
4701 return 0;
4702 }
4703
4704 if (authenticate(s, m)) {
4705 sleep(1);
4706 astman_send_error(s, m, "Authentication failed");
4707 return -1;
4708 }
4709 s->session->authenticated = 1;
4712 ast_verb(2, "%sManager '%s' logged on from %s\n", (s->session->managerid ? "HTTP " : ""), s->session->username, ast_sockaddr_stringify_addr(&s->session->addr));
4713 }
4714 astman_send_ack(s, m, "Authentication accepted");
4719 const char *cat_str = authority_to_str(EVENT_FLAG_SYSTEM, &auth);
4720 long uptime = 0;
4721 long lastreloaded = 0;
4722 struct timeval tmp;
4723 struct timeval curtime = ast_tvnow();
4724
4725 if (ast_startuptime.tv_sec) {
4726 tmp = ast_tvsub(curtime, ast_startuptime);
4727 uptime = tmp.tv_sec;
4728 }
4729
4730 if (ast_lastreloadtime.tv_sec) {
4731 tmp = ast_tvsub(curtime, ast_lastreloadtime);
4732 lastreloaded = tmp.tv_sec;
4733 }
4734
4735 astman_append(s, "Event: FullyBooted\r\n"
4736 "Privilege: %s\r\n"
4737 "Uptime: %ld\r\n"
4738 "LastReload: %ld\r\n"
4739 "Status: Fully Booted\r\n\r\n", cat_str, uptime, lastreloaded);
4740 }
4741 return 0;
4742}
4743
4744static int action_challenge(struct mansession *s, const struct message *m)
4745{
4746 const char *authtype = astman_get_header(m, "AuthType");
4747
4748 if (!strcasecmp(authtype, "MD5")) {
4750 snprintf(s->session->challenge, sizeof(s->session->challenge), "%ld", ast_random());
4751 }
4752 mansession_lock(s);
4753 astman_start_ack(s, m);
4754 astman_append(s, "Challenge: %s\r\n\r\n", s->session->challenge);
4756 } else {
4757 astman_send_error(s, m, "Must specify AuthType");
4758 }
4759 return 0;
4760}
4761
4763 const struct message *m, manager_hangup_handler_t hangup_handler,
4764 manager_hangup_cause_validator_t cause_validator)
4765{
4766 struct ast_channel *c = NULL;
4767 int causecode = 0; /* all values <= 0 mean 'do not set hangupcause in channel' */
4768 const char *id = astman_get_header(m, "ActionID");
4769 const char *name_or_regex = astman_get_header(m, "Channel");
4770 const char *cause = astman_get_header(m, "Cause");
4771 char idText[256];
4772 regex_t regexbuf;
4773 struct ast_channel_iterator *iter = NULL;
4774 struct ast_str *regex_string;
4775 int channels_matched = 0;
4776
4777 if (ast_strlen_zero(name_or_regex)) {
4778 astman_send_error(s, m, "No channel specified");
4779 return 0;
4780 }
4781
4782 if (!ast_strlen_zero(id)) {
4783 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
4784 } else {
4785 idText[0] = '\0';
4786 }
4787
4788 if (cause_validator) {
4789 causecode = cause_validator(name_or_regex, cause);
4790 } else if (!ast_strlen_zero(cause)) {
4791 char *endptr;
4792 causecode = strtol(cause, &endptr, 10);
4793 if (causecode < 0 || causecode > 127 || *endptr != '\0') {
4794 ast_log(LOG_NOTICE, "Invalid 'Cause: %s' in manager action Hangup\n", cause);
4795 /* keep going, better to hangup without cause than to not hang up at all */
4796 causecode = 0; /* do not set channel's hangupcause */
4797 }
4798 }
4799
4800 /************************************************/
4801 /* Regular explicit match channel byname hangup */
4802
4803 if (name_or_regex[0] != '/') {
4804 if (!(c = ast_channel_get_by_name(name_or_regex))) {
4805 ast_log(LOG_NOTICE, "Request to hangup non-existent channel: %s\n",
4806 name_or_regex);
4807 astman_send_error(s, m, "No such channel");
4808 return 0;
4809 }
4810
4811 ast_verb(3, "%sManager '%s' from %s, hanging up channel: %s\n",
4812 (s->session->managerid ? "HTTP " : ""),
4813 s->session->username,
4816
4817 hangup_handler(c, causecode);
4819
4820 astman_send_ack(s, m, "Channel Hungup");
4821
4822 return 0;
4823 }
4824
4825 /***********************************************/
4826 /* find and hangup any channels matching regex */
4827
4828 regex_string = ast_str_create(strlen(name_or_regex));
4829 if (!regex_string) {
4830 astman_send_error(s, m, "Memory Allocation Failure");
4831 return 0;
4832 }
4833
4834 /* Make "/regex/" into "regex" */
4835 if (ast_regex_string_to_regex_pattern(name_or_regex, &regex_string) != 0) {
4836 astman_send_error(s, m, "Regex format invalid, Channel param should be /regex/");
4837 ast_free(regex_string);
4838 return 0;
4839 }
4840
4841 /* if regex compilation fails, hangup fails */
4842 if (regcomp(&regexbuf, ast_str_buffer(regex_string), REG_EXTENDED | REG_NOSUB)) {
4843 astman_send_error_va(s, m, "Regex compile failed on: %s", name_or_regex);
4844 ast_free(regex_string);
4845 return 0;
4846 }