413adf29c971e64dacac731db613020d9fbe940f
[asterisk/asterisk.git] / main / manager.c
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  * \extref 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 /*! \addtogroup Group_AMI AMI functions
40 */
41 /*! @{
42  Doxygen group */
43
44 /*** MODULEINFO
45         <support_level>core</support_level>
46  ***/
47
48 #include "asterisk.h"
49
50 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
51
52 #include "asterisk/_private.h"
53 #include "asterisk/paths.h"     /* use various ast_config_AST_* */
54 #include <ctype.h>
55 #include <sys/time.h>
56 #include <signal.h>
57 #include <sys/mman.h>
58 #include <sys/types.h>
59 #include <regex.h>
60
61 #include "asterisk/channel.h"
62 #include "asterisk/file.h"
63 #include "asterisk/manager.h"
64 #include "asterisk/module.h"
65 #include "asterisk/config.h"
66 #include "asterisk/callerid.h"
67 #include "asterisk/lock.h"
68 #include "asterisk/cli.h"
69 #include "asterisk/app.h"
70 #include "asterisk/pbx.h"
71 #include "asterisk/md5.h"
72 #include "asterisk/acl.h"
73 #include "asterisk/utils.h"
74 #include "asterisk/tcptls.h"
75 #include "asterisk/http.h"
76 #include "asterisk/ast_version.h"
77 #include "asterisk/threadstorage.h"
78 #include "asterisk/linkedlists.h"
79 #include "asterisk/term.h"
80 #include "asterisk/astobj2.h"
81 #include "asterisk/features.h"
82 #include "asterisk/security_events.h"
83 #include "asterisk/aoc.h"
84 #include "asterisk/stringfields.h"
85
86 /*** DOCUMENTATION
87         <manager name="Ping" language="en_US">
88                 <synopsis>
89                         Keepalive command.
90                 </synopsis>
91                 <syntax>
92                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
93                 </syntax>
94                 <description>
95                         <para>A 'Ping' action will ellicit a 'Pong' response. Used to keep the
96                         manager connection open.</para>
97                 </description>
98         </manager>
99         <manager name="Events" language="en_US">
100                 <synopsis>
101                         Control Event Flow.
102                 </synopsis>
103                 <syntax>
104                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
105                         <parameter name="EventMask" required="true">
106                                 <enumlist>
107                                         <enum name="on">
108                                                 <para>If all events should be sent.</para>
109                                         </enum>
110                                         <enum name="off">
111                                                 <para>If no events should be sent.</para>
112                                         </enum>
113                                         <enum name="system,call,log,...">
114                                                 <para>To select which flags events should have to be sent.</para>
115                                         </enum>
116                                 </enumlist>
117                         </parameter>
118                 </syntax>
119                 <description>
120                         <para>Enable/Disable sending of events to this manager client.</para>
121                 </description>
122         </manager>
123         <manager name="Logoff" language="en_US">
124                 <synopsis>
125                         Logoff Manager.
126                 </synopsis>
127                 <syntax>
128                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
129                 </syntax>
130                 <description>
131                         <para>Logoff the current manager session.</para>
132                 </description>
133         </manager>
134         <manager name="Login" language="en_US">
135                 <synopsis>
136                         Login Manager.
137                 </synopsis>
138                 <syntax>
139                         <parameter name="ActionID">
140                                 <para>ActionID for this transaction. Will be returned.</para>
141                         </parameter>
142                         <parameter name="Username" required="true">
143                                 <para>Username to login with as specified in manager.conf.</para>
144                         </parameter>
145                         <parameter name="Secret">
146                                 <para>Secret to login with as specified in manager.conf.</para>
147                         </parameter>
148                 </syntax>
149                 <description>
150                         <para>Login Manager.</para>
151                 </description>
152         </manager>
153         <manager name="Challenge" language="en_US">
154                 <synopsis>
155                         Generate Challenge for MD5 Auth.
156                 </synopsis>
157                 <syntax>
158                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
159                         <parameter name="AuthType" required="true">
160                                 <para>Digest algorithm to use in the challenge. Valid values are:</para>
161                                 <enumlist>
162                                         <enum name="MD5" />
163                                 </enumlist>
164                         </parameter>
165                 </syntax>
166                 <description>
167                         <para>Generate a challenge for MD5 authentication.</para>
168                 </description>
169         </manager>
170         <manager name="Hangup" language="en_US">
171                 <synopsis>
172                         Hangup channel.
173                 </synopsis>
174                 <syntax>
175                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
176                         <parameter name="Channel" required="true">
177                                 <para>The exact channel name to be hungup, or to use a regular expression, set this parameter to: /regex/</para>
178                                 <para>Example exact channel: SIP/provider-0000012a</para>
179                                 <para>Example regular expression: /^SIP/provider-.*$/</para>
180                         </parameter>
181                         <parameter name="Cause">
182                                 <para>Numeric hangup cause.</para>
183                         </parameter>
184                 </syntax>
185                 <description>
186                         <para>Hangup a channel.</para>
187                 </description>
188         </manager>
189         <manager name="Status" language="en_US">
190                 <synopsis>
191                         List channel status.
192                 </synopsis>
193                 <syntax>
194                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
195                         <parameter name="Channel" required="true">
196                                 <para>The name of the channel to query for status.</para>
197                         </parameter>
198                         <parameter name="Variables">
199                                 <para>Comma <literal>,</literal> separated list of variable to include.</para>
200                         </parameter>
201                 </syntax>
202                 <description>
203                         <para>Will return the status information of each channel along with the
204                         value for the specified channel variables.</para>
205                 </description>
206         </manager>
207         <manager name="Setvar" language="en_US">
208                 <synopsis>
209                         Set a channel variable.
210                 </synopsis>
211                 <syntax>
212                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
213                         <parameter name="Channel">
214                                 <para>Channel to set variable for.</para>
215                         </parameter>
216                         <parameter name="Variable" required="true">
217                                 <para>Variable name.</para>
218                         </parameter>
219                         <parameter name="Value" required="true">
220                                 <para>Variable value.</para>
221                         </parameter>
222                 </syntax>
223                 <description>
224                         <para>Set a global or local channel variable.</para>
225                         <note>
226                                 <para>If a channel name is not provided then the variable is global.</para>
227                         </note>
228                 </description>
229         </manager>
230         <manager name="Getvar" language="en_US">
231                 <synopsis>
232                         Gets a channel variable.
233                 </synopsis>
234                 <syntax>
235                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
236                         <parameter name="Channel">
237                                 <para>Channel to read variable from.</para>
238                         </parameter>
239                         <parameter name="Variable" required="true">
240                                 <para>Variable name.</para>
241                         </parameter>
242                 </syntax>
243                 <description>
244                         <para>Get the value of a global or local channel variable.</para>
245                         <note>
246                                 <para>If a channel name is not provided then the variable is global.</para>
247                         </note>
248                 </description>
249         </manager>
250         <manager name="GetConfig" language="en_US">
251                 <synopsis>
252                         Retrieve configuration.
253                 </synopsis>
254                 <syntax>
255                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
256                         <parameter name="Filename" required="true">
257                                 <para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
258                         </parameter>
259                         <parameter name="Category">
260                                 <para>Category in configuration file.</para>
261                         </parameter>
262                 </syntax>
263                 <description>
264                         <para>This action will dump the contents of a configuration
265                         file by category and contents or optionally by specified category only.</para>
266                 </description>
267         </manager>
268         <manager name="GetConfigJSON" language="en_US">
269                 <synopsis>
270                         Retrieve configuration (JSON format).
271                 </synopsis>
272                 <syntax>
273                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
274                         <parameter name="Filename" required="true">
275                                 <para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
276                         </parameter>
277                 </syntax>
278                 <description>
279                         <para>This action will dump the contents of a configuration file by category
280                         and contents in JSON format. This only makes sense to be used using rawman over
281                         the HTTP interface.</para>
282                 </description>
283         </manager>
284         <manager name="UpdateConfig" language="en_US">
285                 <synopsis>
286                         Update basic configuration.
287                 </synopsis>
288                 <syntax>
289                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
290                         <parameter name="SrcFilename" required="true">
291                                 <para>Configuration filename to read (e.g. <filename>foo.conf</filename>).</para>
292                         </parameter>
293                         <parameter name="DstFilename" required="true">
294                                 <para>Configuration filename to write (e.g. <filename>foo.conf</filename>)</para>
295                         </parameter>
296                         <parameter name="Reload">
297                                 <para>Whether or not a reload should take place (or name of specific module).</para>
298                         </parameter>
299                         <parameter name="Action-XXXXXX">
300                                 <para>Action to take.</para>
301                                 <para>X's represent 6 digit number beginning with 000000.</para>
302                                 <enumlist>
303                                         <enum name="NewCat" />
304                                         <enum name="RenameCat" />
305                                         <enum name="DelCat" />
306                                         <enum name="EmptyCat" />
307                                         <enum name="Update" />
308                                         <enum name="Delete" />
309                                         <enum name="Append" />
310                                         <enum name="Insert" />
311                                 </enumlist>
312                         </parameter>
313                         <parameter name="Cat-XXXXXX">
314                                 <para>Category to operate on.</para>
315                                 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
316                         </parameter>
317                         <parameter name="Var-XXXXXX">
318                                 <para>Variable to work on.</para>
319                                 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
320                         </parameter>
321                         <parameter name="Value-XXXXXX">
322                                 <para>Value to work on.</para>
323                                 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
324                         </parameter>
325                         <parameter name="Match-XXXXXX">
326                                 <para>Extra match required to match line.</para>
327                                 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
328                         </parameter>
329                         <parameter name="Line-XXXXXX">
330                                 <para>Line in category to operate on (used with delete and insert actions).</para>
331                                 <xi:include xpointer="xpointer(/docs/manager[@name='UpdateConfig']/syntax/parameter[@name='Action-XXXXXX']/para[2])" />
332                         </parameter>
333                 </syntax>
334                 <description>
335                         <para>This action will modify, create, or delete configuration elements
336                         in Asterisk configuration files.</para>
337                 </description>
338         </manager>
339         <manager name="CreateConfig" language="en_US">
340                 <synopsis>
341                         Creates an empty file in the configuration directory.
342                 </synopsis>
343                 <syntax>
344                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
345                         <parameter name="Filename" required="true">
346                                 <para>The configuration filename to create (e.g. <filename>foo.conf</filename>).</para>
347                         </parameter>
348                 </syntax>
349                 <description>
350                         <para>This action will create an empty file in the configuration
351                         directory. This action is intended to be used before an UpdateConfig
352                         action.</para>
353                 </description>
354         </manager>
355         <manager name="ListCategories" language="en_US">
356                 <synopsis>
357                         List categories in configuration file.
358                 </synopsis>
359                 <syntax>
360                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
361                         <parameter name="Filename" required="true">
362                                 <para>Configuration filename (e.g. <filename>foo.conf</filename>).</para>
363                         </parameter>
364                 </syntax>
365                 <description>
366                         <para>This action will dump the categories in a given file.</para>
367                 </description>
368         </manager>
369         <manager name="Redirect" language="en_US">
370                 <synopsis>
371                         Redirect (transfer) a call.
372                 </synopsis>
373                 <syntax>
374                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
375                         <parameter name="Channel" required="true">
376                                 <para>Channel to redirect.</para>
377                         </parameter>
378                         <parameter name="ExtraChannel">
379                                 <para>Second call leg to transfer (optional).</para>
380                         </parameter>
381                         <parameter name="Exten" required="true">
382                                 <para>Extension to transfer to.</para>
383                         </parameter>
384                         <parameter name="ExtraExten">
385                                 <para>Extension to transfer extrachannel to (optional).</para>
386                         </parameter>
387                         <parameter name="Context" required="true">
388                                 <para>Context to transfer to.</para>
389                         </parameter>
390                         <parameter name="ExtraContext">
391                                 <para>Context to transfer extrachannel to (optional).</para>
392                         </parameter>
393                         <parameter name="Priority" required="true">
394                                 <para>Priority to transfer to.</para>
395                         </parameter>
396                         <parameter name="ExtraPriority">
397                                 <para>Priority to transfer extrachannel to (optional).</para>
398                         </parameter>
399                 </syntax>
400                 <description>
401                         <para>Redirect (transfer) a call.</para>
402                 </description>
403         </manager>
404         <manager name="Atxfer" language="en_US">
405                 <synopsis>
406                         Attended transfer.
407                 </synopsis>
408                 <syntax>
409                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
410                         <parameter name="Channel" required="true">
411                                 <para>Transferer's channel.</para>
412                         </parameter>
413                         <parameter name="Exten" required="true">
414                                 <para>Extension to transfer to.</para>
415                         </parameter>
416                         <parameter name="Context" required="true">
417                                 <para>Context to transfer to.</para>
418                         </parameter>
419                         <parameter name="Priority" required="true">
420                                 <para>Priority to transfer to.</para>
421                         </parameter>
422                 </syntax>
423                 <description>
424                         <para>Attended transfer.</para>
425                 </description>
426         </manager>
427         <manager name="Originate" language="en_US">
428                 <synopsis>
429                         Originate a call.
430                 </synopsis>
431                 <syntax>
432                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
433                         <parameter name="Channel" required="true">
434                                 <para>Channel name to call.</para>
435                         </parameter>
436                         <parameter name="Exten">
437                                 <para>Extension to use (requires <literal>Context</literal> and
438                                 <literal>Priority</literal>)</para>
439                         </parameter>
440                         <parameter name="Context">
441                                 <para>Context to use (requires <literal>Exten</literal> and
442                                 <literal>Priority</literal>)</para>
443                         </parameter>
444                         <parameter name="Priority">
445                                 <para>Priority to use (requires <literal>Exten</literal> and
446                                 <literal>Context</literal>)</para>
447                         </parameter>
448                         <parameter name="Application">
449                                 <para>Application to execute.</para>
450                         </parameter>
451                         <parameter name="Data">
452                                 <para>Data to use (requires <literal>Application</literal>).</para>
453                         </parameter>
454                         <parameter name="Timeout" default="30000">
455                                 <para>How long to wait for call to be answered (in ms.).</para>
456                         </parameter>
457                         <parameter name="CallerID">
458                                 <para>Caller ID to be set on the outgoing channel.</para>
459                         </parameter>
460                         <parameter name="Variable">
461                                 <para>Channel variable to set, multiple Variable: headers are allowed.</para>
462                         </parameter>
463                         <parameter name="Account">
464                                 <para>Account code.</para>
465                         </parameter>
466                         <parameter name="Async">
467                                 <para>Set to <literal>true</literal> for fast origination.</para>
468                         </parameter>
469                         <parameter name="Codecs">
470                                 <para>Comma-separated list of codecs to use for this call.</para>
471                         </parameter>
472                 </syntax>
473                 <description>
474                         <para>Generates an outgoing call to a
475                         <replaceable>Extension</replaceable>/<replaceable>Context</replaceable>/<replaceable>Priority</replaceable>
476                         or <replaceable>Application</replaceable>/<replaceable>Data</replaceable></para>
477                 </description>
478         </manager>
479         <manager name="Command" language="en_US">
480                 <synopsis>
481                         Execute Asterisk CLI Command.
482                 </synopsis>
483                 <syntax>
484                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
485                         <parameter name="Command" required="true">
486                                 <para>Asterisk CLI command to run.</para>
487                         </parameter>
488                 </syntax>
489                 <description>
490                         <para>Run a CLI command.</para>
491                 </description>
492         </manager>
493         <manager name="ExtensionState" language="en_US">
494                 <synopsis>
495                         Check Extension Status.
496                 </synopsis>
497                 <syntax>
498                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
499                         <parameter name="Exten" required="true">
500                                 <para>Extension to check state on.</para>
501                         </parameter>
502                         <parameter name="Context" required="true">
503                                 <para>Context for extension.</para>
504                         </parameter>
505                 </syntax>
506                 <description>
507                         <para>Report the extension state for given extension. If the extension has a hint,
508                         will use devicestate to check the status of the device connected to the extension.</para>
509                         <para>Will return an <literal>Extension Status</literal> message. The response will include
510                         the hint for the extension and the status.</para>
511                 </description>
512         </manager>
513         <manager name="AbsoluteTimeout" language="en_US">
514                 <synopsis>
515                         Set absolute timeout.
516                 </synopsis>
517                 <syntax>
518                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
519                         <parameter name="Channel" required="true">
520                                 <para>Channel name to hangup.</para>
521                         </parameter>
522                         <parameter name="Timeout" required="true">
523                                 <para>Maximum duration of the call (sec).</para>
524                         </parameter>
525                 </syntax>
526                 <description>
527                         <para>Hangup a channel after a certain time. Acknowledges set time with
528                         <literal>Timeout Set</literal> message.</para>
529                 </description>
530         </manager>
531         <manager name="MailboxStatus" language="en_US">
532                 <synopsis>
533                         Check mailbox.
534                 </synopsis>
535                 <syntax>
536                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
537                         <parameter name="Mailbox" required="true">
538                                 <para>Full mailbox ID <replaceable>mailbox</replaceable>@<replaceable>vm-context</replaceable>.</para>
539                         </parameter>
540                 </syntax>
541                 <description>
542                         <para>Checks a voicemail account for status.</para>
543                         <para>Returns number of messages.</para>
544                         <para>Message: Mailbox Status.</para>
545                         <para>Mailbox: <replaceable>mailboxid</replaceable>.</para>
546                         <para>Waiting: <replaceable>count</replaceable>.</para>
547                 </description>
548         </manager>
549         <manager name="MailboxCount" language="en_US">
550                 <synopsis>
551                         Check Mailbox Message Count.
552                 </synopsis>
553                 <syntax>
554                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
555                         <parameter name="Mailbox" required="true">
556                                 <para>Full mailbox ID <replaceable>mailbox</replaceable>@<replaceable>vm-context</replaceable>.</para>
557                         </parameter>
558                 </syntax>
559                 <description>
560                         <para>Checks a voicemail account for new messages.</para>
561                         <para>Returns number of urgent, new and old messages.</para>
562                         <para>Message: Mailbox Message Count</para>
563                         <para>Mailbox: <replaceable>mailboxid</replaceable></para>
564                         <para>UrgentMessages: <replaceable>count</replaceable></para>
565                         <para>NewMessages: <replaceable>count</replaceable></para>
566                         <para>OldMessages: <replaceable>count</replaceable></para>
567                 </description>
568         </manager>
569         <manager name="ListCommands" language="en_US">
570                 <synopsis>
571                         List available manager commands.
572                 </synopsis>
573                 <syntax>
574                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
575                 </syntax>
576                 <description>
577                         <para>Returns the action name and synopsis for every action that
578                         is available to the user.</para>
579                 </description>
580         </manager>
581         <manager name="SendText" language="en_US">
582                 <synopsis>
583                         Send text message to channel.
584                 </synopsis>
585                 <syntax>
586                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
587                         <parameter name="Channel" required="true">
588                                 <para>Channel to send message to.</para>
589                         </parameter>
590                         <parameter name="Message" required="true">
591                                 <para>Message to send.</para>
592                         </parameter>
593                 </syntax>
594                 <description>
595                         <para>Sends A Text Message to a channel while in a call.</para>
596                 </description>
597         </manager>
598         <manager name="UserEvent" language="en_US">
599                 <synopsis>
600                         Send an arbitrary event.
601                 </synopsis>
602                 <syntax>
603                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
604                         <parameter name="UserEvent" required="true">
605                                 <para>Event string to send.</para>
606                         </parameter>
607                         <parameter name="Header1">
608                                 <para>Content1.</para>
609                         </parameter>
610                         <parameter name="HeaderN">
611                                 <para>ContentN.</para>
612                         </parameter>
613                 </syntax>
614                 <description>
615                         <para>Send an event to manager sessions.</para>
616                 </description>
617         </manager>
618         <manager name="WaitEvent" language="en_US">
619                 <synopsis>
620                         Wait for an event to occur.
621                 </synopsis>
622                 <syntax>
623                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
624                         <parameter name="Timeout" required="true">
625                                 <para>Maximum time (in seconds) to wait for events, <literal>-1</literal> means forever.</para>
626                         </parameter>
627                 </syntax>
628                 <description>
629                         <para>This action will ellicit a <literal>Success</literal> response. Whenever
630                         a manager event is queued. Once WaitEvent has been called on an HTTP manager
631                         session, events will be generated and queued.</para>
632                 </description>
633         </manager>
634         <manager name="CoreSettings" language="en_US">
635                 <synopsis>
636                         Show PBX core settings (version etc).
637                 </synopsis>
638                 <syntax>
639                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
640                 </syntax>
641                 <description>
642                         <para>Query for Core PBX settings.</para>
643                 </description>
644         </manager>
645         <manager name="CoreStatus" language="en_US">
646                 <synopsis>
647                         Show PBX core status variables.
648                 </synopsis>
649                 <syntax>
650                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
651                 </syntax>
652                 <description>
653                         <para>Query for Core PBX status.</para>
654                 </description>
655         </manager>
656         <manager name="Reload" language="en_US">
657                 <synopsis>
658                         Send a reload event.
659                 </synopsis>
660                 <syntax>
661                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
662                         <parameter name="Module">
663                                 <para>Name of the module to reload.</para>
664                         </parameter>
665                 </syntax>
666                 <description>
667                         <para>Send a reload event.</para>
668                 </description>
669         </manager>
670         <manager name="CoreShowChannels" language="en_US">
671                 <synopsis>
672                         List currently active channels.
673                 </synopsis>
674                 <syntax>
675                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
676                 </syntax>
677                 <description>
678                         <para>List currently defined channels and some information about them.</para>
679                 </description>
680         </manager>
681         <manager name="ModuleLoad" language="en_US">
682                 <synopsis>
683                         Module management.
684                 </synopsis>
685                 <syntax>
686                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
687                         <parameter name="Module">
688                                 <para>Asterisk module name (including .so extension) or subsystem identifier:</para>
689                                 <enumlist>
690                                         <enum name="cdr" />
691                                         <enum name="enum" />
692                                         <enum name="dnsmgr" />
693                                         <enum name="extconfig" />
694                                         <enum name="manager" />
695                                         <enum name="rtp" />
696                                         <enum name="http" />
697                                 </enumlist>
698                         </parameter>
699                         <parameter name="LoadType" required="true">
700                                 <para>The operation to be done on module.</para>
701                                 <enumlist>
702                                         <enum name="load" />
703                                         <enum name="unload" />
704                                         <enum name="reload" />
705                                 </enumlist>
706                                 <para>If no module is specified for a <literal>reload</literal> loadtype,
707                                 all modules are reloaded.</para>
708                         </parameter>
709                 </syntax>
710                 <description>
711                         <para>Loads, unloads or reloads an Asterisk module in a running system.</para>
712                 </description>
713         </manager>
714         <manager name="ModuleCheck" language="en_US">
715                 <synopsis>
716                         Check if module is loaded.
717                 </synopsis>
718                 <syntax>
719                         <parameter name="Module" required="true">
720                                 <para>Asterisk module name (not including extension).</para>
721                         </parameter>
722                 </syntax>
723                 <description>
724                         <para>Checks if Asterisk module is loaded. Will return Success/Failure.
725                         For success returns, the module revision number is included.</para>
726                 </description>
727         </manager>
728         <manager name="AOCMessage" language="en_US">
729                 <synopsis>
730                         Generate an Advice of Charge message on a channel.
731                 </synopsis>
732                 <syntax>
733                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
734                         <parameter name="Channel" required="true">
735                                 <para>Channel name to generate the AOC message on.</para>
736                         </parameter>
737                         <parameter name="ChannelPrefix">
738                                 <para>Partial channel prefix.  By using this option one can match the beginning part
739                                 of a channel name without having to put the entire name in.  For example
740                                 if a channel name is SIP/snom-00000001 and this value is set to SIP/snom, then
741                                 that channel matches and the message will be sent.  Note however that only
742                                 the first matched channel has the message sent on it. </para>
743                         </parameter>
744                         <parameter name="MsgType" required="true">
745                                 <para>Defines what type of AOC message to create, AOC-D or AOC-E</para>
746                                 <enumlist>
747                                         <enum name="D" />
748                                         <enum name="E" />
749                                 </enumlist>
750                         </parameter>
751                         <parameter name="ChargeType" required="true">
752                                 <para>Defines what kind of charge this message represents.</para>
753                                 <enumlist>
754                                         <enum name="NA" />
755                                         <enum name="FREE" />
756                                         <enum name="Currency" />
757                                         <enum name="Unit" />
758                                 </enumlist>
759                         </parameter>
760                         <parameter name="UnitAmount(0)">
761                                 <para>This represents the amount of units charged. The ETSI AOC standard specifies that
762                                 this value along with the optional UnitType value are entries in a list.  To accommodate this
763                                 these values take an index value starting at 0 which can be used to generate this list of
764                                 unit entries.  For Example, If two unit entires were required this could be achieved by setting the
765                                 paramter UnitAmount(0)=1234 and UnitAmount(1)=5678.  Note that UnitAmount at index 0 is
766                                 required when ChargeType=Unit, all other entries in the list are optional.
767                                 </para>
768                         </parameter>
769                         <parameter name="UnitType(0)">
770                                 <para>Defines the type of unit.  ETSI AOC standard specifies this as an integer
771                                 value between 1 and 16, but this value is left open to accept any positive
772                                 integer.  Like the UnitAmount parameter, this value represents a list entry
773                                 and has an index parameter that starts at 0.
774                                 </para>
775                         </parameter>
776                         <parameter name="CurrencyName">
777                                 <para>Specifies the currency's name.  Note that this value is truncated after 10 characters.</para>
778                         </parameter>
779                         <parameter name="CurrencyAmount">
780                                 <para>Specifies the charge unit amount as a positive integer.  This value is required
781                                 when ChargeType==Currency.</para>
782                         </parameter>
783                         <parameter name="CurrencyMultiplier">
784                                 <para>Specifies the currency multiplier.  This value is required when ChargeType==Currency.</para>
785                                 <enumlist>
786                                         <enum name="OneThousandth" />
787                                         <enum name="OneHundredth" />
788                                         <enum name="OneTenth" />
789                                         <enum name="One" />
790                                         <enum name="Ten" />
791                                         <enum name="Hundred" />
792                                         <enum name="Thousand" />
793                                 </enumlist>
794                         </parameter>
795                         <parameter name="TotalType" default="Total">
796                                 <para>Defines what kind of AOC-D total is represented.</para>
797                                 <enumlist>
798                                         <enum name="Total" />
799                                         <enum name="SubTotal" />
800                                 </enumlist>
801                         </parameter>
802                         <parameter name="AOCBillingId">
803                                 <para>Represents a billing ID associated with an AOC-D or AOC-E message. Note
804                                 that only the first 3 items of the enum are valid AOC-D billing IDs</para>
805                                 <enumlist>
806                                         <enum name="Normal" />
807                                         <enum name="ReverseCharge" />
808                                         <enum name="CreditCard" />
809                                         <enum name="CallFwdUnconditional" />
810                                         <enum name="CallFwdBusy" />
811                                         <enum name="CallFwdNoReply" />
812                                         <enum name="CallDeflection" />
813                                         <enum name="CallTransfer" />
814                                 </enumlist>
815                         </parameter>
816                         <parameter name="ChargingAssociationId">
817                                 <para>Charging association identifier.  This is optional for AOC-E and can be
818                                 set to any value between -32768 and 32767</para>
819                         </parameter>
820                         <parameter name="ChargingAssociationNumber">
821                                 <para>Represents the charging association party number.  This value is optional
822                                 for AOC-E.</para>
823                         </parameter>
824                         <parameter name="ChargingAssociationPlan">
825                                 <para>Integer representing the charging plan associated with the ChargingAssociationNumber.
826                                 The value is bits 7 through 1 of the Q.931 octet containing the type-of-number and
827                                 numbering-plan-identification fields.</para>
828                         </parameter>
829                 </syntax>
830                 <description>
831                         <para>Generates an AOC-D or AOC-E message on a channel.</para>
832                 </description>
833         </manager>
834         <manager name="Filter" language="en_US">
835                 <synopsis>
836                         Dynamically add filters for the current manager session.
837                 </synopsis>
838                 <syntax>
839                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
840                         <parameter name="Operation">
841                                 <enumlist>
842                                         <enum name="Add">
843                                                 <para>Add a filter.</para>
844                                         </enum>
845                                 </enumlist>
846                         </parameter>
847                         <parameter name="Filter">
848                                 <para>Filters can be whitelist or blacklist</para>
849                                 <para>Example whitelist filter: "Event: Newchannel"</para>
850                                 <para>Example blacklist filter: "!Channel: DAHDI.*"</para>
851                                 <para>This filter option is used to whitelist or blacklist events per user to be
852                                 reported with regular expressions and are allowed if both the regex matches
853                                 and the user has read access as defined in manager.conf. Filters are assumed to be for whitelisting
854                                 unless preceeded by an exclamation point, which marks it as being black.
855                                 Evaluation of the filters is as follows:</para>
856                                 <para>- If no filters are configured all events are reported as normal.</para>
857                                 <para>- If there are white filters only: implied black all filter processed first, then white filters.</para>
858                                 <para>- If there are black filters only: implied white all filter processed first, then black filters.</para>
859                                 <para>- If there are both white and black filters: implied black all filter processed first, then white
860                                 filters, and lastly black filters.</para>
861                         </parameter>
862                 </syntax>
863                 <description>
864                         <para>The filters added are only used for the current session.
865                         Once the connection is closed the filters are removed.</para>
866                         <para>This comand requires the system permission because
867                         this command can be used to create filters that may bypass
868                         filters defined in manager.conf</para>
869                 </description>
870         </manager>
871         <manager name="FilterList" language="en_US">
872                 <synopsis>
873                         Show current event filters for this session
874                 </synopsis>
875                 <description>
876                         <para>The filters displayed are for the current session.  Only those filters defined in
877                         manager.conf will be present upon starting a new session.</para>
878                 </description>
879         </manager>
880  ***/
881
882 enum error_type {
883         UNKNOWN_ACTION = 1,
884         UNKNOWN_CATEGORY,
885         UNSPECIFIED_CATEGORY,
886         UNSPECIFIED_ARGUMENT,
887         FAILURE_ALLOCATION,
888         FAILURE_NEWCAT,
889         FAILURE_DELCAT,
890         FAILURE_EMPTYCAT,
891         FAILURE_UPDATE,
892         FAILURE_DELETE,
893         FAILURE_APPEND
894 };
895
896 enum add_filter_result {
897         FILTER_SUCCESS,
898         FILTER_ALLOC_FAILED,
899         FILTER_COMPILE_FAIL,
900 };
901
902 /*!
903  * Linked list of events.
904  * Global events are appended to the list by append_event().
905  * The usecount is the number of stored pointers to the element,
906  * excluding the list pointers. So an element that is only in
907  * the list has a usecount of 0, not 1.
908  *
909  * Clients have a pointer to the last event processed, and for each
910  * of these clients we track the usecount of the elements.
911  * If we have a pointer to an entry in the list, it is safe to navigate
912  * it forward because elements will not be deleted, but only appended.
913  * The worst that can happen is seeing the pointer still NULL.
914  *
915  * When the usecount of an element drops to 0, and the element is the
916  * first in the list, we can remove it. Removal is done within the
917  * main thread, which is woken up for the purpose.
918  *
919  * For simplicity of implementation, we make sure the list is never empty.
920  */
921 struct eventqent {
922         int usecount;           /*!< # of clients who still need the event */
923         int category;
924         unsigned int seq;       /*!< sequence number */
925         struct timeval tv;  /*!< When event was allocated */
926         AST_RWLIST_ENTRY(eventqent) eq_next;
927         char eventdata[1];      /*!< really variable size, allocated by append_event() */
928 };
929
930 static AST_RWLIST_HEAD_STATIC(all_events, eventqent);
931
932 static int displayconnects = 1;
933 static int allowmultiplelogin = 1;
934 static int timestampevents;
935 static int httptimeout = 60;
936 static int broken_events_action = 0;
937 static int manager_enabled = 0;
938 static int webmanager_enabled = 0;
939 static int manager_debug = 0;   /*!< enable some debugging code in the manager */
940 static int authtimeout;
941 static int authlimit;
942 static char *manager_channelvars;
943
944 #define DEFAULT_REALM           "asterisk"
945 static char global_realm[MAXHOSTNAMELEN];       /*!< Default realm */
946
947 static int block_sockets;
948 static int unauth_sessions = 0;
949
950
951 /*! \brief
952  * Descriptor for a manager session, either on the AMI socket or over HTTP.
953  *
954  * \note
955  * AMI session have managerid == 0; the entry is created upon a connect,
956  * and destroyed with the socket.
957  * HTTP sessions have managerid != 0, the value is used as a search key
958  * to lookup sessions (using the mansession_id cookie, or nonce key from
959  * Digest Authentication http header).
960  */
961 #define MAX_BLACKLIST_CMD_LEN 2
962 static const struct {
963         const char *words[AST_MAX_CMD_LEN];
964 } command_blacklist[] = {
965         {{ "module", "load", NULL }},
966         {{ "module", "unload", NULL }},
967         {{ "restart", "gracefully", NULL }},
968 };
969
970 /* In order to understand what the heck is going on with the
971  * mansession_session and mansession structs, we need to have a bit of a history
972  * lesson.
973  *
974  * In the beginning, there was the mansession. The mansession contained data that was
975  * intrinsic to a manager session, such as the time that it started, the name of the logged-in
976  * user, etc. In addition to these parameters were the f and fd parameters. For typical manager
977  * sessions, these were used to represent the TCP socket over which the AMI session was taking
978  * place. It makes perfect sense for these fields to be a part of the session-specific data since
979  * the session actually defines this information.
980  *
981  * Then came the HTTP AMI sessions. With these, the f and fd fields need to be opened and closed
982  * for every single action that occurs. Thus the f and fd fields aren't really specific to the session
983  * but rather to the action that is being executed. Because a single session may execute many commands
984  * at once, some sort of safety needed to be added in order to be sure that we did not end up with fd
985  * leaks from one action overwriting the f and fd fields used by a previous action before the previous action
986  * has had a chance to properly close its handles.
987  *
988  * The initial idea to solve this was to use thread synchronization, but this prevented multiple actions
989  * from being run at the same time in a single session. Some manager actions may block for a long time, thus
990  * creating a large queue of actions to execute. In addition, this fix did not address the basic architectural
991  * issue that for HTTP manager sessions, the f and fd variables are not really a part of the session, but are
992  * part of the action instead.
993  *
994  * The new idea was to create a structure on the stack for each HTTP Manager action. This structure would
995  * contain the action-specific information, such as which file to write to. In order to maintain expectations
996  * of action handlers and not have to change the public API of the manager code, we would need to name this
997  * new stacked structure 'mansession' and contain within it the old mansession struct that we used to use.
998  * We renamed the old mansession struct 'mansession_session' to hopefully convey that what is in this structure
999  * is session-specific data. The structure that it is wrapped in, called a 'mansession' really contains action-specific
1000  * data.
1001  */
1002 struct mansession_session {
1003                                 /*! \todo XXX need to document which fields it is protecting */
1004         struct sockaddr_in sin; /*!< address we are connecting from */
1005         FILE *f;                /*!< fdopen() on the underlying fd */
1006         int fd;                 /*!< descriptor used for output. Either the socket (AMI) or a temporary file (HTTP) */
1007         int inuse;              /*!< number of HTTP sessions using this entry */
1008         int needdestroy;        /*!< Whether an HTTP session should be destroyed */
1009         pthread_t waiting_thread;       /*!< Sleeping thread using this descriptor */
1010         uint32_t managerid;     /*!< Unique manager identifier, 0 for AMI sessions */
1011         time_t sessionstart;    /*!< Session start time */
1012         struct timeval sessionstart_tv; /*!< Session start time */
1013         time_t sessiontimeout;  /*!< Session timeout if HTTP */
1014         char username[80];      /*!< Logged in username */
1015         char challenge[10];     /*!< Authentication challenge */
1016         int authenticated;      /*!< Authentication status */
1017         int readperm;           /*!< Authorization for reading */
1018         int writeperm;          /*!< Authorization for writing */
1019         char inbuf[1025];       /*!< Buffer -  we use the extra byte to add a '\0' and simplify parsing */
1020         int inlen;              /*!< number of buffered bytes */
1021         struct ao2_container *whitefilters;     /*!< Manager event filters - white list */
1022         struct ao2_container *blackfilters;     /*!< Manager event filters - black list */
1023         int send_events;        /*!<  XXX what ? */
1024         struct eventqent *last_ev;      /*!< last event processed. */
1025         int writetimeout;       /*!< Timeout for ast_carefulwrite() */
1026         time_t authstart;
1027         int pending_event;         /*!< Pending events indicator in case when waiting_thread is NULL */
1028         time_t noncetime;       /*!< Timer for nonce value expiration */
1029         unsigned long oldnonce; /*!< Stale nonce value */
1030         unsigned long nc;       /*!< incremental  nonce counter */
1031         AST_LIST_HEAD_NOLOCK(mansession_datastores, ast_datastore) datastores; /*!< Data stores on the session */
1032         AST_LIST_ENTRY(mansession_session) list;
1033 };
1034
1035 /*! \brief In case you didn't read that giant block of text above the mansession_session struct, the
1036  * \ref struct mansession is named this solely to keep the API the same in Asterisk. This structure really
1037  * represents data that is different from Manager action to Manager action. The mansession_session pointer
1038  * contained within points to session-specific data.
1039  */
1040 struct mansession {
1041         struct mansession_session *session;
1042         struct ast_tcptls_session_instance *tcptls_session;
1043         FILE *f;
1044         int fd;
1045         int write_error:1;
1046         struct manager_custom_hook *hook;
1047         ast_mutex_t lock;
1048 };
1049
1050 static struct ao2_container *sessions = NULL;
1051
1052 struct manager_channel_variable {
1053         AST_LIST_ENTRY(manager_channel_variable) entry;
1054         unsigned int isfunc:1;
1055         char name[0]; /* allocate off the end the real size. */
1056 };
1057
1058 static AST_RWLIST_HEAD_STATIC(channelvars, manager_channel_variable);
1059
1060 /*! \brief user descriptor, as read from the config file.
1061  *
1062  * \note It is still missing some fields -- e.g. we can have multiple permit and deny
1063  * lines which are not supported here, and readperm/writeperm/writetimeout
1064  * are not stored.
1065  */
1066 struct ast_manager_user {
1067         char username[80];
1068         char *secret;                   /*!< Secret for logging in */
1069         struct ast_ha *ha;              /*!< ACL setting */
1070         int readperm;                   /*!< Authorization for reading */
1071         int writeperm;                  /*!< Authorization for writing */
1072         int writetimeout;               /*!< Per user Timeout for ast_carefulwrite() */
1073         int displayconnects;            /*!< XXX unused */
1074         int keep;                       /*!< mark entries created on a reload */
1075         struct ao2_container *whitefilters; /*!< Manager event filters - white list */
1076         struct ao2_container *blackfilters; /*!< Manager event filters - black list */
1077         char *a1_hash;                  /*!< precalculated A1 for Digest auth */
1078         AST_RWLIST_ENTRY(ast_manager_user) list;
1079 };
1080
1081 /*! \brief list of users found in the config file */
1082 static AST_RWLIST_HEAD_STATIC(users, ast_manager_user);
1083
1084 /*! \brief list of actions registered */
1085 static AST_RWLIST_HEAD_STATIC(actions, manager_action);
1086
1087 /*! \brief list of hooks registered */
1088 static AST_RWLIST_HEAD_STATIC(manager_hooks, manager_custom_hook);
1089
1090 static void free_channelvars(void);
1091
1092 static enum add_filter_result manager_add_filter(const char *filter_pattern, struct ao2_container *whitefilters, struct ao2_container *blackfilters);
1093
1094 /*!
1095  * \internal
1096  * \brief Find a registered action object.
1097  *
1098  * \param name Name of AMI action to find.
1099  *
1100  * \return Reffed action found or NULL
1101  */
1102 static struct manager_action *action_find(const char *name)
1103 {
1104         struct manager_action *act;
1105
1106         AST_RWLIST_RDLOCK(&actions);
1107         AST_RWLIST_TRAVERSE(&actions, act, list) {
1108                 if (!strcasecmp(name, act->action)) {
1109                         ao2_t_ref(act, +1, "found action object");
1110                         break;
1111                 }
1112         }
1113         AST_RWLIST_UNLOCK(&actions);
1114
1115         return act;
1116 }
1117
1118 /*! \brief Add a custom hook to be called when an event is fired */
1119 void ast_manager_register_hook(struct manager_custom_hook *hook)
1120 {
1121         AST_RWLIST_WRLOCK(&manager_hooks);
1122         AST_RWLIST_INSERT_TAIL(&manager_hooks, hook, list);
1123         AST_RWLIST_UNLOCK(&manager_hooks);
1124 }
1125
1126 /*! \brief Delete a custom hook to be called when an event is fired */
1127 void ast_manager_unregister_hook(struct manager_custom_hook *hook)
1128 {
1129         AST_RWLIST_WRLOCK(&manager_hooks);
1130         AST_RWLIST_REMOVE(&manager_hooks, hook, list);
1131         AST_RWLIST_UNLOCK(&manager_hooks);
1132 }
1133
1134 int check_manager_enabled(void)
1135 {
1136         return manager_enabled;
1137 }
1138
1139 int check_webmanager_enabled(void)
1140 {
1141         return (webmanager_enabled && manager_enabled);
1142 }
1143
1144 /*!
1145  * Grab a reference to the last event, update usecount as needed.
1146  * Can handle a NULL pointer.
1147  */
1148 static struct eventqent *grab_last(void)
1149 {
1150         struct eventqent *ret;
1151
1152         AST_RWLIST_WRLOCK(&all_events);
1153         ret = AST_RWLIST_LAST(&all_events);
1154         /* the list is never empty now, but may become so when
1155          * we optimize it in the future, so be prepared.
1156          */
1157         if (ret) {
1158                 ast_atomic_fetchadd_int(&ret->usecount, 1);
1159         }
1160         AST_RWLIST_UNLOCK(&all_events);
1161         return ret;
1162 }
1163
1164 /*!
1165  * Purge unused events. Remove elements from the head
1166  * as long as their usecount is 0 and there is a next element.
1167  */
1168 static void purge_events(void)
1169 {
1170         struct eventqent *ev;
1171         struct timeval now = ast_tvnow();
1172
1173         AST_RWLIST_WRLOCK(&all_events);
1174         while ( (ev = AST_RWLIST_FIRST(&all_events)) &&
1175             ev->usecount == 0 && AST_RWLIST_NEXT(ev, eq_next)) {
1176                 AST_RWLIST_REMOVE_HEAD(&all_events, eq_next);
1177                 ast_free(ev);
1178         }
1179
1180         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&all_events, ev, eq_next) {
1181                 /* Never release the last event */
1182                 if (!AST_RWLIST_NEXT(ev, eq_next)) {
1183                         break;
1184                 }
1185
1186                 /* 2.5 times whatever the HTTP timeout is (maximum 2.5 hours) is the maximum time that we will definitely cache an event */
1187                 if (ev->usecount == 0 && ast_tvdiff_sec(now, ev->tv) > (httptimeout > 3600 ? 3600 : httptimeout) * 2.5) {
1188                         AST_RWLIST_REMOVE_CURRENT(eq_next);
1189                         ast_free(ev);
1190                 }
1191         }
1192         AST_RWLIST_TRAVERSE_SAFE_END;
1193         AST_RWLIST_UNLOCK(&all_events);
1194 }
1195
1196 /*!
1197  * helper functions to convert back and forth between
1198  * string and numeric representation of set of flags
1199  */
1200 static const struct permalias {
1201         int num;
1202         const char *label;
1203 } perms[] = {
1204         { EVENT_FLAG_SYSTEM, "system" },
1205         { EVENT_FLAG_CALL, "call" },
1206         { EVENT_FLAG_LOG, "log" },
1207         { EVENT_FLAG_VERBOSE, "verbose" },
1208         { EVENT_FLAG_COMMAND, "command" },
1209         { EVENT_FLAG_AGENT, "agent" },
1210         { EVENT_FLAG_USER, "user" },
1211         { EVENT_FLAG_CONFIG, "config" },
1212         { EVENT_FLAG_DTMF, "dtmf" },
1213         { EVENT_FLAG_REPORTING, "reporting" },
1214         { EVENT_FLAG_CDR, "cdr" },
1215         { EVENT_FLAG_DIALPLAN, "dialplan" },
1216         { EVENT_FLAG_ORIGINATE, "originate" },
1217         { EVENT_FLAG_AGI, "agi" },
1218         { EVENT_FLAG_CC, "cc" },
1219         { EVENT_FLAG_AOC, "aoc" },
1220         { EVENT_FLAG_TEST, "test" },
1221         { INT_MAX, "all" },
1222         { 0, "none" },
1223 };
1224
1225 /*! \brief Convert authority code to a list of options */
1226 static const char *authority_to_str(int authority, struct ast_str **res)
1227 {
1228         int i;
1229         char *sep = "";
1230
1231         ast_str_reset(*res);
1232         for (i = 0; i < ARRAY_LEN(perms) - 1; i++) {
1233                 if (authority & perms[i].num) {
1234                         ast_str_append(res, 0, "%s%s", sep, perms[i].label);
1235                         sep = ",";
1236                 }
1237         }
1238
1239         if (ast_str_strlen(*res) == 0)  /* replace empty string with something sensible */
1240                 ast_str_append(res, 0, "<none>");
1241
1242         return ast_str_buffer(*res);
1243 }
1244
1245 /*! Tells you if smallstr exists inside bigstr
1246    which is delim by delim and uses no buf or stringsep
1247    ast_instring("this|that|more","this",'|') == 1;
1248
1249    feel free to move this to app.c -anthm */
1250 static int ast_instring(const char *bigstr, const char *smallstr, const char delim)
1251 {
1252         const char *val = bigstr, *next;
1253
1254         do {
1255                 if ((next = strchr(val, delim))) {
1256                         if (!strncmp(val, smallstr, (next - val))) {
1257                                 return 1;
1258                         } else {
1259                                 continue;
1260                         }
1261                 } else {
1262                         return !strcmp(smallstr, val);
1263                 }
1264         } while (*(val = (next + 1)));
1265
1266         return 0;
1267 }
1268
1269 static int get_perm(const char *instr)
1270 {
1271         int x = 0, ret = 0;
1272
1273         if (!instr) {
1274                 return 0;
1275         }
1276
1277         for (x = 0; x < ARRAY_LEN(perms); x++) {
1278                 if (ast_instring(instr, perms[x].label, ',')) {
1279                         ret |= perms[x].num;
1280                 }
1281         }
1282
1283         return ret;
1284 }
1285
1286 /*!
1287  * A number returns itself, false returns 0, true returns all flags,
1288  * other strings return the flags that are set.
1289  */
1290 static int strings_to_mask(const char *string)
1291 {
1292         const char *p;
1293
1294         if (ast_strlen_zero(string)) {
1295                 return -1;
1296         }
1297
1298         for (p = string; *p; p++) {
1299                 if (*p < '0' || *p > '9') {
1300                         break;
1301                 }
1302         }
1303         if (!*p) { /* all digits */
1304                 return atoi(string);
1305         }
1306         if (ast_false(string)) {
1307                 return 0;
1308         }
1309         if (ast_true(string)) { /* all permissions */
1310                 int x, ret = 0;
1311                 for (x = 0; x < ARRAY_LEN(perms); x++) {
1312                         ret |= perms[x].num;
1313                 }
1314                 return ret;
1315         }
1316         return get_perm(string);
1317 }
1318
1319 /*! \brief Unreference manager session object.
1320      If no more references, then go ahead and delete it */
1321 static struct mansession_session *unref_mansession(struct mansession_session *s)
1322 {
1323         int refcount = ao2_ref(s, -1);
1324         if (manager_debug) {
1325                 ast_debug(1, "Mansession: %p refcount now %d\n", s, refcount - 1);
1326         }
1327         return s;
1328 }
1329
1330 static void event_filter_destructor(void *obj)
1331 {
1332         regex_t *regex_filter = obj;
1333         regfree(regex_filter);
1334 }
1335
1336 static void session_destructor(void *obj)
1337 {
1338         struct mansession_session *session = obj;
1339         struct eventqent *eqe = session->last_ev;
1340         struct ast_datastore *datastore;
1341
1342         /* Get rid of each of the data stores on the session */
1343         while ((datastore = AST_LIST_REMOVE_HEAD(&session->datastores, entry))) {
1344                 /* Free the data store */
1345                 ast_datastore_free(datastore);
1346         }
1347
1348         if (session->f != NULL) {
1349                 fclose(session->f);
1350         }
1351         if (eqe) {
1352                 ast_atomic_fetchadd_int(&eqe->usecount, -1);
1353         }
1354
1355         if (session->whitefilters) {
1356                 ao2_t_callback(session->whitefilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all white filters");
1357                 ao2_t_ref(session->whitefilters, -1 , "decrement ref for white container, should be last one");
1358         }
1359
1360         if (session->blackfilters) {
1361                 ao2_t_callback(session->blackfilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all black filters");
1362                 ao2_t_ref(session->blackfilters, -1 , "decrement ref for black container, should be last one");
1363         }
1364 }
1365
1366 /*! \brief Allocate manager session structure and add it to the list of sessions */
1367 static struct mansession_session *build_mansession(struct sockaddr_in sin)
1368 {
1369         struct mansession_session *newsession;
1370
1371         if (!(newsession = ao2_alloc(sizeof(*newsession), session_destructor))) {
1372                 return NULL;
1373         }
1374
1375         if (!(newsession->whitefilters = ao2_container_alloc(1, NULL, NULL))) {
1376                 ao2_ref(newsession, -1);
1377                 return NULL;
1378         }
1379
1380         if (!(newsession->blackfilters = ao2_container_alloc(1, NULL, NULL))) {
1381                 ao2_ref(newsession, -1); /* session_destructor will cleanup the other filter */
1382                 return NULL;
1383         }
1384
1385         newsession->fd = -1;
1386         newsession->waiting_thread = AST_PTHREADT_NULL;
1387         newsession->writetimeout = 100;
1388         newsession->send_events = -1;
1389         newsession->sin = sin;
1390
1391         ao2_link(sessions, newsession);
1392
1393         return newsession;
1394 }
1395
1396 static int mansession_cmp_fn(void *obj, void *arg, int flags)
1397 {
1398         struct mansession_session *s = obj;
1399         char *str = arg;
1400         return !strcasecmp(s->username, str) ? CMP_MATCH : 0;
1401 }
1402
1403 static void session_destroy(struct mansession_session *s)
1404 {
1405         unref_mansession(s);
1406         ao2_unlink(sessions, s);
1407 }
1408
1409
1410 static int check_manager_session_inuse(const char *name)
1411 {
1412         struct mansession_session *session = ao2_find(sessions, (char *) name, 0);
1413         int inuse = 0;
1414
1415         if (session) {
1416                 inuse = 1;
1417                 unref_mansession(session);
1418         }
1419         return inuse;
1420 }
1421
1422
1423 /*!
1424  * lookup an entry in the list of registered users.
1425  * must be called with the list lock held.
1426  */
1427 static struct ast_manager_user *get_manager_by_name_locked(const char *name)
1428 {
1429         struct ast_manager_user *user = NULL;
1430
1431         AST_RWLIST_TRAVERSE(&users, user, list) {
1432                 if (!strcasecmp(user->username, name)) {
1433                         break;
1434                 }
1435         }
1436
1437         return user;
1438 }
1439
1440 /*! \brief Get displayconnects config option.
1441  *  \param session manager session to get parameter from.
1442  *  \return displayconnects config option value.
1443  */
1444 static int manager_displayconnects (struct mansession_session *session)
1445 {
1446         struct ast_manager_user *user = NULL;
1447         int ret = 0;
1448
1449         AST_RWLIST_RDLOCK(&users);
1450         if ((user = get_manager_by_name_locked (session->username))) {
1451                 ret = user->displayconnects;
1452         }
1453         AST_RWLIST_UNLOCK(&users);
1454
1455         return ret;
1456 }
1457
1458 static char *handle_showmancmd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1459 {
1460         struct manager_action *cur;
1461         struct ast_str *authority;
1462         int num, l, which;
1463         char *ret = NULL;
1464 #ifdef AST_XML_DOCS
1465         char syntax_title[64], description_title[64], synopsis_title[64], seealso_title[64], arguments_title[64];
1466 #endif
1467
1468         switch (cmd) {
1469         case CLI_INIT:
1470                 e->command = "manager show command";
1471                 e->usage =
1472                         "Usage: manager show command <actionname> [<actionname> [<actionname> [...]]]\n"
1473                         "       Shows the detailed description for a specific Asterisk manager interface command.\n";
1474                 return NULL;
1475         case CLI_GENERATE:
1476                 l = strlen(a->word);
1477                 which = 0;
1478                 AST_RWLIST_RDLOCK(&actions);
1479                 AST_RWLIST_TRAVERSE(&actions, cur, list) {
1480                         if (!strncasecmp(a->word, cur->action, l) && ++which > a->n) {
1481                                 ret = ast_strdup(cur->action);
1482                                 break;  /* make sure we exit even if ast_strdup() returns NULL */
1483                         }
1484                 }
1485                 AST_RWLIST_UNLOCK(&actions);
1486                 return ret;
1487         }
1488         authority = ast_str_alloca(80);
1489         if (a->argc < 4) {
1490                 return CLI_SHOWUSAGE;
1491         }
1492
1493 #ifdef AST_XML_DOCS
1494         /* setup the titles */
1495         term_color(synopsis_title, "[Synopsis]\n", COLOR_MAGENTA, 0, 40);
1496         term_color(description_title, "[Description]\n", COLOR_MAGENTA, 0, 40);
1497         term_color(syntax_title, "[Syntax]\n", COLOR_MAGENTA, 0, 40);
1498         term_color(seealso_title, "[See Also]\n", COLOR_MAGENTA, 0, 40);
1499         term_color(arguments_title, "[Arguments]\n", COLOR_MAGENTA, 0, 40);
1500 #endif
1501
1502         AST_RWLIST_RDLOCK(&actions);
1503         AST_RWLIST_TRAVERSE(&actions, cur, list) {
1504                 for (num = 3; num < a->argc; num++) {
1505                         if (!strcasecmp(cur->action, a->argv[num])) {
1506 #ifdef AST_XML_DOCS
1507                                 if (cur->docsrc == AST_XML_DOC) {
1508                                         ast_cli(a->fd, "%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n\n",
1509                                                 syntax_title,
1510                                                 ast_xmldoc_printable(S_OR(cur->syntax, "Not available"), 1),
1511                                                 synopsis_title,
1512                                                 ast_xmldoc_printable(S_OR(cur->synopsis, "Not available"), 1),
1513                                                 description_title,
1514                                                 ast_xmldoc_printable(S_OR(cur->description, "Not available"), 1),
1515                                                 arguments_title,
1516                                                 ast_xmldoc_printable(S_OR(cur->arguments, "Not available"), 1),
1517                                                 seealso_title,
1518                                                 ast_xmldoc_printable(S_OR(cur->seealso, "Not available"), 1));
1519                                 } else
1520 #endif
1521                                 {
1522                                         ast_cli(a->fd, "Action: %s\nSynopsis: %s\nPrivilege: %s\n%s\n",
1523                                                 cur->action, cur->synopsis,
1524                                                 authority_to_str(cur->authority, &authority),
1525                                                 S_OR(cur->description, ""));
1526                                 }
1527                         }
1528                 }
1529         }
1530         AST_RWLIST_UNLOCK(&actions);
1531
1532         return CLI_SUCCESS;
1533 }
1534
1535 static char *handle_mandebug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1536 {
1537         switch (cmd) {
1538         case CLI_INIT:
1539                 e->command = "manager set debug [on|off]";
1540                 e->usage = "Usage: manager set debug [on|off]\n Show, enable, disable debugging of the manager code.\n";
1541                 return NULL;
1542         case CLI_GENERATE:
1543                 return NULL;
1544         }
1545
1546         if (a->argc == 3) {
1547                 ast_cli(a->fd, "manager debug is %s\n", manager_debug? "on" : "off");
1548         } else if (a->argc == 4) {
1549                 if (!strcasecmp(a->argv[3], "on")) {
1550                         manager_debug = 1;
1551                 } else if (!strcasecmp(a->argv[3], "off")) {
1552                         manager_debug = 0;
1553                 } else {
1554                         return CLI_SHOWUSAGE;
1555                 }
1556         }
1557         return CLI_SUCCESS;
1558 }
1559
1560 static char *handle_showmanager(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1561 {
1562         struct ast_manager_user *user = NULL;
1563         int l, which;
1564         char *ret = NULL;
1565         struct ast_str *rauthority = ast_str_alloca(128);
1566         struct ast_str *wauthority = ast_str_alloca(128);
1567
1568         switch (cmd) {
1569         case CLI_INIT:
1570                 e->command = "manager show user";
1571                 e->usage =
1572                         " Usage: manager show user <user>\n"
1573                         "        Display all information related to the manager user specified.\n";
1574                 return NULL;
1575         case CLI_GENERATE:
1576                 l = strlen(a->word);
1577                 which = 0;
1578                 if (a->pos != 3) {
1579                         return NULL;
1580                 }
1581                 AST_RWLIST_RDLOCK(&users);
1582                 AST_RWLIST_TRAVERSE(&users, user, list) {
1583                         if ( !strncasecmp(a->word, user->username, l) && ++which > a->n ) {
1584                                 ret = ast_strdup(user->username);
1585                                 break;
1586                         }
1587                 }
1588                 AST_RWLIST_UNLOCK(&users);
1589                 return ret;
1590         }
1591
1592         if (a->argc != 4) {
1593                 return CLI_SHOWUSAGE;
1594         }
1595
1596         AST_RWLIST_RDLOCK(&users);
1597
1598         if (!(user = get_manager_by_name_locked(a->argv[3]))) {
1599                 ast_cli(a->fd, "There is no manager called %s\n", a->argv[3]);
1600                 AST_RWLIST_UNLOCK(&users);
1601                 return CLI_SUCCESS;
1602         }
1603
1604         ast_cli(a->fd, "\n");
1605         ast_cli(a->fd,
1606                 "       username: %s\n"
1607                 "         secret: %s\n"
1608                 "            acl: %s\n"
1609                 "      read perm: %s\n"
1610                 "     write perm: %s\n"
1611                 "displayconnects: %s\n",
1612                 (user->username ? user->username : "(N/A)"),
1613                 (user->secret ? "<Set>" : "(N/A)"),
1614                 (user->ha ? "yes" : "no"),
1615                 authority_to_str(user->readperm, &rauthority),
1616                 authority_to_str(user->writeperm, &wauthority),
1617                 (user->displayconnects ? "yes" : "no"));
1618
1619         AST_RWLIST_UNLOCK(&users);
1620
1621         return CLI_SUCCESS;
1622 }
1623
1624 static char *handle_showmanagers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1625 {
1626         struct ast_manager_user *user = NULL;
1627         int count_amu = 0;
1628         switch (cmd) {
1629         case CLI_INIT:
1630                 e->command = "manager show users";
1631                 e->usage =
1632                         "Usage: manager show users\n"
1633                         "       Prints a listing of all managers that are currently configured on that\n"
1634                         " system.\n";
1635                 return NULL;
1636         case CLI_GENERATE:
1637                 return NULL;
1638         }
1639         if (a->argc != 3) {
1640                 return CLI_SHOWUSAGE;
1641         }
1642
1643         AST_RWLIST_RDLOCK(&users);
1644
1645         /* If there are no users, print out something along those lines */
1646         if (AST_RWLIST_EMPTY(&users)) {
1647                 ast_cli(a->fd, "There are no manager users.\n");
1648                 AST_RWLIST_UNLOCK(&users);
1649                 return CLI_SUCCESS;
1650         }
1651
1652         ast_cli(a->fd, "\nusername\n--------\n");
1653
1654         AST_RWLIST_TRAVERSE(&users, user, list) {
1655                 ast_cli(a->fd, "%s\n", user->username);
1656                 count_amu++;
1657         }
1658
1659         AST_RWLIST_UNLOCK(&users);
1660
1661         ast_cli(a->fd,"-------------------\n"
1662                       "%d manager users configured.\n", count_amu);
1663         return CLI_SUCCESS;
1664 }
1665
1666 /*! \brief  CLI command  manager list commands */
1667 static char *handle_showmancmds(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1668 {
1669         struct manager_action *cur;
1670         struct ast_str *authority;
1671 #define HSMC_FORMAT "  %-15.15s  %-15.15s  %-55.55s\n"
1672         switch (cmd) {
1673         case CLI_INIT:
1674                 e->command = "manager show commands";
1675                 e->usage =
1676                         "Usage: manager show commands\n"
1677                         "       Prints a listing of all the available Asterisk manager interface commands.\n";
1678                 return NULL;
1679         case CLI_GENERATE:
1680                 return NULL;
1681         }
1682         authority = ast_str_alloca(80);
1683         ast_cli(a->fd, HSMC_FORMAT, "Action", "Privilege", "Synopsis");
1684         ast_cli(a->fd, HSMC_FORMAT, "------", "---------", "--------");
1685
1686         AST_RWLIST_RDLOCK(&actions);
1687         AST_RWLIST_TRAVERSE(&actions, cur, list) {
1688                 ast_cli(a->fd, HSMC_FORMAT, cur->action, authority_to_str(cur->authority, &authority), cur->synopsis);
1689         }
1690         AST_RWLIST_UNLOCK(&actions);
1691
1692         return CLI_SUCCESS;
1693 }
1694
1695 /*! \brief CLI command manager list connected */
1696 static char *handle_showmanconn(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1697 {
1698         struct mansession_session *session;
1699         time_t now = time(NULL);
1700 #define HSMCONN_FORMAT1 "  %-15.15s  %-15.15s  %-10.10s  %-10.10s  %-8.8s  %-8.8s  %-5.5s  %-5.5s\n"
1701 #define HSMCONN_FORMAT2 "  %-15.15s  %-15.15s  %-10d  %-10d  %-8d  %-8d  %-5.5d  %-5.5d\n"
1702         int count = 0;
1703         struct ao2_iterator i;
1704
1705         switch (cmd) {
1706         case CLI_INIT:
1707                 e->command = "manager show connected";
1708                 e->usage =
1709                         "Usage: manager show connected\n"
1710                         "       Prints a listing of the users that are currently connected to the\n"
1711                         "Asterisk manager interface.\n";
1712                 return NULL;
1713         case CLI_GENERATE:
1714                 return NULL;
1715         }
1716
1717         ast_cli(a->fd, HSMCONN_FORMAT1, "Username", "IP Address", "Start", "Elapsed", "FileDes", "HttpCnt", "Read", "Write");
1718
1719         i = ao2_iterator_init(sessions, 0);
1720         while ((session = ao2_iterator_next(&i))) {
1721                 ao2_lock(session);
1722                 ast_cli(a->fd, HSMCONN_FORMAT2, session->username, ast_inet_ntoa(session->sin.sin_addr), (int)(session->sessionstart), (int)(now - session->sessionstart), session->fd, session->inuse, session->readperm, session->writeperm);
1723                 count++;
1724                 ao2_unlock(session);
1725                 unref_mansession(session);
1726         }
1727         ao2_iterator_destroy(&i);
1728         ast_cli(a->fd, "%d users connected.\n", count);
1729
1730         return CLI_SUCCESS;
1731 }
1732
1733 /*! \brief CLI command manager list eventq */
1734 /* Should change to "manager show connected" */
1735 static char *handle_showmaneventq(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1736 {
1737         struct eventqent *s;
1738         switch (cmd) {
1739         case CLI_INIT:
1740                 e->command = "manager show eventq";
1741                 e->usage =
1742                         "Usage: manager show eventq\n"
1743                         "       Prints a listing of all events pending in the Asterisk manger\n"
1744                         "event queue.\n";
1745                 return NULL;
1746         case CLI_GENERATE:
1747                 return NULL;
1748         }
1749         AST_RWLIST_RDLOCK(&all_events);
1750         AST_RWLIST_TRAVERSE(&all_events, s, eq_next) {
1751                 ast_cli(a->fd, "Usecount: %d\n", s->usecount);
1752                 ast_cli(a->fd, "Category: %d\n", s->category);
1753                 ast_cli(a->fd, "Event:\n%s", s->eventdata);
1754         }
1755         AST_RWLIST_UNLOCK(&all_events);
1756
1757         return CLI_SUCCESS;
1758 }
1759
1760 /*! \brief CLI command manager reload */
1761 static char *handle_manager_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1762 {
1763         switch (cmd) {
1764         case CLI_INIT:
1765                 e->command = "manager reload";
1766                 e->usage =
1767                         "Usage: manager reload\n"
1768                         "       Reloads the manager configuration.\n";
1769                 return NULL;
1770         case CLI_GENERATE:
1771                 return NULL;
1772         }
1773         if (a->argc > 2) {
1774                 return CLI_SHOWUSAGE;
1775         }
1776         reload_manager();
1777         return CLI_SUCCESS;
1778 }
1779
1780 static struct eventqent *advance_event(struct eventqent *e)
1781 {
1782         struct eventqent *next;
1783
1784         AST_RWLIST_RDLOCK(&all_events);
1785         if ((next = AST_RWLIST_NEXT(e, eq_next))) {
1786                 ast_atomic_fetchadd_int(&next->usecount, 1);
1787                 ast_atomic_fetchadd_int(&e->usecount, -1);
1788         }
1789         AST_RWLIST_UNLOCK(&all_events);
1790         return next;
1791 }
1792
1793 #define GET_HEADER_FIRST_MATCH  0
1794 #define GET_HEADER_LAST_MATCH   1
1795 #define GET_HEADER_SKIP_EMPTY   2
1796
1797 /*!
1798  * \brief Return a matching header value.
1799  *
1800  * \details
1801  * Generic function to return either the first or the last
1802  * matching header from a list of variables, possibly skipping
1803  * empty strings.
1804  *
1805  * \note At the moment there is only one use of this function in
1806  * this file, so we make it static.
1807  *
1808  * \note Never returns NULL.
1809  */
1810 static const char *__astman_get_header(const struct message *m, char *var, int mode)
1811 {
1812         int x, l = strlen(var);
1813         const char *result = "";
1814
1815         for (x = 0; x < m->hdrcount; x++) {
1816                 const char *h = m->headers[x];
1817                 if (!strncasecmp(var, h, l) && h[l] == ':') {
1818                         const char *value = h + l + 1;
1819                         value = ast_skip_blanks(value); /* ignore leading spaces in the value */
1820                         /* found a potential candidate */
1821                         if ((mode & GET_HEADER_SKIP_EMPTY) && ast_strlen_zero(value)) {
1822                                 continue;       /* not interesting */
1823                         }
1824                         if (mode & GET_HEADER_LAST_MATCH) {
1825                                 result = value; /* record the last match so far */
1826                         } else {
1827                                 return value;
1828                         }
1829                 }
1830         }
1831
1832         return result;
1833 }
1834
1835 /*!
1836  * \brief Return the first matching variable from an array.
1837  *
1838  * \note This is the legacy function and is implemented in
1839  * therms of __astman_get_header().
1840  *
1841  * \note Never returns NULL.
1842  */
1843 const char *astman_get_header(const struct message *m, char *var)
1844 {
1845         return __astman_get_header(m, var, GET_HEADER_FIRST_MATCH);
1846 }
1847
1848 /*!
1849  * \internal
1850  * \brief Process one "Variable:" header value string.
1851  *
1852  * \param head Current list of AMI variables to get new values added.
1853  * \param hdr_val Header value string to process.
1854  *
1855  * \return New variable list head.
1856  */
1857 static struct ast_variable *man_do_variable_value(struct ast_variable *head, const char *hdr_val)
1858 {
1859         char *parse;
1860         AST_DECLARE_APP_ARGS(args,
1861                 AST_APP_ARG(vars)[64];
1862         );
1863
1864         hdr_val = ast_skip_blanks(hdr_val); /* ignore leading spaces in the value */
1865         parse = ast_strdupa(hdr_val);
1866
1867         /* Break the header value string into name=val pair items. */
1868         AST_STANDARD_APP_ARGS(args, parse);
1869         if (args.argc) {
1870                 int y;
1871
1872                 /* Process each name=val pair item. */
1873                 for (y = 0; y < args.argc; y++) {
1874                         struct ast_variable *cur;
1875                         char *var;
1876                         char *val;
1877
1878                         if (!args.vars[y]) {
1879                                 continue;
1880                         }
1881                         var = val = args.vars[y];
1882                         strsep(&val, "=");
1883
1884                         /* XXX We may wish to trim whitespace from the strings. */
1885                         if (!val || ast_strlen_zero(var)) {
1886                                 continue;
1887                         }
1888
1889                         /* Create new variable list node and prepend it to the list. */
1890                         cur = ast_variable_new(var, val, "");
1891                         if (cur) {
1892                                 cur->next = head;
1893                                 head = cur;
1894                         }
1895                 }
1896         }
1897
1898         return head;
1899 }
1900
1901 struct ast_variable *astman_get_variables(const struct message *m)
1902 {
1903         int varlen;
1904         int x;
1905         struct ast_variable *head = NULL;
1906
1907         static const char var_hdr[] = "Variable:";
1908
1909         /* Process all "Variable:" headers. */
1910         varlen = strlen(var_hdr);
1911         for (x = 0; x < m->hdrcount; x++) {
1912                 if (strncasecmp(var_hdr, m->headers[x], varlen)) {
1913                         continue;
1914                 }
1915                 head = man_do_variable_value(head, m->headers[x] + varlen);
1916         }
1917
1918         return head;
1919 }
1920
1921 /*! \brief access for hooks to send action messages to ami */
1922 int ast_hook_send_action(struct manager_custom_hook *hook, const char *msg)
1923 {
1924         const char *action;
1925         int ret = 0;
1926         struct manager_action *act_found;
1927         struct mansession s = {.session = NULL, };
1928         struct message m = { 0 };
1929         char *dup_str;
1930         char *src;
1931         int x = 0;
1932         int curlen;
1933
1934         if (hook == NULL) {
1935                 return -1;
1936         }
1937
1938         /* Create our own copy of the AMI action msg string. */
1939         src = dup_str = ast_strdup(msg);
1940         if (!dup_str) {
1941                 return -1;
1942         }
1943
1944         /* convert msg string to message struct */
1945         curlen = strlen(src);
1946         for (x = 0; x < curlen; x++) {
1947                 int cr; /* set if we have \r */
1948                 if (src[x] == '\r' && x+1 < curlen && src[x+1] == '\n')
1949                         cr = 2; /* Found. Update length to include \r\n */
1950                 else if (src[x] == '\n')
1951                         cr = 1; /* also accept \n only */
1952                 else
1953                         continue;
1954                 /* don't keep empty lines */
1955                 if (x && m.hdrcount < ARRAY_LEN(m.headers)) {
1956                         /* ... but trim \r\n and terminate the header string */
1957                         src[x] = '\0';
1958                         m.headers[m.hdrcount++] = src;
1959                 }
1960                 x += cr;
1961                 curlen -= x;            /* remaining size */
1962                 src += x;               /* update pointer */
1963                 x = -1;                 /* reset loop */
1964         }
1965
1966         action = astman_get_header(&m, "Action");
1967         if (strcasecmp(action, "login")) {
1968                 act_found = action_find(action);
1969                 if (act_found) {
1970                         /*
1971                          * we have to simulate a session for this action request
1972                          * to be able to pass it down for processing
1973                          * This is necessary to meet the previous design of manager.c
1974                          */
1975                         s.hook = hook;
1976                         s.f = (void*)1; /* set this to something so our request will make it through all functions that test it*/
1977
1978                         ao2_lock(act_found);
1979                         if (act_found->registered && act_found->func) {
1980                                 if (act_found->module) {
1981                                         ast_module_ref(act_found->module);
1982                                 }
1983                                 ao2_unlock(act_found);
1984                                 ret = act_found->func(&s, &m);
1985                                 ao2_lock(act_found);
1986                                 if (act_found->module) {
1987                                         ast_module_unref(act_found->module);
1988                                 }
1989                         } else {
1990                                 ret = -1;
1991                         }
1992                         ao2_unlock(act_found);
1993                         ao2_t_ref(act_found, -1, "done with found action object");
1994                 }
1995         }
1996         ast_free(dup_str);
1997         return ret;
1998 }
1999
2000
2001 /*!
2002  * helper function to send a string to the socket.
2003  * Return -1 on error (e.g. buffer full).
2004  */
2005 static int send_string(struct mansession *s, char *string)
2006 {
2007         int res;
2008         FILE *f = s->f ? s->f : s->session->f;
2009         int fd = s->f ? s->fd : s->session->fd;
2010
2011         /* It's a result from one of the hook's action invocation */
2012         if (s->hook) {
2013                 /*
2014                  * to send responses, we're using the same function
2015                  * as for receiving events. We call the event "HookResponse"
2016                  */
2017                 s->hook->helper(EVENT_FLAG_HOOKRESPONSE, "HookResponse", string);
2018                 return 0;
2019         }
2020
2021         if ((res = ast_careful_fwrite(f, fd, string, strlen(string), s->session->writetimeout))) {
2022                 s->write_error = 1;
2023         }
2024
2025         return res;
2026 }
2027
2028 /*!
2029  * \brief thread local buffer for astman_append
2030  *
2031  * \note This can not be defined within the astman_append() function
2032  *       because it declares a couple of functions that get used to
2033  *       initialize the thread local storage key.
2034  */
2035 AST_THREADSTORAGE(astman_append_buf);
2036
2037 AST_THREADSTORAGE(userevent_buf);
2038
2039 /*! \brief initial allocated size for the astman_append_buf and astman_send_*_va */
2040 #define ASTMAN_APPEND_BUF_INITSIZE   256
2041
2042 /*!
2043  * utility functions for creating AMI replies
2044  */
2045 void astman_append(struct mansession *s, const char *fmt, ...)
2046 {
2047         va_list ap;
2048         struct ast_str *buf;
2049
2050         if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
2051                 return;
2052         }
2053
2054         va_start(ap, fmt);
2055         ast_str_set_va(&buf, 0, fmt, ap);
2056         va_end(ap);
2057
2058         if (s->f != NULL || s->session->f != NULL) {
2059                 send_string(s, ast_str_buffer(buf));
2060         } else {
2061                 ast_verbose("fd == -1 in astman_append, should not happen\n");
2062         }
2063 }
2064
2065 /*! \note NOTE: XXX this comment is unclear and possibly wrong.
2066    Callers of astman_send_error(), astman_send_response() or astman_send_ack() must EITHER
2067    hold the session lock _or_ be running in an action callback (in which case s->session->busy will
2068    be non-zero). In either of these cases, there is no need to lock-protect the session's
2069    fd, since no other output will be sent (events will be queued), and no input will
2070    be read until either the current action finishes or get_input() obtains the session
2071    lock.
2072  */
2073
2074 /*! \todo XXX MSG_MOREDATA should go to a header file. */
2075 #define MSG_MOREDATA    ((char *)astman_send_response)
2076
2077 /*! \brief send a response with an optional message,
2078  * and terminate it with an empty line.
2079  * m is used only to grab the 'ActionID' field.
2080  *
2081  * Use the explicit constant MSG_MOREDATA to remove the empty line.
2082  * XXX MSG_MOREDATA should go to a header file.
2083  */
2084 static void astman_send_response_full(struct mansession *s, const struct message *m, char *resp, char *msg, char *listflag)
2085 {
2086         const char *id = astman_get_header(m, "ActionID");
2087
2088         astman_append(s, "Response: %s\r\n", resp);
2089         if (!ast_strlen_zero(id)) {
2090                 astman_append(s, "ActionID: %s\r\n", id);
2091         }
2092         if (listflag) {
2093                 astman_append(s, "EventList: %s\r\n", listflag);        /* Start, complete, cancelled */
2094         }
2095         if (msg == MSG_MOREDATA) {
2096                 return;
2097         } else if (msg) {
2098                 astman_append(s, "Message: %s\r\n\r\n", msg);
2099         } else {
2100                 astman_append(s, "\r\n");
2101         }
2102 }
2103
2104 void astman_send_response(struct mansession *s, const struct message *m, char *resp, char *msg)
2105 {
2106         astman_send_response_full(s, m, resp, msg, NULL);
2107 }
2108
2109 void astman_send_error(struct mansession *s, const struct message *m, char *error)
2110 {
2111         astman_send_response_full(s, m, "Error", error, NULL);
2112 }
2113
2114 void astman_send_error_va(struct mansession *s, const struct message *m, const char *fmt, ...)
2115 {
2116         va_list ap;
2117         struct ast_str *buf;
2118
2119         if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
2120                 return;
2121         }
2122
2123         va_start(ap, fmt);
2124         ast_str_set_va(&buf, 0, fmt, ap);
2125         va_end(ap);
2126
2127         astman_send_response_full(s, m, "Error", ast_str_buffer(buf), NULL);
2128         ast_free(buf);
2129 }
2130
2131 void astman_send_ack(struct mansession *s, const struct message *m, char *msg)
2132 {
2133         astman_send_response_full(s, m, "Success", msg, NULL);
2134 }
2135
2136 static void astman_start_ack(struct mansession *s, const struct message *m)
2137 {
2138         astman_send_response_full(s, m, "Success", MSG_MOREDATA, NULL);
2139 }
2140
2141 void astman_send_listack(struct mansession *s, const struct message *m, char *msg, char *listflag)
2142 {
2143         astman_send_response_full(s, m, "Success", msg, listflag);
2144 }
2145
2146 /*! \brief Lock the 'mansession' structure. */
2147 static void mansession_lock(struct mansession *s)
2148 {
2149         ast_mutex_lock(&s->lock);
2150 }
2151
2152 /*! \brief Unlock the 'mansession' structure. */
2153 static void mansession_unlock(struct mansession *s)
2154 {
2155         ast_mutex_unlock(&s->lock);
2156 }
2157
2158 /*! \brief
2159    Rather than braindead on,off this now can also accept a specific int mask value
2160    or a ',' delim list of mask strings (the same as manager.conf) -anthm
2161 */
2162 static int set_eventmask(struct mansession *s, const char *eventmask)
2163 {
2164         int maskint = strings_to_mask(eventmask);
2165
2166         ao2_lock(s->session);
2167         if (maskint >= 0) {
2168                 s->session->send_events = maskint;
2169         }
2170         ao2_unlock(s->session);
2171
2172         return maskint;
2173 }
2174
2175 static enum ast_security_event_transport_type mansession_get_transport(const struct mansession *s)
2176 {
2177         return s->tcptls_session->parent->tls_cfg ? AST_SECURITY_EVENT_TRANSPORT_TLS :
2178                         AST_SECURITY_EVENT_TRANSPORT_TCP;
2179 }
2180
2181 static struct sockaddr_in *mansession_encode_sin_local(const struct mansession *s,
2182                 struct sockaddr_in *sin_local)
2183 {
2184         ast_sockaddr_to_sin(&s->tcptls_session->parent->local_address,
2185                             sin_local);
2186
2187         return sin_local;
2188 }
2189
2190 static void report_invalid_user(const struct mansession *s, const char *username)
2191 {
2192         struct sockaddr_in sin_local;
2193         char session_id[32];
2194         struct ast_security_event_inval_acct_id inval_acct_id = {
2195                 .common.event_type = AST_SECURITY_EVENT_INVAL_ACCT_ID,
2196                 .common.version    = AST_SECURITY_EVENT_INVAL_ACCT_ID_VERSION,
2197                 .common.service    = "AMI",
2198                 .common.account_id = username,
2199                 .common.session_tv = &s->session->sessionstart_tv,
2200                 .common.local_addr = {
2201                         .sin       = mansession_encode_sin_local(s, &sin_local),
2202                         .transport = mansession_get_transport(s),
2203                 },
2204                 .common.remote_addr = {
2205                         .sin       = &s->session->sin,
2206                         .transport = mansession_get_transport(s),
2207                 },
2208                 .common.session_id = session_id,
2209         };
2210
2211         snprintf(session_id, sizeof(session_id), "%p", s);
2212
2213         ast_security_event_report(AST_SEC_EVT(&inval_acct_id));
2214 }
2215
2216 static void report_failed_acl(const struct mansession *s, const char *username)
2217 {
2218         struct sockaddr_in sin_local;
2219         char session_id[32];
2220         struct ast_security_event_failed_acl failed_acl_event = {
2221                 .common.event_type = AST_SECURITY_EVENT_FAILED_ACL,
2222                 .common.version    = AST_SECURITY_EVENT_FAILED_ACL_VERSION,
2223                 .common.service    = "AMI",
2224                 .common.account_id = username,
2225                 .common.session_tv = &s->session->sessionstart_tv,
2226                 .common.local_addr = {
2227                         .sin       = mansession_encode_sin_local(s, &sin_local),
2228                         .transport = mansession_get_transport(s),
2229                 },
2230                 .common.remote_addr = {
2231                         .sin       = &s->session->sin,
2232                         .transport = mansession_get_transport(s),
2233                 },
2234                 .common.session_id = session_id,
2235         };
2236
2237         snprintf(session_id, sizeof(session_id), "%p", s->session);
2238
2239         ast_security_event_report(AST_SEC_EVT(&failed_acl_event));
2240 }
2241
2242 static void report_inval_password(const struct mansession *s, const char *username)
2243 {
2244         struct sockaddr_in sin_local;
2245         char session_id[32];
2246         struct ast_security_event_inval_password inval_password = {
2247                 .common.event_type = AST_SECURITY_EVENT_INVAL_PASSWORD,
2248                 .common.version    = AST_SECURITY_EVENT_INVAL_PASSWORD_VERSION,
2249                 .common.service    = "AMI",
2250                 .common.account_id = username,
2251                 .common.session_tv = &s->session->sessionstart_tv,
2252                 .common.local_addr = {
2253                         .sin       = mansession_encode_sin_local(s, &sin_local),
2254                         .transport = mansession_get_transport(s),
2255                 },
2256                 .common.remote_addr = {
2257                         .sin       = &s->session->sin,
2258                         .transport = mansession_get_transport(s),
2259                 },
2260                 .common.session_id = session_id,
2261         };
2262
2263         snprintf(session_id, sizeof(session_id), "%p", s->session);
2264
2265         ast_security_event_report(AST_SEC_EVT(&inval_password));
2266 }
2267
2268 static void report_auth_success(const struct mansession *s)
2269 {
2270         struct sockaddr_in sin_local;
2271         char session_id[32];
2272         struct ast_security_event_successful_auth successful_auth = {
2273                 .common.event_type = AST_SECURITY_EVENT_SUCCESSFUL_AUTH,
2274                 .common.version    = AST_SECURITY_EVENT_SUCCESSFUL_AUTH_VERSION,
2275                 .common.service    = "AMI",
2276                 .common.account_id = s->session->username,
2277                 .common.session_tv = &s->session->sessionstart_tv,
2278                 .common.local_addr = {
2279                         .sin       = mansession_encode_sin_local(s, &sin_local),
2280                         .transport = mansession_get_transport(s),
2281                 },
2282                 .common.remote_addr = {
2283                         .sin       = &s->session->sin,
2284                         .transport = mansession_get_transport(s),
2285                 },
2286                 .common.session_id = session_id,
2287         };
2288
2289         snprintf(session_id, sizeof(session_id), "%p", s->session);
2290
2291         ast_security_event_report(AST_SEC_EVT(&successful_auth));
2292 }
2293
2294 static void report_req_not_allowed(const struct mansession *s, const char *action)
2295 {
2296         struct sockaddr_in sin_local;
2297         char session_id[32];
2298         char request_type[64];
2299         struct ast_security_event_req_not_allowed req_not_allowed = {
2300                 .common.event_type = AST_SECURITY_EVENT_REQ_NOT_ALLOWED,
2301                 .common.version    = AST_SECURITY_EVENT_REQ_NOT_ALLOWED_VERSION,
2302                 .common.service    = "AMI",
2303                 .common.account_id = s->session->username,
2304                 .common.session_tv = &s->session->sessionstart_tv,
2305                 .common.local_addr = {
2306                         .sin       = mansession_encode_sin_local(s, &sin_local),
2307                         .transport = mansession_get_transport(s),
2308                 },
2309                 .common.remote_addr = {
2310                         .sin       = &s->session->sin,
2311                         .transport = mansession_get_transport(s),
2312                 },
2313                 .common.session_id = session_id,
2314
2315                 .request_type      = request_type,
2316         };
2317
2318         snprintf(session_id, sizeof(session_id), "%p", s->session);
2319         snprintf(request_type, sizeof(request_type), "Action: %s", action);
2320
2321         ast_security_event_report(AST_SEC_EVT(&req_not_allowed));
2322 }
2323
2324 static void report_req_bad_format(const struct mansession *s, const char *action)
2325 {
2326         struct sockaddr_in sin_local;
2327         char session_id[32];
2328         char request_type[64];
2329         struct ast_security_event_req_bad_format req_bad_format = {
2330                 .common.event_type = AST_SECURITY_EVENT_REQ_BAD_FORMAT,
2331                 .common.version    = AST_SECURITY_EVENT_REQ_BAD_FORMAT_VERSION,
2332                 .common.service    = "AMI",
2333                 .common.account_id = s->session->username,
2334                 .common.session_tv = &s->session->sessionstart_tv,
2335                 .common.local_addr = {
2336                         .sin       = mansession_encode_sin_local(s, &sin_local),
2337                         .transport = mansession_get_transport(s),
2338                 },
2339                 .common.remote_addr = {
2340                         .sin       = &s->session->sin,
2341                         .transport = mansession_get_transport(s),
2342                 },
2343                 .common.session_id = session_id,
2344
2345                 .request_type      = request_type,
2346         };
2347
2348         snprintf(session_id, sizeof(session_id), "%p", s->session);
2349         snprintf(request_type, sizeof(request_type), "Action: %s", action);
2350
2351         ast_security_event_report(AST_SEC_EVT(&req_bad_format));
2352 }
2353
2354 static void report_failed_challenge_response(const struct mansession *s,
2355                 const char *response, const char *expected_response)
2356 {
2357         struct sockaddr_in sin_local;
2358         char session_id[32];
2359         struct ast_security_event_chal_resp_failed chal_resp_failed = {
2360                 .common.event_type = AST_SECURITY_EVENT_CHAL_RESP_FAILED,
2361                 .common.version    = AST_SECURITY_EVENT_CHAL_RESP_FAILED_VERSION,
2362                 .common.service    = "AMI",
2363                 .common.account_id = s->session->username,
2364                 .common.session_tv = &s->session->sessionstart_tv,
2365                 .common.local_addr = {
2366                         .sin       = mansession_encode_sin_local(s, &sin_local),
2367                         .transport = mansession_get_transport(s),
2368                 },
2369                 .common.remote_addr = {
2370                         .sin       = &s->session->sin,
2371                         .transport = mansession_get_transport(s),
2372                 },
2373                 .common.session_id = session_id,
2374
2375                 .challenge         = s->session->challenge,
2376                 .response          = response,
2377                 .expected_response = expected_response,
2378         };
2379
2380         snprintf(session_id, sizeof(session_id), "%p", s->session);
2381
2382         ast_security_event_report(AST_SEC_EVT(&chal_resp_failed));
2383 }
2384
2385 static void report_session_limit(const struct mansession *s)
2386 {
2387         struct sockaddr_in sin_local;
2388         char session_id[32];
2389         struct ast_security_event_session_limit session_limit = {
2390                 .common.event_type = AST_SECURITY_EVENT_SESSION_LIMIT,
2391                 .common.version    = AST_SECURITY_EVENT_SESSION_LIMIT_VERSION,
2392                 .common.service    = "AMI",
2393                 .common.account_id = s->session->username,
2394                 .common.session_tv = &s->session->sessionstart_tv,
2395                 .common.local_addr = {
2396                         .sin       = mansession_encode_sin_local(s, &sin_local),
2397                         .transport = mansession_get_transport(s),
2398                 },
2399                 .common.remote_addr = {
2400                         .sin       = &s->session->sin,
2401                         .transport = mansession_get_transport(s),
2402                 },
2403                 .common.session_id = session_id,
2404         };
2405
2406         snprintf(session_id, sizeof(session_id), "%p", s->session);
2407
2408         ast_security_event_report(AST_SEC_EVT(&session_limit));
2409 }
2410
2411 /*
2412  * Here we start with action_ handlers for AMI actions,
2413  * and the internal functions used by them.
2414  * Generally, the handlers are called action_foo()
2415  */
2416
2417 /* helper function for action_login() */
2418 static int authenticate(struct mansession *s, const struct message *m)
2419 {
2420         const char *username = astman_get_header(m, "Username");
2421         const char *password = astman_get_header(m, "Secret");
2422         int error = -1;
2423         struct ast_manager_user *user = NULL;
2424         regex_t *regex_filter;
2425         struct ao2_iterator filter_iter;
2426         struct ast_sockaddr addr;
2427
2428         if (ast_strlen_zero(username)) {        /* missing username */
2429                 return -1;
2430         }
2431
2432         /* locate user in locked state */
2433         AST_RWLIST_WRLOCK(&users);
2434
2435         ast_sockaddr_from_sin(&addr, &s->session->sin);
2436
2437         if (!(user = get_manager_by_name_locked(username))) {
2438                 report_invalid_user(s, username);
2439                 ast_log(LOG_NOTICE, "%s tried to authenticate with nonexistent user '%s'\n", ast_inet_ntoa(s->session->sin.sin_addr), username);
2440         } else if (user->ha && !ast_apply_ha(user->ha, &addr)) {
2441                 report_failed_acl(s, username);
2442                 ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", ast_inet_ntoa(s->session->sin.sin_addr), username);
2443         } else if (!strcasecmp(astman_get_header(m, "AuthType"), "MD5")) {
2444                 const char *key = astman_get_header(m, "Key");
2445                 if (!ast_strlen_zero(key) && !ast_strlen_zero(s->session->challenge) && user->secret) {
2446                         int x;
2447                         int len = 0;
2448                         char md5key[256] = "";
2449                         struct MD5Context md5;
2450                         unsigned char digest[16];
2451
2452                         MD5Init(&md5);
2453                         MD5Update(&md5, (unsigned char *) s->session->challenge, strlen(s->session->challenge));
2454                         MD5Update(&md5, (unsigned char *) user->secret, strlen(user->secret));
2455                         MD5Final(digest, &md5);
2456                         for (x = 0; x < 16; x++)
2457                                 len += sprintf(md5key + len, "%2.2x", digest[x]);
2458                         if (!strcmp(md5key, key)) {
2459                                 error = 0;
2460                         } else {
2461                                 report_failed_challenge_response(s, key, md5key);
2462                         }
2463                 } else {
2464                         ast_debug(1, "MD5 authentication is not possible.  challenge: '%s'\n",
2465                                 S_OR(s->session->challenge, ""));
2466                 }
2467         } else if (user->secret) {
2468                 if (!strcmp(password, user->secret)) {
2469                         error = 0;
2470                 } else {
2471                         report_inval_password(s, username);
2472                 }
2473         }
2474
2475         if (error) {
2476                 ast_log(LOG_NOTICE, "%s failed to authenticate as '%s'\n", ast_inet_ntoa(s->session->sin.sin_addr), username);
2477                 AST_RWLIST_UNLOCK(&users);
2478                 return -1;
2479         }
2480
2481         /* auth complete */
2482
2483         /* All of the user parameters are copied to the session so that in the event
2484         * of a reload and a configuration change, the session parameters are not
2485         * changed. */
2486         ast_copy_string(s->session->username, username, sizeof(s->session->username));
2487         s->session->readperm = user->readperm;
2488         s->session->writeperm = user->writeperm;
2489         s->session->writetimeout = user->writetimeout;
2490
2491         filter_iter = ao2_iterator_init(user->whitefilters, 0);
2492         while ((regex_filter = ao2_iterator_next(&filter_iter))) {
2493                 ao2_t_link(s->session->whitefilters, regex_filter, "add white user filter to session");
2494                 ao2_t_ref(regex_filter, -1, "remove iterator ref");
2495         }
2496         ao2_iterator_destroy(&filter_iter);
2497
2498         filter_iter = ao2_iterator_init(user->blackfilters, 0);
2499         while ((regex_filter = ao2_iterator_next(&filter_iter))) {
2500                 ao2_t_link(s->session->blackfilters, regex_filter, "add black user filter to session");
2501                 ao2_t_ref(regex_filter, -1, "remove iterator ref");
2502         }
2503         ao2_iterator_destroy(&filter_iter);
2504
2505         s->session->sessionstart = time(NULL);
2506         s->session->sessionstart_tv = ast_tvnow();
2507         set_eventmask(s, astman_get_header(m, "Events"));
2508
2509         report_auth_success(s);
2510
2511         AST_RWLIST_UNLOCK(&users);
2512         return 0;
2513 }
2514
2515 static int action_ping(struct mansession *s, const struct message *m)
2516 {
2517         const char *actionid = astman_get_header(m, "ActionID");
2518         struct timeval now = ast_tvnow();
2519
2520         astman_append(s, "Response: Success\r\n");
2521         if (!ast_strlen_zero(actionid)){
2522                 astman_append(s, "ActionID: %s\r\n", actionid);
2523         }
2524         astman_append(
2525                 s,
2526                 "Ping: Pong\r\n"
2527                 "Timestamp: %ld.%06lu\r\n"
2528                 "\r\n",
2529                 (long) now.tv_sec, (unsigned long) now.tv_usec);
2530         return 0;
2531 }
2532
2533 static int action_getconfig(struct mansession *s, const struct message *m)
2534 {
2535         struct ast_config *cfg;
2536         const char *fn = astman_get_header(m, "Filename");
2537         const char *category = astman_get_header(m, "Category");
2538         int catcount = 0;
2539         int lineno = 0;
2540         char *cur_category = NULL;
2541         struct ast_variable *v;
2542         struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2543
2544         if (ast_strlen_zero(fn)) {
2545                 astman_send_error(s, m, "Filename not specified");
2546                 return 0;
2547         }
2548         cfg = ast_config_load2(fn, "manager", config_flags);
2549         if (cfg == CONFIG_STATUS_FILEMISSING) {
2550                 astman_send_error(s, m, "Config file not found");
2551                 return 0;
2552         } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2553                 astman_send_error(s, m, "Config file has invalid format");
2554                 return 0;
2555         }
2556
2557         astman_start_ack(s, m);
2558         while ((cur_category = ast_category_browse(cfg, cur_category))) {
2559                 if (ast_strlen_zero(category) || (!ast_strlen_zero(category) && !strcmp(category, cur_category))) {
2560                         lineno = 0;
2561                         astman_append(s, "Category-%06d: %s\r\n", catcount, cur_category);
2562                         for (v = ast_variable_browse(cfg, cur_category); v; v = v->next) {
2563                                 astman_append(s, "Line-%06d-%06d: %s=%s\r\n", catcount, lineno++, v->name, v->value);
2564                         }
2565                         catcount++;
2566                 }
2567         }
2568         if (!ast_strlen_zero(category) && catcount == 0) { /* TODO: actually, a config with no categories doesn't even get loaded */
2569                 astman_append(s, "No categories found\r\n");
2570         }
2571         ast_config_destroy(cfg);
2572         astman_append(s, "\r\n");
2573
2574         return 0;
2575 }
2576
2577 static int action_listcategories(struct mansession *s, const struct message *m)
2578 {
2579         struct ast_config *cfg;
2580         const char *fn = astman_get_header(m, "Filename");
2581         char *category = NULL;
2582         struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2583         int catcount = 0;
2584
2585         if (ast_strlen_zero(fn)) {
2586                 astman_send_error(s, m, "Filename not specified");
2587                 return 0;
2588         }
2589         if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
2590                 astman_send_error(s, m, "Config file not found");
2591                 return 0;
2592         } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2593                 astman_send_error(s, m, "Config file has invalid format");
2594                 return 0;
2595         }
2596         astman_start_ack(s, m);
2597         while ((category = ast_category_browse(cfg, category))) {
2598                 astman_append(s, "Category-%06d: %s\r\n", catcount, category);
2599                 catcount++;
2600         }
2601         if (catcount == 0) { /* TODO: actually, a config with no categories doesn't even get loaded */
2602                 astman_append(s, "Error: no categories found\r\n");
2603         }
2604         ast_config_destroy(cfg);
2605         astman_append(s, "\r\n");
2606
2607         return 0;
2608 }
2609
2610
2611
2612
2613 /*! The amount of space in out must be at least ( 2 * strlen(in) + 1 ) */
2614 static void json_escape(char *out, const char *in)
2615 {
2616         for (; *in; in++) {
2617                 if (*in == '\\' || *in == '\"') {
2618                         *out++ = '\\';
2619                 }
2620                 *out++ = *in;
2621         }
2622         *out = '\0';
2623 }
2624
2625 /*!
2626  * \internal
2627  * \brief Append a JSON escaped string to the manager stream.
2628  *
2629  * \param s AMI stream to append a string.
2630  * \param str String to append to the stream after JSON escaping it.
2631  *
2632  * \return Nothing
2633  */
2634 static void astman_append_json(struct mansession *s, const char *str)
2635 {
2636         char *buf;
2637
2638         buf = alloca(2 * strlen(str) + 1);
2639         json_escape(buf, str);
2640         astman_append(s, "%s", buf);
2641 }
2642
2643 static int action_getconfigjson(struct mansession *s, const struct message *m)
2644 {
2645         struct ast_config *cfg;
2646         const char *fn = astman_get_header(m, "Filename");
2647         char *category = NULL;
2648         struct ast_variable *v;
2649         int comma1 = 0;
2650         struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2651
2652         if (ast_strlen_zero(fn)) {
2653                 astman_send_error(s, m, "Filename not specified");
2654                 return 0;
2655         }
2656
2657         if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
2658                 astman_send_error(s, m, "Config file not found");
2659                 return 0;
2660         } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2661                 astman_send_error(s, m, "Config file has invalid format");
2662                 return 0;
2663         }
2664
2665         astman_start_ack(s, m);
2666         astman_append(s, "JSON: {");
2667         while ((category = ast_category_browse(cfg, category))) {
2668                 int comma2 = 0;
2669
2670                 astman_append(s, "%s\"", comma1 ? "," : "");
2671                 astman_append_json(s, category);
2672                 astman_append(s, "\":[");
2673                 comma1 = 1;
2674                 for (v = ast_variable_browse(cfg, category); v; v = v->next) {
2675                         astman_append(s, "%s\"", comma2 ? "," : "");
2676                         astman_append_json(s, v->name);
2677                         astman_append(s, "\":\"");
2678                         astman_append_json(s, v->value);
2679                         astman_append(s, "\"");
2680                         comma2 = 1;
2681                 }
2682                 astman_append(s, "]");
2683         }
2684         astman_append(s, "}\r\n\r\n");
2685
2686         ast_config_destroy(cfg);
2687
2688         return 0;
2689 }
2690
2691 /*! \brief helper function for action_updateconfig */
2692 static enum error_type handle_updates(struct mansession *s, const struct message *m, struct ast_config *cfg, const char *dfn)
2693 {
2694         int x;
2695         char hdr[40];
2696         const char *action, *cat, *var, *value, *match, *line;
2697         struct ast_category *category;
2698         struct ast_variable *v;
2699         struct ast_str *str1 = ast_str_create(16), *str2 = ast_str_create(16);
2700         enum error_type result = 0;
2701
2702         for (x = 0; x < 100000; x++) {  /* 100000 = the max number of allowed updates + 1 */
2703                 unsigned int object = 0;
2704
2705                 snprintf(hdr, sizeof(hdr), "Action-%06d", x);
2706                 action = astman_get_header(m, hdr);
2707                 if (ast_strlen_zero(action))            /* breaks the for loop if no action header */
2708                         break;                          /* this could cause problems if actions come in misnumbered */
2709
2710                 snprintf(hdr, sizeof(hdr), "Cat-%06d", x);
2711                 cat = astman_get_header(m, hdr);
2712                 if (ast_strlen_zero(cat)) {             /* every action needs a category */
2713                         result =  UNSPECIFIED_CATEGORY;
2714                         break;
2715                 }
2716
2717                 snprintf(hdr, sizeof(hdr), "Var-%06d", x);
2718                 var = astman_get_header(m, hdr);
2719
2720                 snprintf(hdr, sizeof(hdr), "Value-%06d", x);
2721                 value = astman_get_header(m, hdr);
2722
2723                 if (!ast_strlen_zero(value) && *value == '>') {
2724                         object = 1;
2725                         value++;
2726                 }
2727
2728                 snprintf(hdr, sizeof(hdr), "Match-%06d", x);
2729                 match = astman_get_header(m, hdr);
2730
2731                 snprintf(hdr, sizeof(hdr), "Line-%06d", x);
2732                 line = astman_get_header(m, hdr);
2733
2734                 if (!strcasecmp(action, "newcat")) {
2735                         if (ast_category_get(cfg,cat)) {        /* check to make sure the cat doesn't */
2736                                 result = FAILURE_NEWCAT;        /* already exist */
2737                                 break;
2738                         }
2739                         if (!(category = ast_category_new(cat, dfn, -1))) {
2740                                 result = FAILURE_ALLOCATION;
2741                                 break;
2742                         }
2743                         if (ast_strlen_zero(match)) {
2744                                 ast_category_append(cfg, category);
2745                         } else {
2746                                 ast_category_insert(cfg, category, match);
2747                         }
2748                 } else if (!strcasecmp(action, "renamecat")) {
2749                         if (ast_strlen_zero(value)) {
2750                                 result = UNSPECIFIED_ARGUMENT;
2751                                 break;
2752                         }
2753                         if (!(category = ast_category_get(cfg, cat))) {
2754                                 result = UNKNOWN_CATEGORY;
2755                                 break;
2756                         }
2757                         ast_category_rename(category, value);
2758                 } else if (!strcasecmp(action, "delcat")) {
2759                         if (ast_category_delete(cfg, cat)) {
2760                                 result = FAILURE_DELCAT;
2761                                 break;
2762                         }
2763                 } else if (!strcasecmp(action, "emptycat")) {
2764                         if (ast_category_empty(cfg, cat)) {
2765                                 result = FAILURE_EMPTYCAT;
2766                                 break;
2767                         }
2768                 } else if (!strcasecmp(action, "update")) {
2769                         if (ast_strlen_zero(var)) {
2770                                 result = UNSPECIFIED_ARGUMENT;
2771                                 break;
2772                         }
2773                         if (!(category = ast_category_get(cfg,cat))) {
2774                                 result = UNKNOWN_CATEGORY;
2775                                 break;
2776                         }
2777                         if (ast_variable_update(category, var, value, match, object)) {
2778                                 result = FAILURE_UPDATE;
2779                                 break;
2780                         }
2781                 } else if (!strcasecmp(action, "delete")) {
2782                         if ((ast_strlen_zero(var) && ast_strlen_zero(line))) {
2783                                 result = UNSPECIFIED_ARGUMENT;
2784                                 break;
2785                         }
2786                         if (!(category = ast_category_get(cfg, cat))) {
2787                                 result = UNKNOWN_CATEGORY;
2788                                 break;
2789                         }
2790                         if (ast_variable_delete(category, var, match, line)) {
2791                                 result = FAILURE_DELETE;
2792                                 break;
2793                         }
2794                 } else if (!strcasecmp(action, "append")) {
2795                         if (ast_strlen_zero(var)) {
2796                                 result = UNSPECIFIED_ARGUMENT;
2797                                 break;
2798                         }
2799                         if (!(category = ast_category_get(cfg, cat))) {
2800                                 result = UNKNOWN_CATEGORY;
2801                                 break;
2802                         }
2803                         if (!(v = ast_variable_new(var, value, dfn))) {
2804                                 result = FAILURE_ALLOCATION;
2805                                 break;
2806                         }
2807                         if (object || (match && !strcasecmp(match, "object"))) {
2808                                 v->object = 1;
2809                         }
2810                         ast_variable_append(category, v);
2811                 } else if (!strcasecmp(action, "insert")) {
2812                         if (ast_strlen_zero(var) || ast_strlen_zero(line)) {
2813                                 result = UNSPECIFIED_ARGUMENT;
2814                                 break;
2815                         }
2816                         if (!(category = ast_category_get(cfg, cat))) {
2817                                 result = UNKNOWN_CATEGORY;
2818                                 break;
2819                         }
2820                         if (!(v = ast_variable_new(var, value, dfn))) {
2821                                 result = FAILURE_ALLOCATION;
2822                                 break;
2823                         }
2824                         ast_variable_insert(category, v, line);
2825                 }
2826                 else {
2827                         ast_log(LOG_WARNING, "Action-%06d: %s not handled\n", x, action);
2828                         result = UNKNOWN_ACTION;
2829                         break;
2830                 }
2831         }
2832         ast_free(str1);
2833         ast_free(str2);
2834         return result;
2835 }
2836
2837 static int action_updateconfig(struct mansession *s, const struct message *m)
2838 {
2839         struct ast_config *cfg;
2840         const char *sfn = astman_get_header(m, "SrcFilename");
2841         const char *dfn = astman_get_header(m, "DstFilename");
2842         int res;
2843         const char *rld = astman_get_header(m, "Reload");
2844         struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2845         enum error_type result;
2846
2847         if (ast_strlen_zero(sfn) || ast_strlen_zero(dfn)) {
2848                 astman_send_error(s, m, "Filename not specified");
2849                 return 0;
2850         }
2851         if (!(cfg = ast_config_load2(sfn, "manager", config_flags))) {
2852                 astman_send_error(s, m, "Config file not found");
2853                 return 0;
2854         } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2855                 astman_send_error(s, m, "Config file has invalid format");
2856                 return 0;
2857         }
2858         result = handle_updates(s, m, cfg, dfn);
2859         if (!result) {
2860                 ast_include_rename(cfg, sfn, dfn); /* change the include references from dfn to sfn, so things match up */
2861                 res = ast_config_text_file_save(dfn, cfg, "Manager");
2862                 ast_config_destroy(cfg);
2863                 if (res) {
2864                         astman_send_error(s, m, "Save of config failed");
2865                         return 0;
2866                 }
2867                 astman_send_ack(s, m, NULL);
2868                 if (!ast_strlen_zero(rld)) {
2869                         if (ast_true(rld)) {
2870                                 rld = NULL;
2871                         }
2872                         ast_module_reload(rld);
2873                 }
2874         } else {
2875                 ast_config_destroy(cfg);
2876                 switch(result) {
2877                 case UNKNOWN_ACTION:
2878                         astman_send_error(s, m, "Unknown action command");
2879                         break;
2880                 case UNKNOWN_CATEGORY:
2881                         astman_send_error(s, m, "Given category does not exist");
2882                         break;
2883                 case UNSPECIFIED_CATEGORY:
2884                         astman_send_error(s, m, "Category not specified");
2885                         break;
2886                 case UNSPECIFIED_ARGUMENT:
2887                         astman_send_error(s, m, "Problem with category, value, or line (if required)");
2888                         break;
2889                 case FAILURE_ALLOCATION:
2890                         astman_send_error(s, m, "Memory allocation failure, this should not happen");
2891                         break;
2892                 case FAILURE_NEWCAT:
2893                         astman_send_error(s, m, "Create category did not complete successfully");
2894                         break;
2895                 case FAILURE_DELCAT:
2896                         astman_send_error(s, m, "Delete category did not complete successfully");
2897                         break;
2898                 case FAILURE_EMPTYCAT:
2899                         astman_send_error(s, m, "Empty category did not complete successfully");
2900                         break;
2901                 case FAILURE_UPDATE:
2902                         astman_send_error(s, m, "Update did not complete successfully");
2903                         break;
2904                 case FAILURE_DELETE:
2905                         astman_send_error(s, m, "Delete did not complete successfully");
2906                         break;
2907                 case FAILURE_APPEND:
2908                         astman_send_error(s, m, "Append did not complete successfully");
2909                         break;
2910                 }
2911         }
2912         return 0;
2913 }
2914
2915 static int action_createconfig(struct mansession *s, const struct message *m)
2916 {
2917         int fd;
2918         const char *fn = astman_get_header(m, "Filename");
2919         struct ast_str *filepath = ast_str_alloca(PATH_MAX);
2920         ast_str_set(&filepath, 0, "%s/", ast_config_AST_CONFIG_DIR);
2921         ast_str_append(&filepath, 0, "%s", fn);
2922
2923         if ((fd = open(ast_str_buffer(filepath), O_CREAT | O_EXCL, AST_FILE_MODE)) != -1) {
2924                 close(fd);
2925                 astman_send_ack(s, m, "New configuration file created successfully");
2926         } else {
2927                 astman_send_error(s, m, strerror(errno));
2928         }
2929
2930         return 0;
2931 }
2932
2933 static int action_waitevent(struct mansession *s, const struct message *m)
2934 {
2935         const char *timeouts = astman_get_header(m, "Timeout");
2936         int timeout = -1;
2937         int x;
2938         int needexit = 0;
2939         const char *id = astman_get_header(m, "ActionID");
2940         char idText[256];
2941
2942         if (!ast_strlen_zero(id)) {
2943                 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
2944         } else {
2945                 idText[0] = '\0';
2946         }
2947
2948         if (!ast_strlen_zero(timeouts)) {
2949                 sscanf(timeouts, "%30i", &timeout);
2950                 if (timeout < -1) {
2951                         timeout = -1;
2952                 }
2953                 /* XXX maybe put an upper bound, or prevent the use of 0 ? */
2954         }
2955
2956         ao2_lock(s->session);
2957         if (s->session->waiting_thread != AST_PTHREADT_NULL) {
2958                 pthread_kill(s->session->waiting_thread, SIGURG);
2959         }
2960
2961         if (s->session->managerid) { /* AMI-over-HTTP session */
2962                 /*
2963                  * Make sure the timeout is within the expire time of the session,
2964                  * as the client will likely abort the request if it does not see
2965                  * data coming after some amount of time.
2966                  */
2967                 time_t now = time(NULL);
2968                 int max = s->session->sessiontimeout - now - 10;
2969
2970                 if (max < 0) {  /* We are already late. Strange but possible. */
2971                         max = 0;
2972                 }
2973                 if (timeout < 0 || timeout > max) {
2974                         timeout = max;
2975                 }
2976                 if (!s->session->send_events) { /* make sure we record events */
2977                         s->session->send_events = -1;
2978                 }
2979         }
2980         ao2_unlock(s->session);
2981
2982         /* XXX should this go inside the lock ? */
2983         s->session->waiting_thread = pthread_self();    /* let new events wake up this thread */
2984         ast_debug(1, "Starting waiting for an event!\n");
2985
2986         for (x = 0; x < timeout || timeout < 0; x++) {
2987                 ao2_lock(s->session);
2988                 if (AST_RWLIST_NEXT(s->session->last_ev, eq_next)) {
2989                         needexit = 1;
2990                 }
2991                 /* We can have multiple HTTP session point to the same mansession entry.
2992                  * The way we deal with it is not very nice: newcomers kick out the previous
2993                  * HTTP session. XXX this needs to be improved.
2994                  */
2995                 if (s->session->waiting_thread != pthread_self()) {
2996                         needexit = 1;
2997                 }
2998                 if (s->session->needdestroy) {
2999                         needexit = 1;
3000                 }
3001                 ao2_unlock(s->session);
3002                 if (needexit) {
3003                         break;
3004                 }
3005                 if (s->session->managerid == 0) {       /* AMI session */
3006                         if (ast_wait_for_input(s->session->fd, 1000)) {
3007                                 break;
3008                         }
3009                 } else {        /* HTTP session */
3010                         sleep(1);
3011                 }
3012         }
3013         ast_debug(1, "Finished waiting for an event!\n");
3014
3015         ao2_lock(s->session);
3016         if (s->session->waiting_thread == pthread_self()) {
3017                 struct eventqent *eqe = s->session->last_ev;
3018                 astman_send_response(s, m, "Success", "Waiting for Event completed.");
3019                 while ((eqe = advance_event(eqe))) {
3020                         if (((s->session->readperm & eqe->category) == eqe->category) &&
3021                             ((s->session->send_events & eqe->category) == eqe->category)) {
3022                                 astman_append(s, "%s", eqe->eventdata);
3023                         }
3024                         s->session->last_ev = eqe;
3025                 }
3026                 astman_append(s,
3027                         "Event: WaitEventComplete\r\n"
3028                         "%s"
3029                         "\r\n", idText);
3030                 s->session->waiting_thread = AST_PTHREADT_NULL;
3031         } else {
3032                 ast_debug(1, "Abandoning event request!\n");
3033         }
3034         ao2_unlock(s->session);
3035
3036         return 0;
3037 }
3038
3039 static int action_listcommands(struct mansession *s, const struct message *m)
3040 {
3041         struct manager_action *cur;
3042         struct ast_str *temp = ast_str_alloca(256);
3043
3044         astman_start_ack(s, m);
3045         AST_RWLIST_RDLOCK(&actions);
3046         AST_RWLIST_TRAVERSE(&actions, cur, list) {
3047                 if ((s->session->writeperm & cur->authority) || cur->authority == 0) {
3048                         astman_append(s, "%s: %s (Priv: %s)\r\n",
3049                                 cur->action, cur->synopsis, authority_to_str(cur->authority, &temp));
3050                 }
3051         }
3052         AST_RWLIST_UNLOCK(&actions);
3053         astman_append(s, "\r\n");
3054
3055         return 0;
3056 }
3057
3058 static int action_events(struct mansession *s, const struct message *m)
3059 {
3060         const char *mask = astman_get_header(m, "EventMask");
3061         int res, x;
3062         const char *id = astman_get_header(m, "ActionID");
3063         char id_text[256];
3064
3065         if (!ast_strlen_zero(id)) {
3066                 snprintf(id_text, sizeof(id_text), "ActionID: %s\r\n", id);
3067         } else {
3068                 id_text[0] = '\0';
3069         }
3070
3071         res = set_eventmask(s, mask);
3072         if (broken_events_action) {
3073                 /* if this option is set we should not return a response on
3074                  * error, or when all events are set */
3075
3076                 if (res > 0) {
3077                         for (x = 0; x < ARRAY_LEN(perms); x++) {
3078                                 if (!strcasecmp(perms[x].label, "all") && res == perms[x].num) {
3079                                         return 0;
3080                                 }
3081                         }
3082                         astman_append(s, "Response: Success\r\n%s"
3083                                          "Events: On\r\n\r\n", id_text);
3084                 } else if (res == 0)
3085                         astman_append(s, "Response: Success\r\n%s"
3086                                          "Events: Off\r\n\r\n", id_text);
3087                 return 0;
3088         }
3089
3090         if (res > 0)
3091                 astman_append(s, "Response: Success\r\n%s"
3092                                  "Events: On\r\n\r\n", id_text);
3093         else if (res == 0)
3094                 astman_append(s, "Response: Success\r\n%s"
3095                                  "Events: Off\r\n\r\n", id_text);
3096         else
3097                 astman_send_error(s, m, "Invalid event mask");
3098
3099         return 0;
3100 }
3101
3102 static int action_logoff(struct mansession *s, const struct message *m)
3103 {
3104         astman_send_response(s, m, "Goodbye", "Thanks for all the fish.");
3105         return -1;
3106 }
3107
3108 static int action_login(struct mansession *s, const struct message *m)
3109 {
3110
3111         /* still authenticated - don't process again */
3112         if (s->session->authenticated) {
3113                 astman_send_ack(s, m, "Already authenticated");
3114                 return 0;
3115         }
3116
3117         if (authenticate(s, m)) {
3118                 sleep(1);
3119                 astman_send_error(s, m, "Authentication failed");
3120                 return -1;
3121         }
3122         s->session->authenticated = 1;
3123         ast_atomic_fetchadd_int(&unauth_sessions, -1);
3124         if (manager_displayconnects(s->session)) {
3125                 ast_verb(2, "%sManager '%s' logged on from %s\n", (s->session->managerid ? "HTTP " : ""), s->session->username, ast_inet_ntoa(s->session->sin.sin_addr));
3126         }
3127         astman_send_ack(s, m, "Authentication accepted");
3128         if ((s->session->send_events & EVENT_FLAG_SYSTEM)
3129                 && ast_test_flag(&ast_options, AST_OPT_FLAG_FULLY_BOOTED)) {
3130                 struct ast_str *auth = ast_str_alloca(80);
3131                 const char *cat_str = authority_to_str(EVENT_FLAG_SYSTEM, &auth);
3132                 astman_append(s, "Event: FullyBooted\r\n"
3133                         "Privilege: %s\r\n"
3134                         "Status: Fully Booted\r\n\r\n", cat_str);
3135         }
3136         return 0;
3137 }
3138
3139 static int action_challenge(struct mansession *s, const struct message *m)
3140 {
3141         const char *authtype = astman_get_header(m, "AuthType");
3142
3143         if (!strcasecmp(authtype, "MD5")) {
3144                 if (ast_strlen_zero(s->session->challenge)) {
3145                         snprintf(s->session->challenge, sizeof(s->session->challenge), "%ld", ast_random());
3146                 }
3147                 mansession_lock(s);
3148                 astman_start_ack(s, m);
3149                 astman_append(s, "Challenge: %s\r\n\r\n", s->session->challenge);
3150                 mansession_unlock(s);
3151         } else {
3152                 astman_send_error(s, m, "Must specify AuthType");
3153         }
3154         return 0;
3155 }
3156
3157 static int action_hangup(struct mansession *s, const struct message *m)
3158 {
3159         struct ast_channel *c = NULL;
3160         int causecode = 0; /* all values <= 0 mean 'do not set hangupcause in channel' */
3161         const char *id = astman_get_header(m, "ActionID");
3162         const char *name_or_regex = astman_get_header(m, "Channel");
3163         const char *cause = astman_get_header(m, "Cause");
3164         char idText[256] = "";
3165         regex_t regexbuf;
3166         struct ast_channel_iterator *iter = NULL;
3167         struct ast_str *regex_string;
3168         int channels_matched = 0;
3169
3170         if (ast_strlen_zero(name_or_regex)) {
3171                 astman_send_error(s, m, "No channel specified");
3172                 return 0;
3173         }
3174
3175         if (!ast_strlen_zero(id)) {
3176                 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
3177         }
3178
3179         if (!ast_strlen_zero(cause)) {
3180                 char *endptr;
3181                 causecode = strtol(cause, &endptr, 10);
3182                 if (causecode < 0 || causecode > 127 || *endptr != '\0') {
3183                         ast_log(LOG_NOTICE, "Invalid 'Cause: %s' in manager action Hangup\n", cause);
3184                         /* keep going, better to hangup without cause than to not hang up at all */
3185                         causecode = 0; /* do not set channel's hangupcause */
3186                 }
3187         }
3188
3189         /************************************************/
3190         /* Regular explicit match channel byname hangup */
3191
3192         if (name_or_regex[0] != '/') {
3193                 if (!(c = ast_channel_get_by_name(name_or_regex))) {
3194                         astman_send_error(s, m, "No such channel");
3195                         return 0;
3196                 }
3197
3198                 ast_verb(3, "%sManager '%s' from %s, hanging up channel: %s\n",
3199                         (s->session->managerid ? "HTTP " : ""),
3200                         s->session->username,
3201                         ast_inet_ntoa(s->session->sin.sin_addr),
3202                         ast_channel_name(c));
3203
3204                 ast_channel_softhangup_withcause_locked(c, causecode);
3205                 c = ast_channel_unref(c);
3206
3207                 astman_send_ack(s, m, "Channel Hungup");
3208
3209                 return 0;
3210         }
3211
3212         /***********************************************/
3213         /* find and hangup any channels matching regex */
3214
3215         regex_string = ast_str_create(strlen(name_or_regex));
3216
3217         /* Make "/regex/" into "regex" */
3218         if (ast_regex_string_to_regex_pattern(name_or_regex, regex_string) != 0) {
3219                 astman_send_error(s, m, "Regex format invalid, Channel param should be /regex/");
3220                 ast_free(regex_string);
3221                 return 0;
3222         }
3223
3224         /* if regex compilation fails, hangup fails */
3225         if (regcomp(&regexbuf, ast_str_buffer(regex_string), REG_EXTENDED | REG_NOSUB)) {
3226                 astman_send_error_va(s, m, "Regex compile failed on: %s\n", name_or_regex);
3227                 ast_free(regex_string);
3228                 return 0;
3229         }
3230
3231         astman_send_listack(s, m, "Channels hung up will follow", "start");
3232
3233         for (iter = ast_channel_iterator_all_new(); iter && (c = ast_channel_iterator_next(iter)); ) {
3234                 if (regexec(&regexbuf, ast_channel_name(c), 0, NULL, 0)) {
3235                         ast_channel_unref(c);
3236                         continue;
3237                 }
3238
3239                 ast_verb(3, "%sManager '%s' from %s, hanging up channel: %s\n",
3240                         (s->session->managerid ? "HTTP " : ""),
3241                         s->session->username,
3242                         ast_inet_ntoa(s->session->sin.sin_addr),
3243                         ast_channel_name(c));
3244
3245                 ast_channel_softhangup_withcause_locked(c, causecode);
3246                 channels_matched++;
3247
3248                 astman_append(s,
3249                         "Event: ChannelHungup\r\n"
3250                         "Channel: %s\r\n"
3251                         "%s"
3252                         "\r\n", ast_channel_name(c), idText);
3253
3254                 ast_channel_unref(c);
3255         }
3256
3257         ast_channel_iterator_destroy(iter);
3258         regfree(&regexbuf);
3259         ast_free(regex_string);
3260
3261         astman_append(s,
3262                 "Event: ChannelsHungupListComplete\r\n"
3263                 "EventList: Complete\r\n"
3264                 "ListItems: %d\r\n"
3265                 "%s"
3266                 "\r\n", channels_matched, idText);
3267
3268         return 0;
3269 }
3270
3271 static int action_setvar(struct mansession *s, const struct message *m)
3272 {
3273         struct ast_channel *c = NULL;
3274         const char *name = astman_get_header(m, "Channel");
3275         const char *varname = astman_get_header(m, "Variable");
3276         const char *varval = astman_get_header(m, "Value");
3277         int res = 0;
3278
3279         if (ast_strlen_zero(varname)) {
3280                 astman_send_error(s, m, "No variable specified");
3281                 return 0;
3282         }
3283
3284         if (!ast_strlen_zero(name)) {
3285                 if (!(c = ast_channel_get_by_name(name))) {
3286                         astman_send_error(s, m, "No such channel");
3287                         return 0;
3288                 }
3289         }
3290
3291         res = pbx_builtin_setvar_helper(c, varname, S_OR(varval, ""));
3292
3293         if (c) {
3294                 c = ast_channel_unref(c);
3295         }
3296         if (res == 0) {
3297                 astman_send_ack(s, m, "Variable Set");
3298         } else {
3299                 astman_send_error(s, m, "Variable not set");
3300         }
3301         return 0;
3302 }
3303
3304 static int action_getvar(struct mansession *s, const struct message *m)
3305 {
3306         struct ast_channel *c = NULL;
3307         const char *name = astman_get_header(m, "Channel");
3308         const char *varname = astman_get_header(m, "Variable");
3309         char *varval;
3310         char workspace[1024];
3311
3312         if (ast_strlen_zero(varname)) {
3313                 astman_send_error(s, m, "No variable specified");
3314                 return 0;
3315         }
3316
3317         if (!ast_strlen_zero(name)) {
3318                 if (!(c = ast_channel_get_by_name(name))) {
3319                         astman_send_error(s, m, "No such channel");
3320                         return 0;
3321                 }
3322         }
3323
3324         workspace[0] = '\0';
3325         if (varname[strlen(varname) - 1] == ')') {
3326                 if (!c) {
3327                         c = ast_dummy_channel_alloc();
3328                         if (c) {
3329                                 ast_func_read(c, (char *) varname, workspace, sizeof(workspace));
3330                         } else
3331                                 ast_log(LOG_ERROR, "Unable to allocate bogus channel for variable substitution.  Function results may be blank.\n");
3332                 } else {
3333                         ast_func_read(c, (char *) varname, workspace, sizeof(workspace));
3334                 }
3335                 varval = workspace;
3336         } else {
3337                 pbx_retrieve_variable(c, varname, &varval, workspace, sizeof(workspace), NULL);
3338         }
3339
3340         if (c) {
3341                 c = ast_channel_unref(c);
3342         }
3343
3344         astman_start_ack(s, m);
3345         astman_append(s, "Variable: %s\r\nValue: %s\r\n\r\n", varname, S_OR(varval, ""));
3346
3347         return 0;
3348 }
3349
3350 /*! \brief Manager "status" command to show channels */
3351 /* Needs documentation... */
3352 static int action_status(struct mansession *s, const struct message *m)
3353 {
3354         const char *name = astman_get_header(m, "Channel");
3355         const char *cvariables = astman_get_header(m, "Variables");
3356         char *variables = ast_strdupa(S_OR(cvariables, ""));
3357         struct ast_channel *c;
3358         char bridge[256];
3359         struct timeval now = ast_tvnow();
3360         long elapsed_seconds = 0;
3361         int channels = 0;
3362         int all = ast_strlen_zero(name); /* set if we want all channels */
3363         const char *id = astman_get_header(m, "ActionID");
3364         char idText[256];
3365         AST_DECLARE_APP_ARGS(vars,
3366                 AST_APP_ARG(name)[100];
3367         );
3368         struct ast_str *str = ast_str_create(1000);
3369         struct ast_channel_iterator *iter = NULL;
3370
3371         if (!ast_strlen_zero(id)) {
3372                 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
3373         } else {
3374                 idText[0] = '\0';
3375         }
3376
3377         if (all) {
3378                 if (!(iter = ast_channel_iterator_all_new())) {
3379                         ast_free(str);
3380                         astman_send_error(s, m, "Memory Allocation Failure");
3381                         return 1;
3382                 }
3383                 c = ast_channel_iterator_next(iter);
3384         } else {
3385                 if (!(c = ast_channel_get_by_name(name))) {
3386                         astman_send_error(s, m, "No such channel");
3387                         ast_free(str);
3388                         return 0;
3389                 }
3390         }
3391
3392         astman_send_ack(s, m, "Channel status will follow");
3393
3394         if (!ast_strlen_zero(cvariables)) {
3395                 AST_STANDARD_APP_ARGS(vars, variables);
3396         }
3397
3398         /* if we look by name, we break after the first iteration */
3399         for (; c; c = ast_channel_iterator_next(iter)) {
3400                 ast_channel_lock(c);
3401
3402                 if (!ast_strlen_zero(cvariables)) {
3403                         int i;
3404                         ast_str_reset(str);
3405                         for (i = 0; i < vars.argc; i++) {
3406                                 char valbuf[512], *ret = NULL;
3407
3408                                 if (vars.name[i][strlen(vars.name[i]) - 1] == ')') {
3409                                         if (ast_func_read(c, vars.name[i], valbuf, sizeof(valbuf)) < 0) {
3410                                                 valbuf[0] = '\0';
3411                                         }
3412                                         ret = valbuf;
3413                                 } else {
3414                                         pbx_retrieve_variable(c, vars.name[i], &ret, valbuf, sizeof(valbuf), NULL);
3415                                 }
3416
3417                                 ast_str_append(&str, 0, "Variable: %s=%s\r\n", vars.name[i], ret);
3418                         }
3419                 }
3420
3421                 channels++;
3422                 if (ast_channel_internal_bridged_channel(c)) {
3423                         snprintf(bridge, sizeof(bridge), "BridgedChannel: %s\r\nBridgedUniqueid: %s\r\n", ast_channel_name(ast_channel_internal_bridged_channel(c)), ast_channel_uniqueid(ast_channel_internal_bridged_channel(c)));
3424                 } else {
3425                         bridge[0] = '\0';
3426                 }
3427                 if (ast_channel_pbx(c)) {
3428                         if (ast_channel_cdr(c)) {
3429                                 elapsed_seconds = now.tv_sec - ast_channel_cdr(c)->start.tv_sec;
3430                         }
3431                         astman_append(s,
3432                         "Event: Status\r\n"
3433                         "Privilege: Call\r\n"
3434                         "Channel: %s\r\n"
3435                         "CallerIDNum: %s\r\n"
3436                         "CallerIDName: %s\r\n"
3437                         "ConnectedLineNum: %s\r\n"
3438                         "ConnectedLineName: %s\r\n"
3439                         "Accountcode: %s\r\n"
3440                         "ChannelState: %d\r\n"
3441                         "ChannelStateDesc: %s\r\n"
3442                         "Context: %s\r\n"
3443                         "Extension: %s\r\n"
3444                         "Priority: %d\r\n"
3445                         "Seconds: %ld\r\n"
3446                         "%s"
3447                         "Uniqueid: %s\r\n"
3448                         "%s"
3449                         "%s"
3450                         "\r\n",
3451                         ast_channel_name(c),
3452                         S_COR(ast_channel_caller(c)->id.number.valid, ast_channel_caller(c)->id.number.str, "<unknown>"),
3453                         S_COR(ast_channel_caller(c)->id.name.valid, ast_channel_caller(c)->id.name.str, "<unknown>"),
3454                         S_COR(ast_channel_connected(c)->id.number.valid, ast_channel_connected(c)->id.number.str, "<unknown>"),
3455                         S_COR(ast_channel_connected(c)->id.name.valid, ast_channel_connected(c)->id.name.str, "<unknown>"),
3456                         ast_channel_accountcode(c),
3457                         ast_channel_state(c),
3458                         ast_state2str(ast_channel_state(c)), ast_channel_context(c),
3459                         ast_channel_exten(c), ast_channel_priority(c), (long)elapsed_seconds, bridge, ast_channel_uniqueid(c), ast_str_buffer(str), idText);
3460                 } else {
3461                         astman_append(s,
3462                                 "Event: Status\r\n"
3463                                 "Privilege: Call\r\n"
3464                                 "Channel: %s\r\n"
3465                                 "CallerIDNum: %s\r\n"
3466                                 "CallerIDName: %s\r\n"
3467                                 "ConnectedLineNum: %s\r\n"
3468                                 "ConnectedLineName: %s\r\n"
3469                                 "Account: %s\r\n"
3470                                 "State: %s\r\n"
3471                                 "%s"
3472                                 "Uniqueid: %s\r\n"
3473                                 "%s"
3474                                 "%s"
3475                                 "\r\n",
3476                                 ast_channel_name(c),
3477                                 S_COR(ast_channel_caller(c)->id.number.valid, ast_channel_caller(c)->id.number.str, "<unknown>"),
3478                                 S_COR(ast_channel_caller(c)->id.name.valid, ast_channel_caller(c)->id.name.str, "<unknown>"),
3479                                 S_COR(ast_channel_connected(c)->id.number.valid, ast_channel_connected(c)->id.number.str, "<unknown>"),
3480                                 S_COR(ast_channel_connected(c)->id.name.valid, ast_channel_connected(c)->id.name.str, "<unknown>"),
3481                                 ast_channel_accountcode(c),
3482                                 ast_state2str(ast_channel_state(c)), bridge, ast_channel_uniqueid(c),
3483                                 ast_str_buffer(str), idText);
3484                 }
3485
3486                 ast_channel_unlock(c);
3487                 c = ast_channel_unref(c);
3488
3489 &n