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