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