Add IPv6 address support to security events framework.
[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 void report_invalid_user(const struct mansession *s, const char *username)
2182 {
2183         struct ast_sockaddr addr_remote;
2184         char session_id[32];
2185         struct ast_security_event_inval_acct_id inval_acct_id = {
2186                 .common.event_type = AST_SECURITY_EVENT_INVAL_ACCT_ID,
2187                 .common.version    = AST_SECURITY_EVENT_INVAL_ACCT_ID_VERSION,
2188                 .common.service    = "AMI",
2189                 .common.account_id = username,
2190                 .common.session_tv = &s->session->sessionstart_tv,
2191                 .common.local_addr = {
2192                         .addr      = &s->tcptls_session->parent->local_address,
2193                         .transport = mansession_get_transport(s),
2194                 },
2195                 .common.remote_addr = {
2196                         .addr      = &addr_remote,
2197                         .transport = mansession_get_transport(s),
2198                 },
2199                 .common.session_id = session_id,
2200         };
2201
2202         ast_sockaddr_from_sin(&addr_remote, &s->session->sin);
2203
2204         snprintf(session_id, sizeof(session_id), "%p", s);
2205
2206         ast_security_event_report(AST_SEC_EVT(&inval_acct_id));
2207 }
2208
2209 static void report_failed_acl(const struct mansession *s, const char *username)
2210 {
2211         struct ast_sockaddr addr_remote;
2212         char session_id[32];
2213         struct ast_security_event_failed_acl failed_acl_event = {
2214                 .common.event_type = AST_SECURITY_EVENT_FAILED_ACL,
2215                 .common.version    = AST_SECURITY_EVENT_FAILED_ACL_VERSION,
2216                 .common.service    = "AMI",
2217                 .common.account_id = username,
2218                 .common.session_tv = &s->session->sessionstart_tv,
2219                 .common.local_addr = {
2220                         .addr      = &s->tcptls_session->parent->local_address,
2221                         .transport = mansession_get_transport(s),
2222                 },
2223                 .common.remote_addr = {
2224                         .addr      = &addr_remote,
2225                         .transport = mansession_get_transport(s),
2226                 },
2227                 .common.session_id = session_id,
2228         };
2229
2230         ast_sockaddr_from_sin(&addr_remote, &s->session->sin);
2231
2232         snprintf(session_id, sizeof(session_id), "%p", s->session);
2233
2234         ast_security_event_report(AST_SEC_EVT(&failed_acl_event));
2235 }
2236
2237 static void report_inval_password(const struct mansession *s, const char *username)
2238 {
2239         struct ast_sockaddr addr_remote;
2240         char session_id[32];
2241         struct ast_security_event_inval_password inval_password = {
2242                 .common.event_type = AST_SECURITY_EVENT_INVAL_PASSWORD,
2243                 .common.version    = AST_SECURITY_EVENT_INVAL_PASSWORD_VERSION,
2244                 .common.service    = "AMI",
2245                 .common.account_id = username,
2246                 .common.session_tv = &s->session->sessionstart_tv,
2247                 .common.local_addr = {
2248                         .addr      = &s->tcptls_session->parent->local_address,
2249                         .transport = mansession_get_transport(s),
2250                 },
2251                 .common.remote_addr = {
2252                         .addr      = &addr_remote,
2253                         .transport = mansession_get_transport(s),
2254                 },
2255                 .common.session_id = session_id,
2256         };
2257
2258         ast_sockaddr_from_sin(&addr_remote, &s->session->sin);
2259
2260         snprintf(session_id, sizeof(session_id), "%p", s->session);
2261
2262         ast_security_event_report(AST_SEC_EVT(&inval_password));
2263 }
2264
2265 static void report_auth_success(const struct mansession *s)
2266 {
2267         struct ast_sockaddr addr_remote;
2268         char session_id[32];
2269         struct ast_security_event_successful_auth successful_auth = {
2270                 .common.event_type = AST_SECURITY_EVENT_SUCCESSFUL_AUTH,
2271                 .common.version    = AST_SECURITY_EVENT_SUCCESSFUL_AUTH_VERSION,
2272                 .common.service    = "AMI",
2273                 .common.account_id = s->session->username,
2274                 .common.session_tv = &s->session->sessionstart_tv,
2275                 .common.local_addr = {
2276                         .addr      = &s->tcptls_session->parent->local_address,
2277                         .transport = mansession_get_transport(s),
2278                 },
2279                 .common.remote_addr = {
2280                         .addr      = &addr_remote,
2281                         .transport = mansession_get_transport(s),
2282                 },
2283                 .common.session_id = session_id,
2284         };
2285
2286         ast_sockaddr_from_sin(&addr_remote, &s->session->sin);
2287
2288         snprintf(session_id, sizeof(session_id), "%p", s->session);
2289
2290         ast_security_event_report(AST_SEC_EVT(&successful_auth));
2291 }
2292
2293 static void report_req_not_allowed(const struct mansession *s, const char *action)
2294 {
2295         struct ast_sockaddr addr_remote;
2296         char session_id[32];
2297         char request_type[64];
2298         struct ast_security_event_req_not_allowed req_not_allowed = {
2299                 .common.event_type = AST_SECURITY_EVENT_REQ_NOT_ALLOWED,
2300                 .common.version    = AST_SECURITY_EVENT_REQ_NOT_ALLOWED_VERSION,
2301                 .common.service    = "AMI",
2302                 .common.account_id = s->session->username,
2303                 .common.session_tv = &s->session->sessionstart_tv,
2304                 .common.local_addr = {
2305                         .addr      = &s->tcptls_session->parent->local_address,
2306                         .transport = mansession_get_transport(s),
2307                 },
2308                 .common.remote_addr = {
2309                         .addr      = &addr_remote,
2310                         .transport = mansession_get_transport(s),
2311                 },
2312                 .common.session_id = session_id,
2313
2314                 .request_type      = request_type,
2315         };
2316
2317         ast_sockaddr_from_sin(&addr_remote, &s->session->sin);
2318
2319         snprintf(session_id, sizeof(session_id), "%p", s->session);
2320         snprintf(request_type, sizeof(request_type), "Action: %s", action);
2321
2322         ast_security_event_report(AST_SEC_EVT(&req_not_allowed));
2323 }
2324
2325 static void report_req_bad_format(const struct mansession *s, const char *action)
2326 {
2327         struct ast_sockaddr addr_remote;
2328         char session_id[32];
2329         char request_type[64];
2330         struct ast_security_event_req_bad_format req_bad_format = {
2331                 .common.event_type = AST_SECURITY_EVENT_REQ_BAD_FORMAT,
2332                 .common.version    = AST_SECURITY_EVENT_REQ_BAD_FORMAT_VERSION,
2333                 .common.service    = "AMI",
2334                 .common.account_id = s->session->username,
2335                 .common.session_tv = &s->session->sessionstart_tv,
2336                 .common.local_addr = {
2337                         .addr      = &s->tcptls_session->parent->local_address,
2338                         .transport = mansession_get_transport(s),
2339                 },
2340                 .common.remote_addr = {
2341                         .addr      = &addr_remote,
2342                         .transport = mansession_get_transport(s),
2343                 },
2344                 .common.session_id = session_id,
2345
2346                 .request_type      = request_type,
2347         };
2348
2349         ast_sockaddr_from_sin(&addr_remote, &s->session->sin);
2350
2351         snprintf(session_id, sizeof(session_id), "%p", s->session);
2352         snprintf(request_type, sizeof(request_type), "Action: %s", action);
2353
2354         ast_security_event_report(AST_SEC_EVT(&req_bad_format));
2355 }
2356
2357 static void report_failed_challenge_response(const struct mansession *s,
2358                 const char *response, const char *expected_response)
2359 {
2360         struct ast_sockaddr addr_remote;
2361         char session_id[32];
2362         struct ast_security_event_chal_resp_failed chal_resp_failed = {
2363                 .common.event_type = AST_SECURITY_EVENT_CHAL_RESP_FAILED,
2364                 .common.version    = AST_SECURITY_EVENT_CHAL_RESP_FAILED_VERSION,
2365                 .common.service    = "AMI",
2366                 .common.account_id = s->session->username,
2367                 .common.session_tv = &s->session->sessionstart_tv,
2368                 .common.local_addr = {
2369                         .addr      = &s->tcptls_session->parent->local_address,
2370                         .transport = mansession_get_transport(s),
2371                 },
2372                 .common.remote_addr = {
2373                         .addr      = &addr_remote,
2374                         .transport = mansession_get_transport(s),
2375                 },
2376                 .common.session_id = session_id,
2377
2378                 .challenge         = s->session->challenge,
2379                 .response          = response,
2380                 .expected_response = expected_response,
2381         };
2382
2383         ast_sockaddr_from_sin(&addr_remote, &s->session->sin);
2384
2385         snprintf(session_id, sizeof(session_id), "%p", s->session);
2386
2387         ast_security_event_report(AST_SEC_EVT(&chal_resp_failed));
2388 }
2389
2390 static void report_session_limit(const struct mansession *s)
2391 {
2392         struct ast_sockaddr addr_remote;
2393         char session_id[32];
2394         struct ast_security_event_session_limit session_limit = {
2395                 .common.event_type = AST_SECURITY_EVENT_SESSION_LIMIT,
2396                 .common.version    = AST_SECURITY_EVENT_SESSION_LIMIT_VERSION,
2397                 .common.service    = "AMI",
2398                 .common.account_id = s->session->username,
2399                 .common.session_tv = &s->session->sessionstart_tv,
2400                 .common.local_addr = {
2401                         .addr      = &s->tcptls_session->parent->local_address,
2402                         .transport = mansession_get_transport(s),
2403                 },
2404                 .common.remote_addr = {
2405                         .addr      = &addr_remote,
2406                         .transport = mansession_get_transport(s),
2407                 },
2408                 .common.session_id = session_id,
2409         };
2410
2411         ast_sockaddr_from_sin(&addr_remote, &s->session->sin);
2412
2413         snprintf(session_id, sizeof(session_id), "%p", s->session);
2414
2415         ast_security_event_report(AST_SEC_EVT(&session_limit));
2416 }
2417
2418 /*
2419  * Here we start with action_ handlers for AMI actions,
2420  * and the internal functions used by them.
2421  * Generally, the handlers are called action_foo()
2422  */
2423
2424 /* helper function for action_login() */
2425 static int authenticate(struct mansession *s, const struct message *m)
2426 {
2427         const char *username = astman_get_header(m, "Username");
2428         const char *password = astman_get_header(m, "Secret");
2429         int error = -1;
2430         struct ast_manager_user *user = NULL;
2431         regex_t *regex_filter;
2432         struct ao2_iterator filter_iter;
2433         struct ast_sockaddr addr;
2434
2435         if (ast_strlen_zero(username)) {        /* missing username */
2436                 return -1;
2437         }
2438
2439         /* locate user in locked state */
2440         AST_RWLIST_WRLOCK(&users);
2441
2442         ast_sockaddr_from_sin(&addr, &s->session->sin);
2443
2444         if (!(user = get_manager_by_name_locked(username))) {
2445                 report_invalid_user(s, username);
2446                 ast_log(LOG_NOTICE, "%s tried to authenticate with nonexistent user '%s'\n", ast_inet_ntoa(s->session->sin.sin_addr), username);
2447         } else if (user->ha && !ast_apply_ha(user->ha, &addr)) {
2448                 report_failed_acl(s, username);
2449                 ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", ast_inet_ntoa(s->session->sin.sin_addr), username);
2450         } else if (!strcasecmp(astman_get_header(m, "AuthType"), "MD5")) {
2451                 const char *key = astman_get_header(m, "Key");
2452                 if (!ast_strlen_zero(key) && !ast_strlen_zero(s->session->challenge) && user->secret) {
2453                         int x;
2454                         int len = 0;
2455                         char md5key[256] = "";
2456                         struct MD5Context md5;
2457                         unsigned char digest[16];
2458
2459                         MD5Init(&md5);
2460                         MD5Update(&md5, (unsigned char *) s->session->challenge, strlen(s->session->challenge));
2461                         MD5Update(&md5, (unsigned char *) user->secret, strlen(user->secret));
2462                         MD5Final(digest, &md5);
2463                         for (x = 0; x < 16; x++)
2464                                 len += sprintf(md5key + len, "%2.2x", digest[x]);
2465                         if (!strcmp(md5key, key)) {
2466                                 error = 0;
2467                         } else {
2468                                 report_failed_challenge_response(s, key, md5key);
2469                         }
2470                 } else {
2471                         ast_debug(1, "MD5 authentication is not possible.  challenge: '%s'\n",
2472                                 S_OR(s->session->challenge, ""));
2473                 }
2474         } else if (user->secret) {
2475                 if (!strcmp(password, user->secret)) {
2476                         error = 0;
2477                 } else {
2478                         report_inval_password(s, username);
2479                 }
2480         }
2481
2482         if (error) {
2483                 ast_log(LOG_NOTICE, "%s failed to authenticate as '%s'\n", ast_inet_ntoa(s->session->sin.sin_addr), username);
2484                 AST_RWLIST_UNLOCK(&users);
2485                 return -1;
2486         }
2487
2488         /* auth complete */
2489
2490         /* All of the user parameters are copied to the session so that in the event
2491         * of a reload and a configuration change, the session parameters are not
2492         * changed. */
2493         ast_copy_string(s->session->username, username, sizeof(s->session->username));
2494         s->session->readperm = user->readperm;
2495         s->session->writeperm = user->writeperm;
2496         s->session->writetimeout = user->writetimeout;
2497
2498         filter_iter = ao2_iterator_init(user->whitefilters, 0);
2499         while ((regex_filter = ao2_iterator_next(&filter_iter))) {
2500                 ao2_t_link(s->session->whitefilters, regex_filter, "add white user filter to session");
2501                 ao2_t_ref(regex_filter, -1, "remove iterator ref");
2502         }
2503         ao2_iterator_destroy(&filter_iter);
2504
2505         filter_iter = ao2_iterator_init(user->blackfilters, 0);
2506         while ((regex_filter = ao2_iterator_next(&filter_iter))) {
2507                 ao2_t_link(s->session->blackfilters, regex_filter, "add black user filter to session");
2508                 ao2_t_ref(regex_filter, -1, "remove iterator ref");
2509         }
2510         ao2_iterator_destroy(&filter_iter);
2511
2512         s->session->sessionstart = time(NULL);
2513         s->session->sessionstart_tv = ast_tvnow();
2514         set_eventmask(s, astman_get_header(m, "Events"));
2515
2516         report_auth_success(s);
2517
2518         AST_RWLIST_UNLOCK(&users);
2519         return 0;
2520 }
2521
2522 static int action_ping(struct mansession *s, const struct message *m)
2523 {
2524         const char *actionid = astman_get_header(m, "ActionID");
2525         struct timeval now = ast_tvnow();
2526
2527         astman_append(s, "Response: Success\r\n");
2528         if (!ast_strlen_zero(actionid)){
2529                 astman_append(s, "ActionID: %s\r\n", actionid);
2530         }
2531         astman_append(
2532                 s,
2533                 "Ping: Pong\r\n"
2534                 "Timestamp: %ld.%06lu\r\n"
2535                 "\r\n",
2536                 (long) now.tv_sec, (unsigned long) now.tv_usec);
2537         return 0;
2538 }
2539
2540 static int action_getconfig(struct mansession *s, const struct message *m)
2541 {
2542         struct ast_config *cfg;
2543         const char *fn = astman_get_header(m, "Filename");
2544         const char *category = astman_get_header(m, "Category");
2545         int catcount = 0;
2546         int lineno = 0;
2547         char *cur_category = NULL;
2548         struct ast_variable *v;
2549         struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2550
2551         if (ast_strlen_zero(fn)) {
2552                 astman_send_error(s, m, "Filename not specified");
2553                 return 0;
2554         }
2555         cfg = ast_config_load2(fn, "manager", config_flags);
2556         if (cfg == CONFIG_STATUS_FILEMISSING) {
2557                 astman_send_error(s, m, "Config file not found");
2558                 return 0;
2559         } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2560                 astman_send_error(s, m, "Config file has invalid format");
2561                 return 0;
2562         }
2563
2564         astman_start_ack(s, m);
2565         while ((cur_category = ast_category_browse(cfg, cur_category))) {
2566                 if (ast_strlen_zero(category) || (!ast_strlen_zero(category) && !strcmp(category, cur_category))) {
2567                         lineno = 0;
2568                         astman_append(s, "Category-%06d: %s\r\n", catcount, cur_category);
2569                         for (v = ast_variable_browse(cfg, cur_category); v; v = v->next) {
2570                                 astman_append(s, "Line-%06d-%06d: %s=%s\r\n", catcount, lineno++, v->name, v->value);
2571                         }
2572                         catcount++;
2573                 }
2574         }
2575         if (!ast_strlen_zero(category) && catcount == 0) { /* TODO: actually, a config with no categories doesn't even get loaded */
2576                 astman_append(s, "No categories found\r\n");
2577         }
2578         ast_config_destroy(cfg);
2579         astman_append(s, "\r\n");
2580
2581         return 0;
2582 }
2583
2584 static int action_listcategories(struct mansession *s, const struct message *m)
2585 {
2586         struct ast_config *cfg;
2587         const char *fn = astman_get_header(m, "Filename");
2588         char *category = NULL;
2589         struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2590         int catcount = 0;
2591
2592         if (ast_strlen_zero(fn)) {
2593                 astman_send_error(s, m, "Filename not specified");
2594                 return 0;
2595         }
2596         if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
2597                 astman_send_error(s, m, "Config file not found");
2598                 return 0;
2599         } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2600                 astman_send_error(s, m, "Config file has invalid format");
2601                 return 0;
2602         }
2603         astman_start_ack(s, m);
2604         while ((category = ast_category_browse(cfg, category))) {
2605                 astman_append(s, "Category-%06d: %s\r\n", catcount, category);
2606                 catcount++;
2607         }
2608         if (catcount == 0) { /* TODO: actually, a config with no categories doesn't even get loaded */
2609                 astman_append(s, "Error: no categories found\r\n");
2610         }
2611         ast_config_destroy(cfg);
2612         astman_append(s, "\r\n");
2613
2614         return 0;
2615 }
2616
2617
2618
2619
2620 /*! The amount of space in out must be at least ( 2 * strlen(in) + 1 ) */
2621 static void json_escape(char *out, const char *in)
2622 {
2623         for (; *in; in++) {
2624                 if (*in == '\\' || *in == '\"') {
2625                         *out++ = '\\';
2626                 }
2627                 *out++ = *in;
2628         }
2629         *out = '\0';
2630 }
2631
2632 /*!
2633  * \internal
2634  * \brief Append a JSON escaped string to the manager stream.
2635  *
2636  * \param s AMI stream to append a string.
2637  * \param str String to append to the stream after JSON escaping it.
2638  *
2639  * \return Nothing
2640  */
2641 static void astman_append_json(struct mansession *s, const char *str)
2642 {
2643         char *buf;
2644
2645         buf = alloca(2 * strlen(str) + 1);
2646         json_escape(buf, str);
2647         astman_append(s, "%s", buf);
2648 }
2649
2650 static int action_getconfigjson(struct mansession *s, const struct message *m)
2651 {
2652         struct ast_config *cfg;
2653         const char *fn = astman_get_header(m, "Filename");
2654         char *category = NULL;
2655         struct ast_variable *v;
2656         int comma1 = 0;
2657         struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2658
2659         if (ast_strlen_zero(fn)) {
2660                 astman_send_error(s, m, "Filename not specified");
2661                 return 0;
2662         }
2663
2664         if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
2665                 astman_send_error(s, m, "Config file not found");
2666                 return 0;
2667         } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2668                 astman_send_error(s, m, "Config file has invalid format");
2669                 return 0;
2670         }
2671
2672         astman_start_ack(s, m);
2673         astman_append(s, "JSON: {");
2674         while ((category = ast_category_browse(cfg, category))) {
2675                 int comma2 = 0;
2676
2677                 astman_append(s, "%s\"", comma1 ? "," : "");
2678                 astman_append_json(s, category);
2679                 astman_append(s, "\":[");
2680                 comma1 = 1;
2681                 for (v = ast_variable_browse(cfg, category); v; v = v->next) {
2682                         astman_append(s, "%s\"", comma2 ? "," : "");
2683                         astman_append_json(s, v->name);
2684                         astman_append(s, "\":\"");
2685                         astman_append_json(s, v->value);
2686                         astman_append(s, "\"");
2687                         comma2 = 1;
2688                 }
2689                 astman_append(s, "]");
2690         }
2691         astman_append(s, "}\r\n\r\n");
2692
2693         ast_config_destroy(cfg);
2694
2695         return 0;
2696 }
2697
2698 /*! \brief helper function for action_updateconfig */
2699 static enum error_type handle_updates(struct mansession *s, const struct message *m, struct ast_config *cfg, const char *dfn)
2700 {
2701         int x;
2702         char hdr[40];
2703         const char *action, *cat, *var, *value, *match, *line;
2704         struct ast_category *category;
2705         struct ast_variable *v;
2706         struct ast_str *str1 = ast_str_create(16), *str2 = ast_str_create(16);
2707         enum error_type result = 0;
2708
2709         for (x = 0; x < 100000; x++) {  /* 100000 = the max number of allowed updates + 1 */
2710                 unsigned int object = 0;
2711
2712                 snprintf(hdr, sizeof(hdr), "Action-%06d", x);
2713                 action = astman_get_header(m, hdr);
2714                 if (ast_strlen_zero(action))            /* breaks the for loop if no action header */
2715                         break;                          /* this could cause problems if actions come in misnumbered */
2716
2717                 snprintf(hdr, sizeof(hdr), "Cat-%06d", x);
2718                 cat = astman_get_header(m, hdr);
2719                 if (ast_strlen_zero(cat)) {             /* every action needs a category */
2720                         result =  UNSPECIFIED_CATEGORY;
2721                         break;
2722                 }
2723
2724                 snprintf(hdr, sizeof(hdr), "Var-%06d", x);
2725                 var = astman_get_header(m, hdr);
2726
2727                 snprintf(hdr, sizeof(hdr), "Value-%06d", x);
2728                 value = astman_get_header(m, hdr);
2729
2730                 if (!ast_strlen_zero(value) && *value == '>') {
2731                         object = 1;
2732                         value++;
2733                 }
2734
2735                 snprintf(hdr, sizeof(hdr), "Match-%06d", x);
2736                 match = astman_get_header(m, hdr);
2737
2738                 snprintf(hdr, sizeof(hdr), "Line-%06d", x);
2739                 line = astman_get_header(m, hdr);
2740
2741                 if (!strcasecmp(action, "newcat")) {
2742                         if (ast_category_get(cfg,cat)) {        /* check to make sure the cat doesn't */
2743                                 result = FAILURE_NEWCAT;        /* already exist */
2744                                 break;
2745                         }
2746                         if (!(category = ast_category_new(cat, dfn, -1))) {
2747                                 result = FAILURE_ALLOCATION;
2748                                 break;
2749                         }
2750                         if (ast_strlen_zero(match)) {
2751                                 ast_category_append(cfg, category);
2752                         } else {
2753                                 ast_category_insert(cfg, category, match);
2754                         }
2755                 } else if (!strcasecmp(action, "renamecat")) {
2756                         if (ast_strlen_zero(value)) {
2757                                 result = UNSPECIFIED_ARGUMENT;
2758                                 break;
2759                         }
2760                         if (!(category = ast_category_get(cfg, cat))) {
2761                                 result = UNKNOWN_CATEGORY;
2762                                 break;
2763                         }
2764                         ast_category_rename(category, value);
2765                 } else if (!strcasecmp(action, "delcat")) {
2766                         if (ast_category_delete(cfg, cat)) {
2767                                 result = FAILURE_DELCAT;
2768                                 break;
2769                         }
2770                 } else if (!strcasecmp(action, "emptycat")) {
2771                         if (ast_category_empty(cfg, cat)) {
2772                                 result = FAILURE_EMPTYCAT;
2773                                 break;
2774                         }
2775                 } else if (!strcasecmp(action, "update")) {
2776                         if (ast_strlen_zero(var)) {
2777                                 result = UNSPECIFIED_ARGUMENT;
2778                                 break;
2779                         }
2780                         if (!(category = ast_category_get(cfg,cat))) {
2781                                 result = UNKNOWN_CATEGORY;
2782                                 break;
2783                         }
2784                         if (ast_variable_update(category, var, value, match, object)) {
2785                                 result = FAILURE_UPDATE;
2786                                 break;
2787                         }
2788                 } else if (!strcasecmp(action, "delete")) {
2789                         if ((ast_strlen_zero(var) && ast_strlen_zero(line))) {
2790                                 result = UNSPECIFIED_ARGUMENT;
2791                                 break;
2792                         }
2793                         if (!(category = ast_category_get(cfg, cat))) {
2794                                 result = UNKNOWN_CATEGORY;
2795                                 break;
2796                         }
2797                         if (ast_variable_delete(category, var, match, line)) {
2798                                 result = FAILURE_DELETE;
2799                                 break;
2800                         }
2801                 } else if (!strcasecmp(action, "append")) {
2802                         if (ast_strlen_zero(var)) {
2803                                 result = UNSPECIFIED_ARGUMENT;
2804                                 break;
2805                         }
2806                         if (!(category = ast_category_get(cfg, cat))) {
2807                                 result = UNKNOWN_CATEGORY;
2808                                 break;
2809                         }
2810                         if (!(v = ast_variable_new(var, value, dfn))) {
2811                                 result = FAILURE_ALLOCATION;
2812                                 break;
2813                         }
2814                         if (object || (match && !strcasecmp(match, "object"))) {
2815                                 v->object = 1;
2816                         }
2817                         ast_variable_append(category, v);
2818                 } else if (!strcasecmp(action, "insert")) {
2819                         if (ast_strlen_zero(var) || ast_strlen_zero(line)) {
2820                                 result = UNSPECIFIED_ARGUMENT;
2821                                 break;
2822                         }
2823                         if (!(category = ast_category_get(cfg, cat))) {
2824                                 result = UNKNOWN_CATEGORY;
2825                                 break;
2826                         }
2827                         if (!(v = ast_variable_new(var, value, dfn))) {
2828                                 result = FAILURE_ALLOCATION;
2829                                 break;
2830                         }
2831                         ast_variable_insert(category, v, line);
2832                 }
2833                 else {
2834                         ast_log(LOG_WARNING, "Action-%06d: %s not handled\n", x, action);
2835                         result = UNKNOWN_ACTION;
2836                         break;
2837                 }
2838         }
2839         ast_free(str1);
2840         ast_free(str2);
2841         return result;
2842 }
2843
2844 static int action_updateconfig(struct mansession *s, const struct message *m)
2845 {
2846         struct ast_config *cfg;
2847         const char *sfn = astman_get_header(m, "SrcFilename");
2848         const char *dfn = astman_get_header(m, "DstFilename");
2849         int res;
2850         const char *rld = astman_get_header(m, "Reload");
2851         struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2852         enum error_type result;
2853
2854         if (ast_strlen_zero(sfn) || ast_strlen_zero(dfn)) {
2855                 astman_send_error(s, m, "Filename not specified");
2856                 return 0;
2857         }
2858         if (!(cfg = ast_config_load2(sfn, "manager", config_flags))) {
2859                 astman_send_error(s, m, "Config file not found");
2860                 return 0;
2861         } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2862                 astman_send_error(s, m, "Config file has invalid format");
2863                 return 0;
2864         }
2865         result = handle_updates(s, m, cfg, dfn);
2866         if (!result) {
2867                 ast_include_rename(cfg, sfn, dfn); /* change the include references from dfn to sfn, so things match up */
2868                 res = ast_config_text_file_save(dfn, cfg, "Manager");
2869                 ast_config_destroy(cfg);
2870                 if (res) {
2871                         astman_send_error(s, m, "Save of config failed");
2872                         return 0;
2873                 }
2874                 astman_send_ack(s, m, NULL);
2875                 if (!ast_strlen_zero(rld)) {
2876                         if (ast_true(rld)) {
2877                                 rld = NULL;
2878                         }
2879                         ast_module_reload(rld);
2880                 }
2881         } else {
2882                 ast_config_destroy(cfg);
2883                 switch(result) {
2884                 case UNKNOWN_ACTION:
2885                         astman_send_error(s, m, "Unknown action command");
2886                         break;
2887                 case UNKNOWN_CATEGORY:
2888                         astman_send_error(s, m, "Given category does not exist");
2889                         break;
2890                 case UNSPECIFIED_CATEGORY:
2891                         astman_send_error(s, m, "Category not specified");
2892                         break;
2893                 case UNSPECIFIED_ARGUMENT:
2894                         astman_send_error(s, m, "Problem with category, value, or line (if required)");
2895                         break;
2896                 case FAILURE_ALLOCATION:
2897                         astman_send_error(s, m, "Memory allocation failure, this should not happen");
2898                         break;
2899                 case FAILURE_NEWCAT:
2900                         astman_send_error(s, m, "Create category did not complete successfully");
2901                         break;
2902                 case FAILURE_DELCAT:
2903                         astman_send_error(s, m, "Delete category did not complete successfully");
2904                         break;
2905                 case FAILURE_EMPTYCAT:
2906                         astman_send_error(s, m, "Empty category did not complete successfully");
2907                         break;
2908                 case FAILURE_UPDATE:
2909                         astman_send_error(s, m, "Update did not complete successfully");
2910                         break;
2911                 case FAILURE_DELETE:
2912                         astman_send_error(s, m, "Delete did not complete successfully");
2913                         break;
2914                 case FAILURE_APPEND:
2915                         astman_send_error(s, m, "Append did not complete successfully");
2916                         break;
2917                 }
2918         }
2919         return 0;
2920 }
2921
2922 static int action_createconfig(struct mansession *s, const struct message *m)
2923 {
2924         int fd;
2925         const char *fn = astman_get_header(m, "Filename");
2926         struct ast_str *filepath = ast_str_alloca(PATH_MAX);
2927         ast_str_set(&filepath, 0, "%s/", ast_config_AST_CONFIG_DIR);
2928         ast_str_append(&filepath, 0, "%s", fn);
2929
2930         if ((fd = open(ast_str_buffer(filepath), O_CREAT | O_EXCL, AST_FILE_MODE)) != -1) {
2931                 close(fd);
2932                 astman_send_ack(s, m, "New configuration file created successfully");
2933         } else {
2934                 astman_send_error(s, m, strerror(errno));
2935         }
2936
2937         return 0;
2938 }
2939
2940 static int action_waitevent(struct mansession *s, const struct message *m)
2941 {
2942         const char *timeouts = astman_get_header(m, "Timeout");
2943         int timeout = -1;
2944         int x;
2945         int needexit = 0;
2946         const char *id = astman_get_header(m, "ActionID");
2947         char idText[256];
2948
2949         if (!ast_strlen_zero(id)) {
2950                 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
2951         } else {
2952                 idText[0] = '\0';
2953         }
2954
2955         if (!ast_strlen_zero(timeouts)) {
2956                 sscanf(timeouts, "%30i", &timeout);
2957                 if (timeout < -1) {
2958                         timeout = -1;
2959                 }
2960                 /* XXX maybe put an upper bound, or prevent the use of 0 ? */
2961         }
2962
2963         ao2_lock(s->session);
2964         if (s->session->waiting_thread != AST_PTHREADT_NULL) {
2965                 pthread_kill(s->session->waiting_thread, SIGURG);
2966         }
2967
2968         if (s->session->managerid) { /* AMI-over-HTTP session */
2969                 /*
2970                  * Make sure the timeout is within the expire time of the session,
2971                  * as the client will likely abort the request if it does not see
2972                  * data coming after some amount of time.
2973                  */
2974                 time_t now = time(NULL);
2975                 int max = s->session->sessiontimeout - now - 10;
2976
2977                 if (max < 0) {  /* We are already late. Strange but possible. */
2978                         max = 0;
2979                 }
2980                 if (timeout < 0 || timeout > max) {
2981                         timeout = max;
2982                 }
2983                 if (!s->session->send_events) { /* make sure we record events */
2984                         s->session->send_events = -1;
2985                 }
2986         }
2987         ao2_unlock(s->session);
2988
2989         /* XXX should this go inside the lock ? */
2990         s->session->waiting_thread = pthread_self();    /* let new events wake up this thread */
2991         ast_debug(1, "Starting waiting for an event!\n");
2992
2993         for (x = 0; x < timeout || timeout < 0; x++) {
2994                 ao2_lock(s->session);
2995                 if (AST_RWLIST_NEXT(s->session->last_ev, eq_next)) {
2996                         needexit = 1;
2997                 }
2998                 /* We can have multiple HTTP session point to the same mansession entry.
2999                  * The way we deal with it is not very nice: newcomers kick out the previous
3000                  * HTTP session. XXX this needs to be improved.
3001                  */
3002                 if (s->session->waiting_thread != pthread_self()) {
3003                         needexit = 1;
3004                 }
3005                 if (s->session->needdestroy) {
3006                         needexit = 1;
3007                 }
3008                 ao2_unlock(s->session);
3009                 if (needexit) {
3010                         break;
3011                 }
3012                 if (s->session->managerid == 0) {       /* AMI session */
3013                         if (ast_wait_for_input(s->session->fd, 1000)) {
3014                                 break;
3015                         }
3016                 } else {        /* HTTP session */
3017                         sleep(1);
3018                 }
3019         }
3020         ast_debug(1, "Finished waiting for an event!\n");
3021
3022         ao2_lock(s->session);
3023         if (s->session->waiting_thread == pthread_self()) {
3024                 struct eventqent *eqe = s->session->last_ev;
3025                 astman_send_response(s, m, "Success", "Waiting for Event completed.");
3026                 while ((eqe = advance_event(eqe))) {
3027                         if (((s->session->readperm & eqe->category) == eqe->category) &&
3028                             ((s->session->send_events & eqe->category) == eqe->category)) {
3029                                 astman_append(s, "%s", eqe->eventdata);
3030                         }
3031                         s->session->last_ev = eqe;
3032                 }
3033                 astman_append(s,
3034                         "Event: WaitEventComplete\r\n"